test.cc 1016 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. std::vector<std::string> get_ca_names(ctx_t ctx);
  69. } // namespace tls
  70. } // namespace httplib
  71. #endif
  72. using namespace std;
  73. using namespace httplib;
  74. const char *HOST = "localhost";
  75. static int get_base_port() {
  76. const char *shard = getenv("GTEST_SHARD_INDEX");
  77. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  78. }
  79. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  80. // New standalone tests MUST use svr.bind_to_any_port() instead.
  81. const int PORT = get_base_port();
  82. const string LONG_QUERY_VALUE = string(25000, '@');
  83. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  84. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  85. const string TOO_LONG_QUERY_URL =
  86. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  87. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  88. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  89. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  90. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  91. return file.name == key;
  92. });
  93. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  94. return *it;
  95. #else
  96. if (it != items.end()) { return *it; }
  97. throw std::runtime_error("invalid multipart form data name error");
  98. #endif
  99. }
  100. static void read_file(const std::string &path, std::string &out) {
  101. std::ifstream fs(path, std::ios_base::binary);
  102. if (!fs) {
  103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  104. return;
  105. #else
  106. throw std::runtime_error("File not found: " + path);
  107. #endif
  108. }
  109. fs.seekg(0, std::ios_base::end);
  110. auto size = fs.tellg();
  111. fs.seekg(0);
  112. out.resize(static_cast<size_t>(size));
  113. fs.read(&out[0], static_cast<std::streamsize>(size));
  114. }
  115. class UnixSocketTest : public ::testing::Test {
  116. protected:
  117. void TearDown() override { std::remove(pathname_.c_str()); }
  118. void client_GET(const std::string &addr) {
  119. httplib::Client cli{addr};
  120. cli.set_address_family(AF_UNIX);
  121. ASSERT_TRUE(cli.is_valid());
  122. const auto &result = cli.Get(pattern_);
  123. ASSERT_TRUE(result) << "error: " << result.error();
  124. const auto &resp = result.value();
  125. EXPECT_EQ(resp.status, StatusCode::OK_200);
  126. EXPECT_EQ(resp.body, content_);
  127. }
  128. static std::string make_sock_path() {
  129. const char *shard = getenv("GTEST_SHARD_INDEX");
  130. return shard ? std::string("./httplib-server-") + shard + ".sock"
  131. : "./httplib-server.sock";
  132. }
  133. const std::string pathname_{make_sock_path()};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. // ".//x.sock", which is not taken for a URL
  154. client_GET("./" + pathname_.substr(1));
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_TRUE(s0.is_peer_alive());
  247. EXPECT_EQ(0, close(fds[1]));
  248. EXPECT_FALSE(s0.is_peer_alive());
  249. return true;
  250. });
  251. EXPECT_EQ(0, close(fds[0]));
  252. }
  253. TEST(SocketStream, wait_writable_INET) {
  254. sockaddr_in addr;
  255. memset(&addr, 0, sizeof(addr));
  256. addr.sin_family = AF_INET;
  257. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  258. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  259. int disconnected_svr_sock = -1;
  260. std::thread svr{[&] {
  261. const int s = socket(AF_INET, SOCK_STREAM, 0);
  262. ASSERT_LE(0, s);
  263. // PORT + 1 is shared with the SSL redirect tests and with
  264. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  265. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  266. // because that happens on a worker thread the ASSERT does not stop the
  267. // test: it runs on and fails at the disconnected_svr_sock check instead.
  268. default_socket_options(s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. // wait_writable() returns true because select_write() only checks if the
  292. // send buffer has space. Peer disconnection is detected later by send().
  293. EXPECT_TRUE(ss.wait_writable());
  294. return true;
  295. });
  296. ASSERT_EQ(0, close(disconnected_svr_sock));
  297. }
  298. #endif // #ifndef _WIN32
  299. TEST(SetSocketOptTest, TcpNoDelay) {
  300. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  301. ASSERT_NE(sock, INVALID_SOCKET);
  302. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  303. int val = 0;
  304. socklen_t len = sizeof(val);
  305. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  306. reinterpret_cast<char *>(&val), &len));
  307. EXPECT_NE(val, 0);
  308. detail::close_socket(sock);
  309. }
  310. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  311. // accept() reports failures through WSAGetLastError() on Windows and through
  312. // errno everywhere else. Asking the wrong one is what made the accept loop
  313. // treat every recoverable failure as fatal on Windows.
  314. struct Classification {
  315. bool resource;
  316. bool transient;
  317. };
  318. auto classify = [](int err) {
  319. #ifdef _WIN32
  320. WSASetLastError(err);
  321. #else
  322. errno = err;
  323. #endif
  324. // Read both before asserting: an assertion may clobber the error slot.
  325. Classification c;
  326. c.resource = detail::is_accept_resource_error();
  327. c.transient = detail::is_accept_transient_error();
  328. return c;
  329. };
  330. #ifdef _WIN32
  331. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  332. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  333. WSAECONNRESET, WSAECONNABORTED};
  334. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  335. #else
  336. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  337. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  338. ECONNABORTED};
  339. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  340. #endif
  341. for (auto err : resource_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.resource) << "error " << err;
  344. EXPECT_FALSE(c.transient) << "error " << err;
  345. }
  346. for (auto err : transient_errors) {
  347. const auto c = classify(err);
  348. EXPECT_TRUE(c.transient) << "error " << err;
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. }
  351. for (auto err : fatal_errors) {
  352. const auto c = classify(err);
  353. EXPECT_FALSE(c.resource) << "error " << err;
  354. EXPECT_FALSE(c.transient) << "error " << err;
  355. }
  356. #ifdef _WIN32
  357. WSASetLastError(0);
  358. #else
  359. errno = 0;
  360. #endif
  361. }
  362. TEST(ClientTest, MoveConstructible) {
  363. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  365. }
  366. TEST(ClientTest, MoveAssignable) {
  367. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  368. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  369. }
  370. #ifdef _WIN32
  371. TEST(StartupTest, WSAStartup) {
  372. WSADATA wsaData;
  373. int ret = WSAStartup(0x0002, &wsaData);
  374. ASSERT_EQ(0, ret);
  375. }
  376. #endif
  377. TEST(DecodePathTest, PercentCharacter) {
  378. EXPECT_EQ(
  379. decode_path_component(
  380. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  381. U8("descrip=Gastos áéíóúñÑ 6"));
  382. }
  383. TEST(DecodePathTest, PercentCharacterNUL) {
  384. string expected;
  385. expected.push_back('x');
  386. expected.push_back('\0');
  387. expected.push_back('x');
  388. EXPECT_EQ(decode_path_component("x%00x"), expected);
  389. }
  390. TEST(DecodePathTest, UnicodeEncoding) {
  391. // %u0041 = 'A' (1-byte UTF-8)
  392. EXPECT_EQ("A", decode_path_component("%u0041"));
  393. // %u00E9 = 'é' (2-byte UTF-8)
  394. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  395. // %u3042 = 'あ' (3-byte UTF-8)
  396. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  397. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  398. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  399. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  400. // neighbours)
  401. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  402. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  403. }
  404. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  405. // A sign or whitespace inside the two-character escape window must not be
  406. // accepted as a valid percent-encoding; the sequence is passed through
  407. // literally, matching decode_uri_component / decode_path_component.
  408. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  409. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  410. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  411. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  412. // Well-formed escapes still decode.
  413. EXPECT_EQ("-", decode_query_component("%2D", false));
  414. EXPECT_EQ("A", decode_query_component("%41", false));
  415. }
  416. TEST(SanitizeFilenameTest, VariousPatterns) {
  417. // Path traversal
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  420. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  421. // Normal and edge cases
  422. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  423. EXPECT_EQ("filename.txt",
  424. httplib::sanitize_filename("/path/to/filename.txt"));
  425. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  426. EXPECT_EQ("", httplib::sanitize_filename(".."));
  427. EXPECT_EQ("", httplib::sanitize_filename(""));
  428. // Null bytes stripped
  429. EXPECT_EQ("safe.txt",
  430. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  431. // Whitespace-only rejected
  432. EXPECT_EQ("", httplib::sanitize_filename(" "));
  433. }
  434. // Forward declaration (see the base64_encode note below): split builds move the
  435. // definition into httplib.cc, so re-declaring it here lets the test link.
  436. namespace httplib {
  437. namespace detail {
  438. bool is_chunked_transfer_encoding(const Headers &headers);
  439. } // namespace detail
  440. } // namespace httplib
  441. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  442. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  443. auto make = [](std::initializer_list<const char *> lines) {
  444. Headers h;
  445. for (auto te : lines) {
  446. if (te) { h.emplace("Transfer-Encoding", te); }
  447. }
  448. return h;
  449. };
  450. // Sole coding, matched case-insensitively.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  454. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  458. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  463. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  464. // were received, into one list. Headers preserves that order, so the answer
  465. // is decided by the last coding of the last line and the order the lines
  466. // arrived in is significant.
  467. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  470. // The split can fall anywhere in the list.
  471. EXPECT_TRUE(
  472. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  473. EXPECT_FALSE(
  474. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  475. // A trailing line naming no coding leaves the list ending in nothing, so it
  476. // must not inherit the chunked from the line before it.
  477. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  478. }
  479. // Forward declarations (see the base64_encode note below).
  480. namespace httplib {
  481. namespace detail {
  482. bool parse_status_line(const char *line, std::string &version, int &status,
  483. std::string &reason);
  484. std::string file_extension(const std::string &path);
  485. std::string
  486. find_content_type(const std::string &path,
  487. const std::map<std::string, std::string> &user_data,
  488. const std::string &default_content_type);
  489. bool can_compress_content_type(const std::string &content_type);
  490. bool is_prohibited_header_name(const std::string &name);
  491. #ifdef CPPHTTPLIB_SSL_ENABLED
  492. bool match_hostname(const std::string &pattern, const std::string &hostname);
  493. #endif
  494. } // namespace detail
  495. } // namespace httplib
  496. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  497. struct {
  498. const char *line;
  499. const char *version;
  500. int status;
  501. const char *reason;
  502. } cases[] = {
  503. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  504. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  505. // The reason phrase may be empty, or left out along with its space.
  506. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  507. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  508. };
  509. for (const auto &c : cases) {
  510. std::string version;
  511. int status = 0;
  512. std::string reason = "unset";
  513. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  514. << c.line;
  515. EXPECT_EQ(c.version, version);
  516. EXPECT_EQ(c.status, status);
  517. EXPECT_EQ(c.reason, reason);
  518. }
  519. }
  520. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  521. const char *lines[] = {
  522. "HTTP/2 200 OK\r\n",
  523. "HTTP/1.2 200 OK\r\n",
  524. "HTTP/1.1 20 OK\r\n",
  525. "HTTP/1.1 2000 OK\r\n",
  526. "HTTP/1.1 2x0 OK\r\n",
  527. "HTTP/1.1 200 OK\r\n",
  528. "HTTP/1.1 200OK\r\n",
  529. "HTTP/1.1 200 O\rK\r\n",
  530. "HTTP/1.1 200 OK",
  531. "HTTP/1.1 200 OK\r\nX",
  532. "",
  533. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  534. "HTTP/1.1 200 OK\n",
  535. #endif
  536. };
  537. for (auto line : lines) {
  538. std::string version;
  539. int status = 0;
  540. std::string reason;
  541. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  542. << line;
  543. }
  544. }
  545. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  546. // Long enough to overflow the stack when matched with std::regex.
  547. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  548. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  549. std::string version;
  550. int status = 0;
  551. std::string reason;
  552. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  553. EXPECT_EQ(200, status);
  554. EXPECT_EQ(long_reason, reason);
  555. }
  556. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  557. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  558. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  559. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  560. EXPECT_EQ("", detail::file_extension("noext"));
  561. EXPECT_EQ("", detail::file_extension("a."));
  562. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  563. EXPECT_EQ("", detail::file_extension("a.b-c"));
  564. // Long enough to overflow the stack when matched with std::regex.
  565. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  566. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  567. }
  568. #ifdef CPPHTTPLIB_SSL_ENABLED
  569. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  570. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  573. // A wildcard needs two labels after it, in the leftmost label only
  574. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  575. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  576. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  577. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  578. EXPECT_FALSE(
  579. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  580. // No name may have an empty label
  581. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  582. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  583. }
  584. #endif
  585. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  586. detail::case_ignore::hash hash;
  587. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  588. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  589. // Long enough to overflow the stack if hashed one call per character.
  590. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  591. }
  592. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  593. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  594. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  595. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  596. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  597. // Same 26-bit hash as html, svg and js.
  598. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  601. }
  602. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  603. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  604. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  605. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  606. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  607. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  608. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  609. // Same 26-bit hash as application/json.
  610. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  611. }
  612. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  613. Request req;
  614. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  615. EXPECT_TRUE(req.is_multipart_form_data());
  616. std::string boundary;
  617. EXPECT_TRUE(detail::parse_multipart_boundary(
  618. req.get_header_value("Content-Type"), boundary));
  619. EXPECT_EQ("x", boundary);
  620. }
  621. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  622. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  623. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  624. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  625. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  626. // Same 26-bit hash as REMOTE_ADDR.
  627. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  628. }
  629. // Forward declaration: in split builds split.py strips `inline` and moves the
  630. // definition into httplib.cc, so detail::base64_encode is not visible from the
  631. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  632. // in both header-only and split builds.
  633. namespace httplib {
  634. namespace detail {
  635. std::string base64_encode(const std::string &in);
  636. } // namespace detail
  637. } // namespace httplib
  638. TEST(Base64EncodeTest, KnownAnswers) {
  639. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  640. // where the accumulator's top bit is already set before the next shift.
  641. EXPECT_EQ("", detail::base64_encode(""));
  642. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  643. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  644. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  645. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  646. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  647. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  648. // High bytes keep the top bit set across several rounds.
  649. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  650. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  651. }
  652. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  653. string unescapedCharacters = "-_.!~*'()";
  654. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  655. }
  656. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  657. string reservedCharacters = ";,/?:@&=+$";
  658. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  659. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  660. }
  661. TEST(ClientQueryOrder, PreserveOrder) {
  662. // This test reproduces Issue #2259: client may reorder query parameters
  663. // when sending a GET request. The expected behavior is that the client
  664. // preserves the original query string order when the caller supplied it
  665. // as part of the path.
  666. Server svr;
  667. svr.Get("/", [&](const Request &req, Response &res) {
  668. // Echo back the raw target so the test can assert ordering
  669. res.set_content(req.target, "text/plain");
  670. });
  671. std::thread t{[&] { svr.listen(HOST, PORT); }};
  672. auto se = detail::scope_exit([&] {
  673. svr.stop();
  674. t.join();
  675. ASSERT_FALSE(svr.is_running());
  676. });
  677. svr.wait_until_ready();
  678. Client cli(HOST, PORT);
  679. ASSERT_TRUE(cli.is_valid());
  680. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  681. auto res = cli.Get(original);
  682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  683. // Expect the echoed target to exactly match the original path (order
  684. // preserved)
  685. EXPECT_EQ(res->body, original);
  686. }
  687. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  688. string chineseCharacters = U8("中国語");
  689. string russianCharacters = U8("дом");
  690. string brazilianCharacters = U8("óculos");
  691. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  692. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  693. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  694. "%D0%B4%D0%BE%D0%BC");
  695. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  696. }
  697. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  698. string unescapedCharacters = "-_.!~*'()";
  699. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  700. }
  701. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  702. string reservedCharacters = ";,/?:@&=+$";
  703. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  704. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  705. }
  706. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  707. string chineseCharacters = U8("中国語");
  708. string russianCharacters = U8("дом");
  709. string brazilianCharacters = U8("óculos");
  710. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  711. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  712. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  713. "%D0%B4%D0%BE%D0%BC");
  714. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  715. }
  716. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  717. // Issue #2082 use case: encoding path component with ampersand
  718. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  719. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  720. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  721. }
  722. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  723. string unescapedCharacters = "-_.!~*'()";
  724. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  725. }
  726. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  727. string reservedCharacters = ";,/?:@&=+$#";
  728. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  729. }
  730. TEST(EncodeUriTest, TestUTF8Characters) {
  731. string chineseCharacters = U8("中国語");
  732. string russianCharacters = U8("дом");
  733. string brazilianCharacters = U8("óculos");
  734. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  735. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  736. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  737. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  738. }
  739. TEST(EncodeUriTest, TestCompleteUri) {
  740. string uri =
  741. "https://example.com/path/to/resource?query=value&param=test#fragment";
  742. EXPECT_EQ(
  743. httplib::encode_uri(uri),
  744. "https://example.com/path/to/resource?query=value&param=test#fragment");
  745. }
  746. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  747. string uri =
  748. "https://example.com/path with spaces/file name.html?q=hello world";
  749. EXPECT_EQ(httplib::encode_uri(uri),
  750. "https://example.com/path%20with%20spaces/"
  751. "file%20name.html?q=hello%20world");
  752. }
  753. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  754. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  755. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  756. }
  757. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  758. string unescapedCharacters = "-_.!~*'()";
  759. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  760. }
  761. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  762. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  763. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  764. string encodedBrazilian = "%C3%B3culos";
  765. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  767. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  768. }
  769. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  770. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  772. "Piri Tommy Villiers - on & on");
  773. }
  774. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  775. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  776. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  777. }
  778. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  779. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  780. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  781. }
  782. TEST(DecodeUriTest, TestUTF8Characters) {
  783. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  784. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  785. string encodedBrazilian = "%C3%B3culos";
  786. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  787. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  788. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  789. }
  790. TEST(DecodeUriTest, TestCompleteUri) {
  791. string encodedUri = "https://example.com/path%20with%20spaces/"
  792. "file%20name.html?q=hello%20world";
  793. EXPECT_EQ(
  794. httplib::decode_uri(encodedUri),
  795. "https://example.com/path with spaces/file name.html?q=hello world");
  796. }
  797. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  798. string original =
  799. "https://example.com/path with spaces/file name.html?q=hello world";
  800. string encoded = httplib::encode_uri(original);
  801. string decoded = httplib::decode_uri(encoded);
  802. EXPECT_EQ(decoded, original);
  803. }
  804. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  805. // decode_uri is the inverse of encode_uri: an escaped reserved character
  806. // stays encoded so it is not promoted into a real delimiter, while
  807. // non-reserved escapes still decode (like JS decodeURI).
  808. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  809. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  810. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  811. "%3F%3A%40%26%3D%2B%24%2C%3B");
  812. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  813. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  814. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  815. "http://example.com/a%2Fb");
  816. // decode_uri_component still decodes the reserved character.
  817. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  818. }
  819. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  820. string original = "Piri Tommy Villiers - on & on";
  821. string encoded = httplib::encode_uri_component(original);
  822. string decoded = httplib::decode_uri_component(encoded);
  823. EXPECT_EQ(decoded, original);
  824. }
  825. TEST(TrimTests, TrimStringTests) {
  826. EXPECT_EQ("abc", detail::trim_copy("abc"));
  827. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  828. EXPECT_TRUE(detail::trim_copy("").empty());
  829. }
  830. TEST(AsciiTest, LocaleIndependentClassification) {
  831. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  832. // which consult the global C locale: std::isalnum(0xC5) can return true
  833. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  834. // helpers must classify every byte by the ASCII grammar alone.
  835. for (int i = 0; i < 256; i++) {
  836. auto c = static_cast<char>(i);
  837. auto is_digit = i >= '0' && i <= '9';
  838. auto is_upper = i >= 'A' && i <= 'Z';
  839. auto is_lower = i >= 'a' && i <= 'z';
  840. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  841. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  842. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  843. << "byte " << i;
  844. }
  845. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  846. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  847. // Non-ASCII bytes must be percent-encoded, never passed through as
  848. // alphanumeric.
  849. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  850. }
  851. TEST(FromCharsTest, Double) {
  852. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  853. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  854. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  855. auto parse = [](const std::string &s, double &v) {
  856. return detail::from_chars(s.data(), s.data() + s.size(), v);
  857. };
  858. double v = -1.0;
  859. // Representative quality values.
  860. EXPECT_EQ(parse("0", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.0);
  862. EXPECT_EQ(parse("1", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 1.0);
  864. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 0.8);
  866. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.001);
  868. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. // A missing integer or fractional part is tolerated.
  871. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  872. EXPECT_DOUBLE_EQ(v, 0.5);
  873. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 5.0);
  875. // Values outside [0, 1] still parse; the caller range-checks them.
  876. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  877. EXPECT_DOUBLE_EQ(v, 123.456);
  878. // Stops at the first byte that is not part of the number and reports where.
  879. std::string trailing = "0.9, text/html";
  880. auto r = parse(trailing, v);
  881. EXPECT_EQ(r.ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 0.9);
  883. EXPECT_EQ(*r.ptr, ',');
  884. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  885. // outright, and an 'e'/'E' simply ends the number.
  886. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  888. std::string exp_input = "1.5e3";
  889. r = parse(exp_input, v);
  890. EXPECT_EQ(r.ec, std::errc{});
  891. EXPECT_DOUBLE_EQ(v, 1.5);
  892. EXPECT_EQ(*r.ptr, 'e');
  893. // Invalid inputs.
  894. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  898. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  899. // Pathological but well-formed inputs must stay bounded (no overflow, no
  900. // out-of-bounds table access) and stay within [0, 1] for the caller.
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  902. std::errc{});
  903. EXPECT_DOUBLE_EQ(v, 0.0);
  904. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  905. std::errc{});
  906. EXPECT_GE(v, 0.0);
  907. EXPECT_LE(v, 1.0);
  908. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  909. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  910. }
  911. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  912. // Simple case without quality values
  913. std::vector<std::string> result1;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html,application/json,text/plain", result1));
  916. EXPECT_EQ(result1.size(), 3U);
  917. EXPECT_EQ(result1[0], "text/html");
  918. EXPECT_EQ(result1[1], "application/json");
  919. EXPECT_EQ(result1[2], "text/plain");
  920. // With quality values
  921. std::vector<std::string> result2;
  922. EXPECT_TRUE(detail::parse_accept_header(
  923. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  924. EXPECT_EQ(result2.size(), 3U);
  925. EXPECT_EQ(result2[0], "application/json"); // highest q value
  926. EXPECT_EQ(result2[1], "text/html");
  927. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  928. }
  929. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  930. // Mixed with and without quality values
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(
  933. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  934. EXPECT_EQ(result.size(), 3U);
  935. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  936. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  937. EXPECT_EQ(result[2], "application/json"); // q=0.5
  938. }
  939. TEST(ParseAcceptHeaderTest, EdgeCases) {
  940. // Empty header
  941. std::vector<std::string> empty_result;
  942. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  943. EXPECT_TRUE(empty_result.empty());
  944. // Single type
  945. std::vector<std::string> single_result;
  946. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  947. EXPECT_EQ(single_result.size(), 1U);
  948. EXPECT_EQ(single_result[0], "application/json");
  949. // Wildcard types
  950. std::vector<std::string> wildcard_result;
  951. EXPECT_TRUE(detail::parse_accept_header(
  952. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  953. EXPECT_EQ(wildcard_result.size(), 3U);
  954. EXPECT_EQ(wildcard_result[0], "application/json");
  955. EXPECT_EQ(wildcard_result[1], "text/*");
  956. EXPECT_EQ(wildcard_result[2], "*/*");
  957. }
  958. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  959. // Common browser Accept header
  960. std::vector<std::string> browser_result;
  961. EXPECT_TRUE(
  962. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  963. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  964. browser_result));
  965. EXPECT_EQ(browser_result.size(), 6U);
  966. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  970. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  971. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  972. // API client header
  973. std::vector<std::string> api_result;
  974. EXPECT_TRUE(detail::parse_accept_header(
  975. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  976. api_result));
  977. EXPECT_EQ(api_result.size(), 3U);
  978. EXPECT_EQ(api_result[0], "application/json");
  979. EXPECT_EQ(api_result[1], "application/xml");
  980. EXPECT_EQ(api_result[2], "text/plain");
  981. }
  982. TEST(ParseAcceptHeaderTest, SpecialCases) {
  983. // Quality value with 3 decimal places
  984. std::vector<std::string> decimal_result;
  985. EXPECT_TRUE(detail::parse_accept_header(
  986. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  987. EXPECT_EQ(decimal_result.size(), 2U);
  988. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  989. EXPECT_EQ(decimal_result[1], "text/html");
  990. // Zero quality (should still be included but with lowest priority)
  991. std::vector<std::string> zero_q_result;
  992. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  993. zero_q_result));
  994. EXPECT_EQ(zero_q_result.size(), 2U);
  995. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  996. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  997. // No spaces around commas
  998. std::vector<std::string> no_space_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1001. no_space_result));
  1002. EXPECT_EQ(no_space_result.size(), 3U);
  1003. EXPECT_EQ(no_space_result[0], "text/html");
  1004. EXPECT_EQ(no_space_result[1], "application/json");
  1005. EXPECT_EQ(no_space_result[2], "text/plain");
  1006. }
  1007. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1008. // Quality values always use '.' as the decimal separator, so parsing must
  1009. // not depend on the process locale. An embedding application may have
  1010. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1011. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1012. std::string saved = cur ? cur : "C";
  1013. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1014. "fr_FR.UTF-8"};
  1015. bool switched = false;
  1016. for (const auto loc : comma_locales) {
  1017. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1018. std::localeconv()->decimal_point[0] == ',') {
  1019. switched = true;
  1020. break;
  1021. }
  1022. }
  1023. if (!switched) {
  1024. std::setlocale(LC_NUMERIC, saved.c_str());
  1025. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1026. }
  1027. // The higher-weighted type appears later in the list, so a correct parse
  1028. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1029. // sensitive parse reads both weights as 0 and leaves the original order.
  1030. std::vector<std::string> result;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "application/json;q=0.1,text/html;q=0.9", result));
  1033. ASSERT_EQ(result.size(), 2U);
  1034. EXPECT_EQ(result[0], "text/html");
  1035. EXPECT_EQ(result[1], "application/json");
  1036. std::setlocale(LC_NUMERIC, saved.c_str());
  1037. }
  1038. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1039. std::vector<std::string> result;
  1040. // Invalid quality value (> 1.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1043. // Invalid quality value (< 0.0)
  1044. EXPECT_FALSE(
  1045. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1046. // Invalid quality value (not a number)
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=invalid,application/json", result));
  1049. // A valid numeric prefix does not make the entire quality value valid.
  1050. EXPECT_FALSE(detail::parse_accept_header(
  1051. "text/html;q=0.5junk,application/json", result));
  1052. // Empty quality value
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("text/html;q=,application/json", result));
  1055. // Invalid media type format (no slash and not wildcard)
  1056. EXPECT_FALSE(
  1057. detail::parse_accept_header("invalidtype,application/json", result));
  1058. // Valid cases should still work
  1059. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*/*");
  1062. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "*");
  1065. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "text/*");
  1068. }
  1069. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1070. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1071. // and must not be answered with 400 Bad Request.
  1072. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1073. struct {
  1074. const char *value;
  1075. std::vector<std::string> expected;
  1076. } cases[] = {
  1077. {",application/json", {"application/json"}},
  1078. {"text/html,", {"text/html"}},
  1079. {"text/html,,*/*", {"text/html", "*/*"}},
  1080. // An empty element may be spelled with whitespace in it
  1081. {"text/html, , application/json", {"text/html", "application/json"}},
  1082. // Nothing but empty elements is an empty list, which means the same
  1083. // thing as no Accept header at all
  1084. {",,,", {}},
  1085. // Quality values still apply across ignored empty elements
  1086. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1087. };
  1088. for (const auto &c : cases) {
  1089. std::vector<std::string> result;
  1090. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1091. << "value: " << c.value;
  1092. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1093. }
  1094. // An invalid entry is still rejected when empty elements surround it
  1095. std::vector<std::string> result;
  1096. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1097. }
  1098. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1099. // or ';' inside one does not end the list element or the parameter. Section
  1100. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1101. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1102. struct {
  1103. const char *value;
  1104. std::vector<std::string> expected;
  1105. } cases[] = {
  1106. {"text/html;profile=\"a,b\",application/json",
  1107. {"text/html", "application/json"}},
  1108. // A "q=" inside a quoted value is not the weight
  1109. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1110. {"text/html", "application/json"}},
  1111. // The weight after a quoted value still applies
  1112. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1113. {"application/json", "text/html"}},
  1114. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1115. {"application/json", "text/html"}},
  1116. {"text/html;profile=\"a\\\"b\",application/json",
  1117. {"text/html", "application/json"}},
  1118. // An escaped backslash does not escape the '"' after it
  1119. {"text/html;profile=\"a\\\\\",application/json",
  1120. {"text/html", "application/json"}},
  1121. };
  1122. for (const auto &c : cases) {
  1123. std::vector<std::string> result;
  1124. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1125. << "value: " << c.value;
  1126. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1127. }
  1128. }
  1129. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1130. Server svr;
  1131. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1132. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1133. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1134. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1135. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1136. res.set_content("ok", "text/plain");
  1137. });
  1138. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1139. EXPECT_TRUE(false);
  1140. res.set_content("bad request", "text/plain");
  1141. });
  1142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1143. auto se = detail::scope_exit([&] {
  1144. svr.stop();
  1145. listen_thread.join();
  1146. ASSERT_FALSE(svr.is_running());
  1147. });
  1148. svr.wait_until_ready();
  1149. Client cli("localhost", PORT);
  1150. {
  1151. auto res = cli.Get(
  1152. "/accept_ok",
  1153. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. auto res = cli.Get("/accept_bad_request",
  1159. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1162. }
  1163. }
  1164. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1165. Server svr;
  1166. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1167. res.set_content("ok", "text/plain");
  1168. });
  1169. std::atomic<int> start_count{0};
  1170. std::atomic<bool> running_when_called{false};
  1171. svr.set_start_handler([&]() {
  1172. running_when_called = svr.is_running();
  1173. start_count++;
  1174. });
  1175. auto port = svr.bind_to_any_port(HOST);
  1176. std::thread t([&]() { svr.listen_after_bind(); });
  1177. auto se = detail::scope_exit([&] {
  1178. svr.stop();
  1179. t.join();
  1180. ASSERT_FALSE(svr.is_running());
  1181. });
  1182. svr.wait_until_ready();
  1183. // A successful request proves the accept loop is running, which the start
  1184. // handler precedes; so by now the handler must have run exactly once.
  1185. Client cli(HOST, port);
  1186. cli.set_connection_timeout(std::chrono::seconds(5));
  1187. auto res = cli.Get("/");
  1188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1189. EXPECT_EQ(StatusCode::OK_200, res->status);
  1190. EXPECT_EQ(1, start_count.load());
  1191. EXPECT_TRUE(running_when_called.load());
  1192. }
  1193. TEST(DivideTest, DivideStringTests) {
  1194. auto divide = [](const std::string &str, char d) {
  1195. std::string lhs;
  1196. std::string rhs;
  1197. detail::divide(str, d,
  1198. [&](const char *lhs_data, std::size_t lhs_size,
  1199. const char *rhs_data, std::size_t rhs_size) {
  1200. lhs.assign(lhs_data, lhs_size);
  1201. rhs.assign(rhs_data, rhs_size);
  1202. });
  1203. return std::make_pair(std::move(lhs), std::move(rhs));
  1204. };
  1205. {
  1206. const auto res = divide("", '=');
  1207. EXPECT_EQ(res.first, "");
  1208. EXPECT_EQ(res.second, "");
  1209. }
  1210. {
  1211. const auto res = divide("=", '=');
  1212. EXPECT_EQ(res.first, "");
  1213. EXPECT_EQ(res.second, "");
  1214. }
  1215. {
  1216. const auto res = divide(" ", '=');
  1217. EXPECT_EQ(res.first, " ");
  1218. EXPECT_EQ(res.second, "");
  1219. }
  1220. {
  1221. const auto res = divide("a", '=');
  1222. EXPECT_EQ(res.first, "a");
  1223. EXPECT_EQ(res.second, "");
  1224. }
  1225. {
  1226. const auto res = divide("a=", '=');
  1227. EXPECT_EQ(res.first, "a");
  1228. EXPECT_EQ(res.second, "");
  1229. }
  1230. {
  1231. const auto res = divide("=b", '=');
  1232. EXPECT_EQ(res.first, "");
  1233. EXPECT_EQ(res.second, "b");
  1234. }
  1235. {
  1236. const auto res = divide("a=b", '=');
  1237. EXPECT_EQ(res.first, "a");
  1238. EXPECT_EQ(res.second, "b");
  1239. }
  1240. {
  1241. const auto res = divide("a=b=", '=');
  1242. EXPECT_EQ(res.first, "a");
  1243. EXPECT_EQ(res.second, "b=");
  1244. }
  1245. {
  1246. const auto res = divide("a=b=c", '=');
  1247. EXPECT_EQ(res.first, "a");
  1248. EXPECT_EQ(res.second, "b=c");
  1249. }
  1250. }
  1251. TEST(SplitTest, ParseQueryString) {
  1252. string s = "key1=val1&key2=val2&key3=val3";
  1253. Params dic;
  1254. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1255. [&](const char *b, const char *e) {
  1256. string key, val;
  1257. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1258. if (key.empty()) {
  1259. key.assign(b2, e2);
  1260. } else {
  1261. val.assign(b2, e2);
  1262. }
  1263. });
  1264. dic.emplace(key, val);
  1265. });
  1266. EXPECT_EQ("val1", dic.find("key1")->second);
  1267. EXPECT_EQ("val2", dic.find("key2")->second);
  1268. EXPECT_EQ("val3", dic.find("key3")->second);
  1269. }
  1270. TEST(SplitTest, ParseInvalidQueryTests) {
  1271. {
  1272. string s = " ";
  1273. Params dict;
  1274. detail::parse_query_text(s, dict);
  1275. EXPECT_TRUE(dict.empty());
  1276. }
  1277. {
  1278. string s = " = =";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. }
  1284. TEST(ParseQueryTest, ParseQueryString) {
  1285. {
  1286. std::string s = "key1=val1&key2=val2&key3=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("val1", dic.find("key1")->second);
  1290. EXPECT_EQ("val2", dic.find("key2")->second);
  1291. EXPECT_EQ("val3", dic.find("key3")->second);
  1292. }
  1293. {
  1294. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1295. Params dic;
  1296. detail::parse_query_text(s, dic);
  1297. EXPECT_EQ("", dic.find("key1")->second);
  1298. EXPECT_EQ("val1", dic.find("key2")->second);
  1299. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1300. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1301. }
  1302. }
  1303. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1304. Params dic;
  1305. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1306. dic.emplace("key1", "val1");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1308. dic.emplace("key2", "val2");
  1309. dic.emplace("key3", "val3");
  1310. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1311. }
  1312. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1313. Params params;
  1314. params.emplace("a", "1");
  1315. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1316. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1317. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1318. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1319. // Long enough to overflow the stack when matched with std::regex.
  1320. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1321. EXPECT_EQ("/p?" + long_query + "&a=1",
  1322. append_query_params("/p?" + long_query, params));
  1323. }
  1324. // Joins every entry of a Headers or Params into "key=value " so a whole
  1325. // traversal can be compared in one assertion. Both are instantiations of the
  1326. // same insertion-ordered container, so one helper serves both.
  1327. template <typename Map> static std::string entries_to_string(const Map &m) {
  1328. std::string s;
  1329. for (const auto &entry : m) {
  1330. s += entry.first + "=" + entry.second + " ";
  1331. }
  1332. return s;
  1333. }
  1334. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1335. // Params used to be a std::multimap, which sorted by name and handed the
  1336. // caller's query back alphabetised. A client signing its query string could
  1337. // not reproduce the order it asked for.
  1338. Params dic;
  1339. dic.emplace("zulu", "1");
  1340. dic.emplace("alpha", "2");
  1341. dic.emplace("mike", "3");
  1342. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1343. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1344. }
  1345. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1346. Params dic;
  1347. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1349. }
  1350. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1351. Request req;
  1352. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1353. req.params);
  1354. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag"));
  1356. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1357. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1358. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1359. EXPECT_EQ("", req.get_param_value("tag", 3));
  1360. }
  1361. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1362. // Params shares its container with Headers, which matches field names
  1363. // case-insensitively. Parameter names must not pick that up.
  1364. Params dic;
  1365. dic.emplace("Key", "upper");
  1366. dic.emplace("key", "lower");
  1367. EXPECT_EQ(2U, dic.size());
  1368. EXPECT_EQ(1U, dic.count("Key"));
  1369. EXPECT_EQ(1U, dic.count("key"));
  1370. EXPECT_EQ("upper", dic.find("Key")->second);
  1371. EXPECT_EQ("lower", dic.find("key")->second);
  1372. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1373. }
  1374. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1375. Server svr;
  1376. std::string order;
  1377. svr.Get("/order", [&](const Request &req, Response &res) {
  1378. order = entries_to_string(req.params);
  1379. res.set_content("ok", "text/plain");
  1380. });
  1381. auto port = svr.bind_to_any_port(HOST);
  1382. thread t = thread([&] { svr.listen_after_bind(); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. t.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, port);
  1390. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1391. ASSERT_TRUE(res);
  1392. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1393. }
  1394. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1395. Server svr;
  1396. std::string field_order, file_order;
  1397. svr.Post("/order", [&](const Request &req, Response &res) {
  1398. for (const auto &field : req.form.fields) {
  1399. field_order += field.first + "=" + field.second.content + " ";
  1400. }
  1401. for (const auto &file : req.form.files) {
  1402. file_order += file.first + "=" + file.second.filename + " ";
  1403. }
  1404. res.set_content("ok", "text/plain");
  1405. });
  1406. auto port = svr.bind_to_any_port(HOST);
  1407. thread t = thread([&] { svr.listen_after_bind(); });
  1408. auto se = detail::scope_exit([&] {
  1409. svr.stop();
  1410. t.join();
  1411. ASSERT_FALSE(svr.is_running());
  1412. });
  1413. svr.wait_until_ready();
  1414. UploadFormDataItems items = {
  1415. {"zulu", "1", "", ""},
  1416. {"alpha", "2", "", ""},
  1417. {"mike", "3", "", ""},
  1418. {"zebra", "z", "z.txt", "text/plain"},
  1419. {"apple", "a", "a.txt", "text/plain"},
  1420. };
  1421. Client cli(HOST, port);
  1422. auto res = cli.Post("/order", items);
  1423. ASSERT_TRUE(res);
  1424. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1425. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1426. }
  1427. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1428. Server svr;
  1429. std::vector<std::string> values;
  1430. std::string first, second, out_of_range, order;
  1431. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1432. values = req.form.get_fields("tag");
  1433. first = req.form.get_field("tag", 0);
  1434. second = req.form.get_field("tag", 1);
  1435. out_of_range = req.form.get_field("tag", 2);
  1436. for (const auto &field : req.form.fields) {
  1437. order += field.first + "=" + field.second.content + " ";
  1438. }
  1439. res.set_content("ok", "text/plain");
  1440. });
  1441. auto port = svr.bind_to_any_port(HOST);
  1442. thread t = thread([&] { svr.listen_after_bind(); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. t.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1450. // not adjacent in the container.
  1451. UploadFormDataItems items = {
  1452. {"tag", "first", "", ""},
  1453. {"other", "x", "", ""},
  1454. {"tag", "second", "", ""},
  1455. };
  1456. Client cli(HOST, port);
  1457. auto res = cli.Post("/repeated", items);
  1458. ASSERT_TRUE(res);
  1459. ASSERT_EQ(2U, values.size());
  1460. EXPECT_EQ("first", values[0]);
  1461. EXPECT_EQ("second", values[1]);
  1462. EXPECT_EQ("first", first);
  1463. EXPECT_EQ("second", second);
  1464. // std::multimap already kept entries sharing a name in insertion order, so
  1465. // everything above passes without this change too. The whole traversal is
  1466. // what tells the two apart: sorting by name would hoist "other" to the front
  1467. // and the two "tag" parts would end up adjacent.
  1468. EXPECT_EQ("tag=first other=x tag=second ", order);
  1469. // Advancing past the last entry of a name used to run off the container;
  1470. // the container's saturating increment makes it return the default instead.
  1471. EXPECT_EQ("", out_of_range);
  1472. }
  1473. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1474. Server svr;
  1475. std::string file_names;
  1476. svr.Post("/upload", [&](const Request &req, Response &res) {
  1477. for (const auto &file : req.form.files) {
  1478. file_names += file.first + "|" + file.second.filename + " ";
  1479. }
  1480. res.set_content("ok", "text/plain");
  1481. });
  1482. auto port = svr.bind_to_any_port(HOST);
  1483. thread t = thread([&] { svr.listen_after_bind(); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. t.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. // A trailing backslash would otherwise escape the closing quote.
  1491. UploadFormDataItems items = {
  1492. {"dir\\", "x", "a.txt", "text/plain"},
  1493. {"b", "y", "a\\\\b.txt", "text/plain"},
  1494. };
  1495. Client cli(HOST, port);
  1496. auto res = cli.Post("/upload", items);
  1497. ASSERT_TRUE(res);
  1498. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1499. }
  1500. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1501. // Server::read_content() keeps a FormFields::iterator alive across the
  1502. // content callbacks that fill the part it points at. The container is
  1503. // vector-backed, so a later emplace can reallocate and invalidate an older
  1504. // iterator; 64 parts grow the vector through seven reallocations, which
  1505. // checks that every part's content still lands in its own entry.
  1506. const size_t part_count = 64;
  1507. // One formula for both the parts sent and the values expected back, so the
  1508. // two cannot drift apart.
  1509. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1510. auto content_of = [](size_t i) {
  1511. return std::string(64, static_cast<char>('a' + (i % 26)));
  1512. };
  1513. Server svr;
  1514. std::vector<std::pair<std::string, std::string>> received;
  1515. svr.Post("/many", [&](const Request &req, Response &res) {
  1516. for (const auto &field : req.form.fields) {
  1517. received.emplace_back(field.first, field.second.content);
  1518. }
  1519. res.set_content("ok", "text/plain");
  1520. });
  1521. auto port = svr.bind_to_any_port(HOST);
  1522. thread t = thread([&] { svr.listen_after_bind(); });
  1523. auto se = detail::scope_exit([&] {
  1524. svr.stop();
  1525. t.join();
  1526. ASSERT_FALSE(svr.is_running());
  1527. });
  1528. svr.wait_until_ready();
  1529. UploadFormDataItems items;
  1530. for (size_t i = 0; i < part_count; i++) {
  1531. items.push_back({name_of(i), content_of(i), "", ""});
  1532. }
  1533. Client cli(HOST, port);
  1534. auto res = cli.Post("/many", items);
  1535. ASSERT_TRUE(res);
  1536. ASSERT_EQ(part_count, received.size());
  1537. for (size_t i = 0; i < part_count; i++) {
  1538. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1539. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1540. }
  1541. }
  1542. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1543. string content_type = "multipart/form-data; boundary=something";
  1544. string boundary;
  1545. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(boundary, "something");
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1550. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1551. string boundary;
  1552. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1553. EXPECT_TRUE(ret);
  1554. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1557. string content_type =
  1558. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1559. string boundary;
  1560. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1561. EXPECT_TRUE(ret);
  1562. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1565. string content_type =
  1566. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1567. string boundary;
  1568. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1569. EXPECT_TRUE(ret);
  1570. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1571. }
  1572. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1573. const string boundary(70, 'a');
  1574. string content_type = "multipart/form-data; boundary=" + boundary;
  1575. string parsed;
  1576. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1577. EXPECT_TRUE(ret);
  1578. EXPECT_EQ(parsed, boundary);
  1579. }
  1580. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1581. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1582. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1583. string parsed;
  1584. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1585. EXPECT_FALSE(ret);
  1586. }
  1587. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1588. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1589. // is 72 characters on the wire and still valid.
  1590. const string boundary(70, 'a');
  1591. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1592. string parsed;
  1593. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1594. EXPECT_EQ(parsed, boundary);
  1595. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1596. parsed.clear();
  1597. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1598. }
  1599. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1600. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1601. // The parameter parser must not treat that '=' as the key/value separator.
  1602. string content_type =
  1603. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1604. "charset=UTF-8";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1608. }
  1609. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1610. // A ';' inside the quoted-string is part of the value, not a parameter
  1611. // separator, so it must not truncate the boundary.
  1612. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1613. string parsed;
  1614. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1615. EXPECT_EQ(parsed, "a;b");
  1616. }
  1617. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1621. EXPECT_EQ("a\\b", parsed);
  1622. EXPECT_TRUE(detail::parse_multipart_boundary(
  1623. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1624. EXPECT_EQ("a\"b", parsed);
  1625. }
  1626. TEST(ParseDispositionParamsTest, QuotedValues) {
  1627. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1628. // ';' and '=' are ordinary characters inside one.
  1629. struct {
  1630. const char *value;
  1631. std::vector<std::pair<const char *, const char *>> expected;
  1632. } cases[] = {
  1633. {"name=\"file1\"; filename=\"a.txt\"",
  1634. {{"name", "file1"}, {"filename", "a.txt"}}},
  1635. // Whitespace around '=' and ';' is still trimmed
  1636. {"name=\"file2\" ;filename = \"a.html\"",
  1637. {{"name", "file2"}, {"filename", "a.html"}}},
  1638. // '=' inside the value used to leave only the text after the last one
  1639. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1640. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1641. {"name=\"x=y\"", {{"name", "x=y"}}},
  1642. // ';' inside the value used to truncate the pair and leave a bogus one
  1643. {"name=\"file3\"; filename=\"a;b.txt\"",
  1644. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1645. // An unquoted value keeps working, and so does filename*
  1646. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1647. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1648. // A parameter with no key is dropped rather than turned into one whose
  1649. // key is the value
  1650. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1651. // An escaped quote does not end the value
  1652. {"name=\"a\\\"; filename=evil.php\"",
  1653. {{"name", "a\"; filename=evil.php"}}},
  1654. // Other backslashes, as in a Windows path, are kept
  1655. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1656. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1657. };
  1658. for (const auto &c : cases) {
  1659. Params params;
  1660. detail::parse_disposition_params(c.value, params);
  1661. for (const auto &kv : c.expected) {
  1662. auto it = params.find(kv.first);
  1663. ASSERT_NE(it, params.end())
  1664. << "value: " << c.value << ", key: " << kv.first;
  1665. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1666. }
  1667. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1668. }
  1669. }
  1670. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1671. Server svr;
  1672. std::string filename;
  1673. std::string content;
  1674. svr.Post("/upload", [&](const Request &req, Response &) {
  1675. const auto &file = req.form.get_file("file");
  1676. filename = file.filename;
  1677. content = file.content;
  1678. });
  1679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1680. auto se = detail::scope_exit([&] {
  1681. svr.stop();
  1682. thread.join();
  1683. ASSERT_FALSE(svr.is_running());
  1684. });
  1685. svr.wait_until_ready();
  1686. std::string body = "--B\r\n"
  1687. "Content-Disposition: form-data; name=\"file\"; "
  1688. "filename=\"a.txt\"\r\n"
  1689. "Content-Type: text/plain\r\n"
  1690. "\r\n"
  1691. "hello\r\n"
  1692. "--B--\r\n";
  1693. Client cli(HOST, PORT);
  1694. auto res = cli.Post(
  1695. "/upload",
  1696. [&](size_t offset, DataSink &sink) {
  1697. if (offset < body.size()) {
  1698. sink.write(&body[offset], 1);
  1699. } else {
  1700. sink.done();
  1701. }
  1702. return true;
  1703. },
  1704. "multipart/form-data; boundary=B");
  1705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1706. EXPECT_EQ(StatusCode::OK_200, res->status);
  1707. EXPECT_EQ("a.txt", filename);
  1708. EXPECT_EQ("hello", content);
  1709. }
  1710. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1711. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1712. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1713. Server svr;
  1714. std::string field_value, file_name, file_filename;
  1715. bool has_field = false, has_file = false;
  1716. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1717. has_field = req.form.has_field("x=y");
  1718. field_value = req.form.get_field("x=y");
  1719. has_file = req.form.has_file("file1");
  1720. const auto &file = req.form.get_file("file1");
  1721. file_name = file.name;
  1722. file_filename = file.filename;
  1723. res.set_content("ok", "text/plain");
  1724. });
  1725. auto port = svr.bind_to_any_port(HOST);
  1726. thread t = thread([&] { svr.listen_after_bind(); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. t.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. UploadFormDataItems items = {
  1734. {"x=y", "field-value", "", ""},
  1735. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1736. };
  1737. Client cli(HOST, port);
  1738. auto res = cli.Post("/quoted", items);
  1739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1740. ASSERT_EQ(StatusCode::OK_200, res->status);
  1741. EXPECT_TRUE(has_field);
  1742. EXPECT_EQ("field-value", field_value);
  1743. EXPECT_TRUE(has_file);
  1744. EXPECT_EQ("file1", file_name);
  1745. EXPECT_EQ("a;b=report.pdf", file_filename);
  1746. }
  1747. TEST(GetHeaderValueTest, DefaultValue) {
  1748. Headers headers = {{"Dummy", "Dummy"}};
  1749. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1750. EXPECT_STREQ("text/plain", val);
  1751. }
  1752. TEST(GetHeaderValueTest, DefaultValueInt) {
  1753. Headers headers = {{"Dummy", "Dummy"}};
  1754. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1755. EXPECT_EQ(100ull, val);
  1756. }
  1757. TEST(GetHeaderValueTest, RegularValue) {
  1758. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1759. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1760. EXPECT_STREQ("text/html", val);
  1761. }
  1762. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1763. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1764. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1765. EXPECT_STREQ("text/html", val);
  1766. }
  1767. TEST(GetHeaderValueTest, SetContent) {
  1768. Response res;
  1769. res.set_content("html", "text/html");
  1770. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1771. res.set_content("text", "text/plain");
  1772. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1773. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueInt) {
  1776. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1778. EXPECT_EQ(100ull, val);
  1779. }
  1780. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1781. Headers headers = {{"Content-Length", "x"}};
  1782. auto is_invalid_value = false;
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1784. is_invalid_value);
  1785. EXPECT_EQ(0ull, val);
  1786. EXPECT_TRUE(is_invalid_value);
  1787. }
  1788. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1789. // An all-digit value that overflows size_t must be reported as invalid, not
  1790. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1791. // a large length to a small one on 32-bit builds, leaving the framing length
  1792. // wrong while is_invalid_value stayed false.
  1793. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1794. auto is_invalid_value = false;
  1795. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1796. is_invalid_value);
  1797. EXPECT_TRUE(is_invalid_value);
  1798. // A well-formed length is unaffected.
  1799. Headers ok = {{"Content-Length", "1234"}};
  1800. is_invalid_value = false;
  1801. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_EQ(1234ull, val);
  1804. EXPECT_FALSE(is_invalid_value);
  1805. }
  1806. TEST(GetHeaderValueTest, Range) {
  1807. {
  1808. Headers headers = {make_range_header({{1, -1}})};
  1809. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1810. EXPECT_STREQ("bytes=1-", val);
  1811. }
  1812. {
  1813. Headers headers = {make_range_header({{-1, 1}})};
  1814. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1815. EXPECT_STREQ("bytes=-1", val);
  1816. }
  1817. {
  1818. Headers headers = {make_range_header({{1, 10}})};
  1819. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1820. EXPECT_STREQ("bytes=1-10", val);
  1821. }
  1822. {
  1823. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1824. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1825. EXPECT_STREQ("bytes=1-10, 100-", val);
  1826. }
  1827. {
  1828. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1829. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1830. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1831. }
  1832. {
  1833. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1834. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1835. EXPECT_STREQ("bytes=0-0, -1", val);
  1836. }
  1837. }
  1838. TEST(BearerTokenAuthTest, SchemeValidation) {
  1839. // A value shorter than "Bearer " must not throw from the fixed-length
  1840. // substr, and a non-Bearer scheme must not be reported as a token.
  1841. struct {
  1842. const char *value;
  1843. const char *expected;
  1844. } cases[] = {
  1845. {"x", ""},
  1846. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1847. {"Bearer abc123", "abc123"},
  1848. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1849. };
  1850. for (const auto &c : cases) {
  1851. Request req;
  1852. req.set_header("Authorization", c.value);
  1853. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1854. }
  1855. }
  1856. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1857. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1858. // to depend on the standard library (libstdc++ handed back duplicates in
  1859. // reverse insertion order, libc++ in insertion order).
  1860. Request req;
  1861. req.set_header("Accept-Encoding", "gzip");
  1862. req.set_header("Accept-Encoding", "deflate");
  1863. req.set_header("Accept-Encoding", "br");
  1864. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1866. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1867. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1868. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1869. }
  1870. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1871. Request req;
  1872. req.set_header("X-Test", "only");
  1873. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1875. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1876. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1877. }
  1878. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1879. Request req;
  1880. req.set_header("X-First", "1");
  1881. req.set_header("X-Test", "2");
  1882. req.params.emplace("first", "1");
  1883. req.params.emplace("test", "2");
  1884. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1885. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1886. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1887. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1888. // The second one is negative when read as a signed value
  1889. const auto max_id = (std::numeric_limits<size_t>::max)();
  1890. for (auto id : {max_id / 2, max_id}) {
  1891. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1892. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1893. EXPECT_EQ("", req.get_param_value("test", id));
  1894. EXPECT_EQ("", req.form.get_field("test", id));
  1895. EXPECT_EQ("", req.form.get_file("test", id).content);
  1896. }
  1897. }
  1898. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1899. Headers headers;
  1900. headers.emplace("Host", "example.com");
  1901. headers.emplace("Accept-Encoding", "gzip");
  1902. headers.emplace("User-Agent", "test");
  1903. headers.emplace("Accept-Encoding", "deflate");
  1904. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1905. "Accept-Encoding=deflate ",
  1906. entries_to_string(headers));
  1907. }
  1908. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1909. Headers headers = {{"Content-Type", "text/html"},
  1910. {"CONTENT-TYPE", "text/xml"}};
  1911. EXPECT_EQ(2U, headers.count("content-type"));
  1912. auto it = headers.find("content-type");
  1913. ASSERT_TRUE(it != headers.end());
  1914. EXPECT_EQ("text/html", it->second);
  1915. }
  1916. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1917. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1918. // drop only those fields and leave everything positioned between them.
  1919. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1920. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1921. auto rng = headers.equal_range("a");
  1922. headers.erase(rng.first, rng.second);
  1923. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1924. }
  1925. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1926. Headers headers = {
  1927. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1928. EXPECT_EQ(3U, headers.erase("A"));
  1929. EXPECT_EQ(0U, headers.count("A"));
  1930. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1933. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1934. headers.emplace_front("Host", "example.com");
  1935. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1936. entries_to_string(headers));
  1937. }
  1938. TEST(ParseHeaderValueTest, Range) {
  1939. {
  1940. Ranges ranges;
  1941. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1944. }
  1945. {
  1946. Ranges ranges;
  1947. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1948. EXPECT_TRUE(ret);
  1949. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1960. EXPECT_FALSE(ret);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1965. EXPECT_TRUE(ret);
  1966. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret =
  1971. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1990. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1991. EXPECT_FALSE(
  1992. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1993. EXPECT_TRUE(ranges.empty());
  1994. }
  1995. {
  1996. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1997. // remainder of the representation, so it stays accepted.
  1998. Ranges ranges;
  1999. auto ret =
  2000. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2001. EXPECT_TRUE(ret);
  2002. ASSERT_EQ(1u, ranges.size());
  2003. EXPECT_EQ(0, ranges[0].first);
  2004. EXPECT_EQ(-1, ranges[0].second);
  2005. }
  2006. // RFC 9110 14.1: range unit names are case-insensitive.
  2007. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2008. Ranges ranges;
  2009. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2010. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2011. }
  2012. }
  2013. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding", "gzip");
  2016. Response res;
  2017. res.set_header("Content-Type", "text/plain");
  2018. auto ret = detail::encoding_type(req, res);
  2019. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2020. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2021. #else
  2022. EXPECT_TRUE(ret == detail::EncodingType::None);
  2023. #endif
  2024. }
  2025. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2033. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2034. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2035. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2036. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2037. #else
  2038. EXPECT_TRUE(ret == detail::EncodingType::None);
  2039. #endif
  2040. }
  2041. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2042. Request req;
  2043. req.set_header("Accept-Encoding",
  2044. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2045. Response res;
  2046. res.set_header("Content-Type", "text/plain");
  2047. auto ret = detail::encoding_type(req, res);
  2048. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2050. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2052. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2053. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2054. #else
  2055. EXPECT_TRUE(ret == detail::EncodingType::None);
  2056. #endif
  2057. }
  2058. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2059. // All supported encodings rejected with q=0 should return None
  2060. Request req;
  2061. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2062. Response res;
  2063. res.set_header("Content-Type", "text/plain");
  2064. auto ret = detail::encoding_type(req, res);
  2065. EXPECT_TRUE(ret == detail::EncodingType::None);
  2066. }
  2067. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2068. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2069. Request req;
  2070. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2071. Response res;
  2072. res.set_header("Content-Type", "text/plain");
  2073. auto ret = detail::encoding_type(req, res);
  2074. EXPECT_TRUE(ret == detail::EncodingType::None);
  2075. }
  2076. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2077. Request req;
  2078. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2079. Response res;
  2080. res.set_header("Content-Type", "text/plain");
  2081. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2082. }
  2083. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2084. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2085. Request req;
  2086. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2087. Response res;
  2088. res.set_header("Content-Type", "text/plain");
  2089. auto ret = detail::encoding_type(req, res);
  2090. EXPECT_TRUE(ret == detail::EncodingType::None);
  2091. }
  2092. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2093. // RFC 7231: Accept-Encoding values are case-insensitive
  2094. Request req;
  2095. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2096. Response res;
  2097. res.set_header("Content-Type", "text/plain");
  2098. auto ret = detail::encoding_type(req, res);
  2099. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2100. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2101. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2102. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2103. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2104. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2105. #else
  2106. EXPECT_TRUE(ret == detail::EncodingType::None);
  2107. #endif
  2108. }
  2109. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2110. // q value should determine priority, not hardcoded order
  2111. Request req;
  2112. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2113. Response res;
  2114. res.set_header("Content-Type", "text/plain");
  2115. auto ret = detail::encoding_type(req, res);
  2116. // gzip has highest q=1.0, so it should be selected even though
  2117. // br and zstd are also supported
  2118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2120. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2121. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2122. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2123. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2124. #else
  2125. EXPECT_TRUE(ret == detail::EncodingType::None);
  2126. #endif
  2127. }
  2128. TEST(BufferStreamTest, read) {
  2129. detail::BufferStream strm1;
  2130. Stream &strm = strm1;
  2131. EXPECT_EQ(5, strm.write("hello"));
  2132. char buf[512];
  2133. EXPECT_EQ(2, strm.read(buf, 2));
  2134. EXPECT_EQ('h', buf[0]);
  2135. EXPECT_EQ('e', buf[1]);
  2136. EXPECT_EQ(2, strm.read(buf, 2));
  2137. EXPECT_EQ('l', buf[0]);
  2138. EXPECT_EQ('l', buf[1]);
  2139. EXPECT_EQ(1, strm.read(buf, 1));
  2140. EXPECT_EQ('o', buf[0]);
  2141. EXPECT_EQ(0, strm.read(buf, 1));
  2142. }
  2143. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2144. auto host = "www.httpwatch.com";
  2145. auto ip = hosted_at(host);
  2146. EXPECT_EQ("23.96.13.243", ip);
  2147. std::vector<std::string> addrs;
  2148. hosted_at(host, addrs);
  2149. EXPECT_EQ(1u, addrs.size());
  2150. }
  2151. #if 0 // It depends on each test environment...
  2152. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2153. auto host = "www.youtube.com";
  2154. std::vector<std::string> addrs;
  2155. hosted_at(host, addrs);
  2156. EXPECT_EQ(20u, addrs.size());
  2157. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2158. EXPECT_TRUE(it != addrs.end());
  2159. }
  2160. #endif
  2161. class ChunkedEncodingTest : public ::testing::Test {
  2162. protected:
  2163. ChunkedEncodingTest()
  2164. : cli_(HOST, PORT)
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. ,
  2167. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2168. #endif
  2169. {
  2170. cli_.set_connection_timeout(2);
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. cli_.enable_server_certificate_verification(false);
  2173. #endif
  2174. }
  2175. virtual void SetUp() {
  2176. read_file("./image.jpg", image_data_);
  2177. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2178. res.set_content("Hello World!", "text/plain");
  2179. });
  2180. svr_.Get(
  2181. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2182. res.set_chunked_content_provider(
  2183. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2184. size_t remaining = image_data_.size() - offset;
  2185. if (remaining == 0) {
  2186. sink.done();
  2187. } else {
  2188. constexpr size_t CHUNK_SIZE = 1024;
  2189. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2190. sink.write(&image_data_[offset], send_size);
  2191. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2192. }
  2193. return true;
  2194. });
  2195. });
  2196. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2197. svr_.wait_until_ready();
  2198. }
  2199. virtual void TearDown() {
  2200. svr_.stop();
  2201. if (!request_threads_.empty()) {
  2202. std::this_thread::sleep_for(std::chrono::seconds(1));
  2203. for (auto &t : request_threads_) {
  2204. t.join();
  2205. }
  2206. }
  2207. t_.join();
  2208. }
  2209. #ifdef CPPHTTPLIB_SSL_ENABLED
  2210. SSLClient cli_;
  2211. SSLServer svr_;
  2212. #else
  2213. Client cli_;
  2214. Server svr_;
  2215. #endif
  2216. thread t_;
  2217. std::vector<thread> request_threads_;
  2218. std::string image_data_;
  2219. };
  2220. TEST_F(ChunkedEncodingTest, NormalGet) {
  2221. auto res = cli_.Get("/chunked");
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. std::string out;
  2224. read_file("./image.jpg", out);
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(out, res->body);
  2227. }
  2228. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2229. std::string body;
  2230. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2231. body.append(data, data_length);
  2232. return true;
  2233. });
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get(
  2243. "/chunked",
  2244. [&](const Response &response) {
  2245. EXPECT_EQ(StatusCode::OK_200, response.status);
  2246. return true;
  2247. },
  2248. [&](const char *data, size_t data_length) {
  2249. body.append(data, data_length);
  2250. return true;
  2251. });
  2252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2253. std::string out;
  2254. read_file("./image.jpg", out);
  2255. EXPECT_EQ(StatusCode::OK_200, res->status);
  2256. EXPECT_EQ(out, body);
  2257. }
  2258. TEST(RangeTest, FromHTTPBin_Online) {
  2259. auto host = "httpbingo.org";
  2260. auto path = std::string{"/range/32"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(5);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. }
  2275. {
  2276. Headers headers = {make_range_header({{1, -1}})};
  2277. auto res = cli.Get(path, headers);
  2278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2279. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2281. }
  2282. {
  2283. Headers headers = {make_range_header({{1, 10}})};
  2284. auto res = cli.Get(path, headers);
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("bcdefghijk", res->body);
  2287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2288. }
  2289. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2290. // entire resource, while the original httpbin returned 200. Both are
  2291. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2292. {
  2293. Headers headers = {make_range_header({{0, 31}})};
  2294. auto res = cli.Get(path, headers);
  2295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2296. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2297. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2298. res->status == StatusCode::PartialContent_206);
  2299. }
  2300. {
  2301. Headers headers = {make_range_header({{0, -1}})};
  2302. auto res = cli.Get(path, headers);
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2305. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2306. res->status == StatusCode::PartialContent_206);
  2307. }
  2308. // go-httpbin returns 206 with clamped range for over-range requests,
  2309. // while the original httpbin returned 416. Both behaviors are observed
  2310. // in real servers, so we only verify the request succeeds.
  2311. {
  2312. Headers headers = {make_range_header({{0, 32}})};
  2313. auto res = cli.Get(path, headers);
  2314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2315. }
  2316. }
  2317. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2318. auto host = "unresolvableaddress.local";
  2319. auto path = std::string{"/"};
  2320. #ifdef CPPHTTPLIB_SSL_ENABLED
  2321. auto port = 443;
  2322. SSLClient cli(host, port);
  2323. #else
  2324. auto port = 80;
  2325. Client cli(host, port);
  2326. #endif
  2327. cli.set_connection_timeout(1);
  2328. {
  2329. auto res = cli.Get(path);
  2330. ASSERT_FALSE(res);
  2331. }
  2332. std::this_thread::sleep_for(std::chrono::seconds(8));
  2333. }
  2334. #if defined(__linux__) && defined(__GLIBC__) && \
  2335. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2336. // Forward declaration: in split builds split.py strips `inline` and moves the
  2337. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2338. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2339. // against the symbol in both header-only and split builds.
  2340. namespace httplib {
  2341. namespace detail {
  2342. int getaddrinfo_with_timeout(const char *node, const char *service,
  2343. const struct addrinfo *hints,
  2344. struct addrinfo **res, time_t timeout_sec);
  2345. } // namespace detail
  2346. } // namespace httplib
  2347. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2348. //
  2349. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2350. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2351. // gai_suspend() call hits the connection timeout the function calls
  2352. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2353. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2354. // still alive and still references the now-destroyed stack frame.
  2355. //
  2356. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2357. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2358. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2359. // and runs them in a container.
  2360. namespace {
  2361. bool should_run_issue_2431_tests() {
  2362. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2363. return v && *v && std::string(v) != "0";
  2364. }
  2365. std::string unique_unresolvable_host(int n) {
  2366. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2367. // glibc still asks the configured nameserver — which is exactly the path
  2368. // we want to exercise. A unique label per call avoids the resolver cache.
  2369. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2370. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2371. std::to_string(n) + ".invalid";
  2372. }
  2373. } // namespace
  2374. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2375. if (!should_run_issue_2431_tests()) {
  2376. GTEST_SKIP()
  2377. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2378. }
  2379. for (int i = 0; i < 8; ++i) {
  2380. struct addrinfo hints;
  2381. memset(&hints, 0, sizeof(hints));
  2382. hints.ai_family = AF_UNSPEC;
  2383. hints.ai_socktype = SOCK_STREAM;
  2384. auto host = unique_unresolvable_host(i);
  2385. struct addrinfo *result = nullptr;
  2386. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2387. &result, /*timeout_sec=*/1);
  2388. if (rc == 0 && result) { freeaddrinfo(result); }
  2389. }
  2390. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2391. // stack region they still believe holds their gaicb.
  2392. std::this_thread::sleep_for(std::chrono::seconds(3));
  2393. }
  2394. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2395. if (!should_run_issue_2431_tests()) {
  2396. GTEST_SKIP()
  2397. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2398. }
  2399. std::atomic<bool> stop{false};
  2400. std::vector<std::thread> threads;
  2401. for (int t = 0; t < 8; ++t) {
  2402. threads.emplace_back([t, &stop] {
  2403. int i = 0;
  2404. while (!stop.load(std::memory_order_relaxed)) {
  2405. struct addrinfo hints;
  2406. memset(&hints, 0, sizeof(hints));
  2407. hints.ai_family = AF_UNSPEC;
  2408. hints.ai_socktype = SOCK_STREAM;
  2409. auto host = unique_unresolvable_host(t * 100000 + i++);
  2410. struct addrinfo *result = nullptr;
  2411. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2412. &result, /*timeout_sec=*/1);
  2413. if (rc == 0 && result) { freeaddrinfo(result); }
  2414. }
  2415. });
  2416. }
  2417. std::this_thread::sleep_for(std::chrono::seconds(8));
  2418. stop.store(true, std::memory_order_relaxed);
  2419. for (auto &th : threads) {
  2420. th.join();
  2421. }
  2422. std::this_thread::sleep_for(std::chrono::seconds(3));
  2423. }
  2424. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2425. if (!should_run_issue_2431_tests()) {
  2426. GTEST_SKIP()
  2427. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2428. }
  2429. std::atomic<bool> stop{false};
  2430. std::vector<std::thread> threads;
  2431. for (int t = 0; t < 8; ++t) {
  2432. threads.emplace_back([t, &stop] {
  2433. int i = 0;
  2434. while (!stop.load(std::memory_order_relaxed)) {
  2435. auto host = unique_unresolvable_host(t * 100000 + i++);
  2436. Client cli(host, 80);
  2437. cli.set_connection_timeout(1, 0);
  2438. cli.set_read_timeout(1, 0);
  2439. cli.set_write_timeout(1, 0);
  2440. (void)cli.Get("/");
  2441. }
  2442. });
  2443. }
  2444. std::this_thread::sleep_for(std::chrono::seconds(8));
  2445. stop.store(true, std::memory_order_relaxed);
  2446. for (auto &th : threads) {
  2447. th.join();
  2448. }
  2449. std::this_thread::sleep_for(std::chrono::seconds(3));
  2450. }
  2451. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2452. TEST(ConnectionErrorTest, InvalidHost) {
  2453. auto host = "-abcde.com";
  2454. #ifdef CPPHTTPLIB_SSL_ENABLED
  2455. auto port = 443;
  2456. SSLClient cli(host, port);
  2457. #else
  2458. auto port = 80;
  2459. Client cli(host, port);
  2460. #endif
  2461. cli.set_connection_timeout(std::chrono::seconds(2));
  2462. auto res = cli.Get("/");
  2463. ASSERT_TRUE(!res);
  2464. EXPECT_EQ(Error::Connection, res.error());
  2465. }
  2466. TEST(ConnectionErrorTest, InvalidHost2) {
  2467. auto host = "httpcan.org/";
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. SSLClient cli(host);
  2470. #else
  2471. Client cli(host);
  2472. #endif
  2473. cli.set_connection_timeout(std::chrono::seconds(2));
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(!res);
  2476. EXPECT_EQ(Error::Connection, res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2479. auto host = "httpcan.org/";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. SSLClient cli(host);
  2482. #else
  2483. Client cli(host);
  2484. #endif
  2485. cli.set_connection_timeout(std::chrono::seconds(2));
  2486. auto res = cli.Get("/");
  2487. ASSERT_TRUE(!res);
  2488. stringstream s;
  2489. s << "error code: " << res.error();
  2490. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2491. }
  2492. TEST(ConnectionErrorTest, InvalidPort) {
  2493. auto host = "localhost";
  2494. auto port = 44380;
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host, port);
  2497. #else
  2498. Client cli(host, port);
  2499. #endif
  2500. cli.set_connection_timeout(std::chrono::seconds(2));
  2501. auto res = cli.Get("/");
  2502. ASSERT_TRUE(!res);
  2503. EXPECT_TRUE(Error::Connection == res.error() ||
  2504. Error::ConnectionTimeout == res.error());
  2505. }
  2506. TEST(ConnectionErrorTest, Timeout_Online) {
  2507. auto host = "google.com";
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. auto port = 44380;
  2510. SSLClient cli(host, port);
  2511. #else
  2512. auto port = 8080;
  2513. Client cli(host, port);
  2514. #endif
  2515. cli.set_connection_timeout(std::chrono::seconds(2));
  2516. // only probe one address type so that the error reason
  2517. // correlates to the timed-out IPv4, not the unsupported
  2518. // IPv6 connection attempt
  2519. cli.set_address_family(AF_INET);
  2520. auto res = cli.Get("/");
  2521. ASSERT_TRUE(!res);
  2522. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2523. }
  2524. TEST(CancelTest, NoCancel_Online) {
  2525. auto host = "httpbingo.org";
  2526. auto path = std::string{"/range/32"};
  2527. #ifdef CPPHTTPLIB_SSL_ENABLED
  2528. auto port = 443;
  2529. SSLClient cli(host, port);
  2530. #else
  2531. auto port = 80;
  2532. Client cli(host, port);
  2533. #endif
  2534. cli.set_connection_timeout(std::chrono::seconds(5));
  2535. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2537. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2538. EXPECT_EQ(StatusCode::OK_200, res->status);
  2539. }
  2540. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2541. // Use /bytes with a large payload so that the DownloadProgress callback
  2542. // (which only fires for Content-Length responses) is invoked before the
  2543. // entire body is received, giving cancellation a chance to fire.
  2544. auto host = "httpbingo.org";
  2545. auto path = std::string{"/bytes/524288"};
  2546. #ifdef CPPHTTPLIB_SSL_ENABLED
  2547. auto port = 443;
  2548. SSLClient cli(host, port);
  2549. #else
  2550. auto port = 80;
  2551. Client cli(host, port);
  2552. #endif
  2553. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2554. cli.set_connection_timeout(std::chrono::seconds(5));
  2555. ASSERT_TRUE(!res);
  2556. EXPECT_EQ(Error::Canceled, res.error());
  2557. }
  2558. TEST(CancelTest, WithCancelLargePayload_Online) {
  2559. auto host = "httpbingo.org";
  2560. auto path = std::string{"/bytes/524288"};
  2561. #ifdef CPPHTTPLIB_SSL_ENABLED
  2562. auto port = 443;
  2563. SSLClient cli(host, port);
  2564. #else
  2565. auto port = 80;
  2566. Client cli(host, port);
  2567. #endif
  2568. cli.set_connection_timeout(std::chrono::seconds(5));
  2569. uint32_t count = 0;
  2570. auto res =
  2571. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2572. ASSERT_TRUE(!res);
  2573. EXPECT_EQ(Error::Canceled, res.error());
  2574. }
  2575. TEST(CancelTest, NoCancelPost) {
  2576. Server svr;
  2577. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2578. res.set_content("Hello World!", "text/plain");
  2579. });
  2580. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2581. auto se = detail::scope_exit([&] {
  2582. svr.stop();
  2583. thread.join();
  2584. ASSERT_FALSE(svr.is_running());
  2585. });
  2586. svr.wait_until_ready();
  2587. Client cli(HOST, PORT);
  2588. cli.set_connection_timeout(std::chrono::seconds(5));
  2589. auto res =
  2590. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2591. "application/json", [](uint64_t, uint64_t) { return true; });
  2592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2593. EXPECT_EQ("Hello World!", res->body);
  2594. EXPECT_EQ(StatusCode::OK_200, res->status);
  2595. }
  2596. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2597. Server svr;
  2598. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2599. res.set_content("Hello World!", "text/plain");
  2600. });
  2601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2602. auto se = detail::scope_exit([&] {
  2603. svr.stop();
  2604. thread.join();
  2605. ASSERT_FALSE(svr.is_running());
  2606. });
  2607. svr.wait_until_ready();
  2608. Client cli(HOST, PORT);
  2609. cli.set_connection_timeout(std::chrono::seconds(5));
  2610. auto res =
  2611. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2612. "application/json", [](uint64_t, uint64_t) { return false; });
  2613. ASSERT_TRUE(!res);
  2614. EXPECT_EQ(Error::Canceled, res.error());
  2615. }
  2616. TEST(CancelTest, WithCancelLargePayloadPost) {
  2617. Server svr;
  2618. svr.set_payload_max_length(200 * 1024 * 1024);
  2619. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2620. res.set_content(LARGE_DATA, "text/plain");
  2621. });
  2622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2623. auto se = detail::scope_exit([&] {
  2624. svr.stop();
  2625. thread.join();
  2626. ASSERT_FALSE(svr.is_running());
  2627. });
  2628. svr.wait_until_ready();
  2629. Client cli(HOST, PORT);
  2630. cli.set_payload_max_length(200 * 1024 * 1024);
  2631. cli.set_connection_timeout(std::chrono::seconds(5));
  2632. auto res =
  2633. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2634. "application/json", [](uint64_t, uint64_t) { return false; });
  2635. ASSERT_TRUE(!res);
  2636. EXPECT_EQ(Error::Canceled, res.error());
  2637. }
  2638. TEST(CancelTest, NoCancelPut) {
  2639. Server svr;
  2640. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2641. res.set_content("Hello World!", "text/plain");
  2642. });
  2643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2644. auto se = detail::scope_exit([&] {
  2645. svr.stop();
  2646. thread.join();
  2647. ASSERT_FALSE(svr.is_running());
  2648. });
  2649. svr.wait_until_ready();
  2650. Client cli(HOST, PORT);
  2651. cli.set_connection_timeout(std::chrono::seconds(5));
  2652. auto res =
  2653. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2654. "application/json", [](uint64_t, uint64_t) { return true; });
  2655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2656. EXPECT_EQ("Hello World!", res->body);
  2657. EXPECT_EQ(StatusCode::OK_200, res->status);
  2658. }
  2659. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2660. Server svr;
  2661. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2662. res.set_content("Hello World!", "text/plain");
  2663. });
  2664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2665. auto se = detail::scope_exit([&] {
  2666. svr.stop();
  2667. thread.join();
  2668. ASSERT_FALSE(svr.is_running());
  2669. });
  2670. svr.wait_until_ready();
  2671. Client cli(HOST, PORT);
  2672. cli.set_connection_timeout(std::chrono::seconds(5));
  2673. auto res =
  2674. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2675. "application/json", [](uint64_t, uint64_t) { return false; });
  2676. ASSERT_TRUE(!res);
  2677. EXPECT_EQ(Error::Canceled, res.error());
  2678. }
  2679. TEST(CancelTest, WithCancelLargePayloadPut) {
  2680. Server svr;
  2681. svr.set_payload_max_length(200 * 1024 * 1024);
  2682. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2683. res.set_content(LARGE_DATA, "text/plain");
  2684. });
  2685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2686. auto se = detail::scope_exit([&] {
  2687. svr.stop();
  2688. thread.join();
  2689. ASSERT_FALSE(svr.is_running());
  2690. });
  2691. svr.wait_until_ready();
  2692. Client cli(HOST, PORT);
  2693. cli.set_payload_max_length(200 * 1024 * 1024);
  2694. cli.set_connection_timeout(std::chrono::seconds(5));
  2695. auto res =
  2696. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2697. "application/json", [](uint64_t, uint64_t) { return false; });
  2698. ASSERT_TRUE(!res);
  2699. EXPECT_EQ(Error::Canceled, res.error());
  2700. }
  2701. TEST(CancelTest, NoCancelPatch) {
  2702. Server svr;
  2703. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content("Hello World!", "text/plain");
  2705. });
  2706. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2707. auto se = detail::scope_exit([&] {
  2708. svr.stop();
  2709. thread.join();
  2710. ASSERT_FALSE(svr.is_running());
  2711. });
  2712. svr.wait_until_ready();
  2713. Client cli(HOST, PORT);
  2714. cli.set_connection_timeout(std::chrono::seconds(5));
  2715. auto res =
  2716. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2717. "application/json", [](uint64_t, uint64_t) { return true; });
  2718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2719. EXPECT_EQ("Hello World!", res->body);
  2720. EXPECT_EQ(StatusCode::OK_200, res->status);
  2721. }
  2722. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2723. Server svr;
  2724. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2725. res.set_content("Hello World!", "text/plain");
  2726. });
  2727. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2728. auto se = detail::scope_exit([&] {
  2729. svr.stop();
  2730. thread.join();
  2731. ASSERT_FALSE(svr.is_running());
  2732. });
  2733. svr.wait_until_ready();
  2734. Client cli(HOST, PORT);
  2735. cli.set_connection_timeout(std::chrono::seconds(5));
  2736. auto res =
  2737. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2738. "application/json", [](uint64_t, uint64_t) { return false; });
  2739. ASSERT_TRUE(!res);
  2740. EXPECT_EQ(Error::Canceled, res.error());
  2741. }
  2742. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2743. Server svr;
  2744. svr.set_payload_max_length(200 * 1024 * 1024);
  2745. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2746. res.set_content(LARGE_DATA, "text/plain");
  2747. });
  2748. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2749. auto se = detail::scope_exit([&] {
  2750. svr.stop();
  2751. thread.join();
  2752. ASSERT_FALSE(svr.is_running());
  2753. });
  2754. svr.wait_until_ready();
  2755. Client cli(HOST, PORT);
  2756. cli.set_payload_max_length(200 * 1024 * 1024);
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. auto res =
  2759. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2760. "application/json", [](uint64_t, uint64_t) { return false; });
  2761. ASSERT_TRUE(!res);
  2762. EXPECT_EQ(Error::Canceled, res.error());
  2763. }
  2764. TEST(CancelTest, NoCancelDelete) {
  2765. Server svr;
  2766. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2767. res.set_content("Hello World!", "text/plain");
  2768. });
  2769. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2770. auto se = detail::scope_exit([&] {
  2771. svr.stop();
  2772. thread.join();
  2773. ASSERT_FALSE(svr.is_running());
  2774. });
  2775. svr.wait_until_ready();
  2776. Client cli(HOST, PORT);
  2777. cli.set_connection_timeout(std::chrono::seconds(5));
  2778. auto res =
  2779. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2780. "application/json", [](uint64_t, uint64_t) { return true; });
  2781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2782. EXPECT_EQ("Hello World!", res->body);
  2783. EXPECT_EQ(StatusCode::OK_200, res->status);
  2784. }
  2785. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2786. Server svr;
  2787. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2788. res.set_content("Hello World!", "text/plain");
  2789. });
  2790. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2791. auto se = detail::scope_exit([&] {
  2792. svr.stop();
  2793. thread.join();
  2794. ASSERT_FALSE(svr.is_running());
  2795. });
  2796. svr.wait_until_ready();
  2797. Client cli(HOST, PORT);
  2798. cli.set_connection_timeout(std::chrono::seconds(5));
  2799. auto res =
  2800. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2801. "application/json", [](uint64_t, uint64_t) { return false; });
  2802. ASSERT_TRUE(!res);
  2803. EXPECT_EQ(Error::Canceled, res.error());
  2804. }
  2805. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2806. Server svr;
  2807. svr.set_payload_max_length(200 * 1024 * 1024);
  2808. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2809. res.set_content(LARGE_DATA, "text/plain");
  2810. });
  2811. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2812. auto se = detail::scope_exit([&] {
  2813. svr.stop();
  2814. thread.join();
  2815. ASSERT_FALSE(svr.is_running());
  2816. });
  2817. svr.wait_until_ready();
  2818. Client cli(HOST, PORT);
  2819. cli.set_payload_max_length(200 * 1024 * 1024);
  2820. cli.set_connection_timeout(std::chrono::seconds(5));
  2821. auto res =
  2822. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2823. "application/json", [](uint64_t, uint64_t) { return false; });
  2824. ASSERT_TRUE(!res);
  2825. EXPECT_EQ(Error::Canceled, res.error());
  2826. }
  2827. static std::string remove_whitespace(const std::string &input) {
  2828. std::string output;
  2829. output.reserve(input.size());
  2830. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2831. [](unsigned char c) { return !std::isspace(c); });
  2832. return output;
  2833. }
  2834. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2835. auto host = "httpbingo.org";
  2836. auto path = std::string{"/basic-auth/hello/world"};
  2837. #ifdef CPPHTTPLIB_SSL_ENABLED
  2838. auto port = 443;
  2839. SSLClient cli(host, port);
  2840. #else
  2841. auto port = 80;
  2842. Client cli(host, port);
  2843. #endif
  2844. {
  2845. auto res = cli.Get(path);
  2846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2848. }
  2849. {
  2850. auto res = cli.Get(
  2851. path, Headers{make_basic_authentication_header("hello", "world")});
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. auto body = remove_whitespace(res->body);
  2854. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2855. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2856. EXPECT_EQ(StatusCode::OK_200, res->status);
  2857. }
  2858. {
  2859. cli.set_basic_auth("hello", "world");
  2860. auto res = cli.Get(path);
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. auto body = remove_whitespace(res->body);
  2863. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2864. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2865. EXPECT_EQ(StatusCode::OK_200, res->status);
  2866. }
  2867. {
  2868. cli.set_basic_auth("hello", "bad");
  2869. auto res = cli.Get(path);
  2870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2871. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2872. }
  2873. {
  2874. cli.set_basic_auth("bad", "world");
  2875. auto res = cli.Get(path);
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2878. }
  2879. }
  2880. #ifdef CPPHTTPLIB_SSL_ENABLED
  2881. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2882. auto host = "httpbingo.org";
  2883. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2884. auto paths = std::vector<std::string>{
  2885. "/digest-auth/auth/hello/world/MD5",
  2886. "/digest-auth/auth/hello/world/SHA-256",
  2887. };
  2888. auto port = 443;
  2889. SSLClient cli(host, port);
  2890. {
  2891. auto res = cli.Get(unauth_path);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2894. }
  2895. {
  2896. cli.set_digest_auth("hello", "world");
  2897. for (const auto &path : paths) {
  2898. auto res = cli.Get(path.c_str());
  2899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2900. auto body = remove_whitespace(res->body);
  2901. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2902. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2903. EXPECT_EQ(StatusCode::OK_200, res->status);
  2904. }
  2905. cli.set_digest_auth("hello", "bad");
  2906. for (const auto &path : paths) {
  2907. auto res = cli.Get(path.c_str());
  2908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2909. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2910. }
  2911. }
  2912. }
  2913. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2914. // comma-separated list of challenges, and each challenge may itself carry a
  2915. // comma-separated auth-param list, so a server can legally offer Basic
  2916. // before Digest, either as two field lines or packed into one. Runs one 401
  2917. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2918. // value() joins them in receipt order) and checks that the retry carries a
  2919. // well-formed Digest Authorization header naming expected_realm.
  2920. static void
  2921. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2922. const std::string &expected_realm) {
  2923. std::atomic<int> hits{0};
  2924. Server svr;
  2925. svr.Get("/x", [&](const Request &req, Response &res) {
  2926. if (++hits == 1) {
  2927. res.status = StatusCode::Unauthorized_401;
  2928. for (const auto &challenge : challenges) {
  2929. res.set_header("WWW-Authenticate", challenge);
  2930. }
  2931. } else {
  2932. auto authorization = req.get_header_value("Authorization");
  2933. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2934. EXPECT_NE(std::string::npos,
  2935. authorization.find("realm=\"" + expected_realm + "\""));
  2936. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2937. res.set_content("ok", "text/plain");
  2938. }
  2939. });
  2940. auto port = svr.bind_to_any_port(HOST);
  2941. std::thread t([&]() { svr.listen_after_bind(); });
  2942. auto se = detail::scope_exit([&] {
  2943. svr.stop();
  2944. t.join();
  2945. });
  2946. svr.wait_until_ready();
  2947. Client cli(HOST, port);
  2948. cli.set_digest_auth("hello", "world");
  2949. auto res = cli.Get("/x");
  2950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2951. EXPECT_EQ(2, hits.load());
  2952. }
  2953. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2954. static const char *kDigestChallenge =
  2955. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2956. "algorithm=MD5";
  2957. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2958. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2959. "testrealm");
  2960. }
  2961. // Same challenge list with the schemes in the opposite order, to make sure
  2962. // the fix above didn't just special-case "Basic first".
  2963. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2964. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2965. "testrealm");
  2966. }
  2967. // A comma inside a quoted auth-param value must not be mistaken for the
  2968. // separator between two challenges (or two auth-params).
  2969. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2970. run_digest_challenge_list_test(
  2971. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2972. "algorithm=MD5"},
  2973. "test,realm");
  2974. }
  2975. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2976. // the params and leaves out the fragment.
  2977. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2978. Server svr;
  2979. std::string uri, target;
  2980. svr.Get("/a b", [&](const Request &req, Response &res) {
  2981. auto auth = req.get_header_value("Authorization");
  2982. if (auth.empty()) {
  2983. res.status = StatusCode::Unauthorized_401;
  2984. res.set_header("WWW-Authenticate",
  2985. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2986. return;
  2987. }
  2988. auto b = auth.find("uri=\"") + 5;
  2989. uri = auth.substr(b, auth.find('"', b) - b);
  2990. target = req.target;
  2991. });
  2992. auto port = svr.bind_to_any_port(HOST);
  2993. std::thread t([&]() { svr.listen_after_bind(); });
  2994. auto se = detail::scope_exit([&] {
  2995. svr.stop();
  2996. t.join();
  2997. });
  2998. svr.wait_until_ready();
  2999. Client cli(HOST, port);
  3000. cli.set_digest_auth("hello", "world");
  3001. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. EXPECT_EQ("/a%20b?x=1", target);
  3004. EXPECT_EQ(target, uri);
  3005. }
  3006. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3007. // make_digest_authentication_header() dereferences both unconditionally, so
  3008. // a server sending a challenge missing either one must not be treated as
  3009. // usable -- doing so used to crash the client with std::out_of_range.
  3010. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3011. Server svr;
  3012. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3013. res.status = StatusCode::Unauthorized_401;
  3014. res.set_header("WWW-Authenticate", challenge);
  3015. });
  3016. auto port = svr.bind_to_any_port(HOST);
  3017. std::thread t([&]() { svr.listen_after_bind(); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. t.join();
  3021. });
  3022. svr.wait_until_ready();
  3023. Client cli(HOST, port);
  3024. cli.set_digest_auth("hello", "world");
  3025. auto res = cli.Get("/x");
  3026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3027. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3028. }
  3029. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3030. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3031. }
  3032. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3033. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3034. }
  3035. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3036. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3037. }
  3038. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3039. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3040. // when storing the values, so the header builder has to re-escape them (and
  3041. // keep algorithm a bare token); otherwise the value breaks out of its
  3042. // quoted-string and injects extra auth-params into the client's Authorization.
  3043. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3044. std::atomic<int> hits{0};
  3045. std::string authorization;
  3046. Server svr;
  3047. svr.Get("/x", [&](const Request &req, Response &res) {
  3048. if (++hits == 1) {
  3049. res.status = StatusCode::Unauthorized_401;
  3050. // On the wire the quotes embedded in the values are backslash-escaped.
  3051. res.set_header("WWW-Authenticate",
  3052. "Digest realm=\"testrealm\", "
  3053. "nonce=\"n\\\"; injected=\\\"x\", "
  3054. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3055. } else {
  3056. authorization = req.get_header_value("Authorization");
  3057. res.set_content("ok", "text/plain");
  3058. }
  3059. });
  3060. auto port = svr.bind_to_any_port(HOST);
  3061. std::thread t([&]() { svr.listen_after_bind(); });
  3062. auto se = detail::scope_exit([&] {
  3063. svr.stop();
  3064. t.join();
  3065. });
  3066. svr.wait_until_ready();
  3067. Client cli(HOST, port);
  3068. cli.set_digest_auth("hello", "world");
  3069. auto res = cli.Get("/x");
  3070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3071. EXPECT_EQ(2, hits.load());
  3072. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3073. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3074. // inside its quoted-string rather than starting an "injected" auth-param.
  3075. EXPECT_NE(std::string::npos,
  3076. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3077. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3078. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3079. }
  3080. #endif
  3081. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3082. auto host = "google.com";
  3083. auto another_host = "example.com";
  3084. auto wrong_ip = "0.0.0.0";
  3085. #ifdef CPPHTTPLIB_SSL_ENABLED
  3086. SSLClient cli(host);
  3087. #else
  3088. Client cli(host);
  3089. #endif
  3090. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3091. auto res = cli.Get("/");
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3094. }
  3095. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3096. auto host = "google.com";
  3097. auto wrong_ip = "0.0.0.0";
  3098. #ifdef CPPHTTPLIB_SSL_ENABLED
  3099. SSLClient cli(host);
  3100. #else
  3101. Client cli(host);
  3102. #endif
  3103. cli.set_hostname_addr_map({{host, wrong_ip}});
  3104. auto res = cli.Get("/");
  3105. ASSERT_TRUE(!res);
  3106. EXPECT_EQ(Error::Connection, res.error());
  3107. }
  3108. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3109. // A mapped value that is not an IP literal must be resolved. "localhost"
  3110. // resolves from the hosts file, so this test needs no external DNS.
  3111. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3112. auto host = "target.invalid";
  3113. Server svr;
  3114. std::string received_host;
  3115. svr.Get("/hi", [&](const Request &req, Response &res) {
  3116. received_host = req.get_header_value("Host");
  3117. res.set_content("Hello World!", "text/plain");
  3118. });
  3119. auto port = svr.bind_to_any_port(HOST);
  3120. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3121. auto se = detail::scope_exit([&] {
  3122. svr.stop();
  3123. thread.join();
  3124. ASSERT_FALSE(svr.is_running());
  3125. });
  3126. svr.wait_until_ready();
  3127. Client cli(host, port);
  3128. cli.set_hostname_addr_map({{host, HOST}});
  3129. auto res = cli.Get("/hi");
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. // The mapping only redirects the connection; the identity stays host_.
  3133. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3134. }
  3135. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3136. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3137. auto host = "target.invalid";
  3138. Server svr;
  3139. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3140. res.set_content("Hello World!", "text/plain");
  3141. });
  3142. auto port = svr.bind_to_any_port("127.0.0.1");
  3143. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3144. auto se = detail::scope_exit([&] {
  3145. svr.stop();
  3146. thread.join();
  3147. ASSERT_FALSE(svr.is_running());
  3148. });
  3149. svr.wait_until_ready();
  3150. Client cli(host, port);
  3151. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3152. auto res = cli.Get("/hi");
  3153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3154. EXPECT_EQ(StatusCode::OK_200, res->status);
  3155. }
  3156. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3157. // An empty mapped value must leave host_ as the connection target. Without
  3158. // that guard the empty value would become the host argument, getaddrinfo
  3159. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3160. // loopback - silently connecting somewhere the caller never asked for.
  3161. // The server listens on loopback, so such a fallback would succeed and is
  3162. // therefore observable as a failure of this test.
  3163. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3164. Server svr;
  3165. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3166. res.set_content("Hello World!", "text/plain");
  3167. });
  3168. auto port = svr.bind_to_any_port(HOST);
  3169. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3170. auto se = detail::scope_exit([&] {
  3171. svr.stop();
  3172. thread.join();
  3173. ASSERT_FALSE(svr.is_running());
  3174. });
  3175. svr.wait_until_ready();
  3176. Client cli(blackhole, port);
  3177. cli.set_hostname_addr_map({{blackhole, ""}});
  3178. cli.set_connection_timeout(1);
  3179. auto res = cli.Get("/hi");
  3180. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3181. }
  3182. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3183. auto host = "httpbingo.org";
  3184. auto path = std::string{"/absolute-redirect/3"};
  3185. #ifdef CPPHTTPLIB_SSL_ENABLED
  3186. SSLClient cli(host);
  3187. #else
  3188. Client cli(host);
  3189. #endif
  3190. cli.set_follow_location(true);
  3191. auto res = cli.Get(path);
  3192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3193. EXPECT_EQ(StatusCode::OK_200, res->status);
  3194. }
  3195. TEST(RedirectTest, Redirect_Online) {
  3196. auto host = "httpbingo.org";
  3197. auto path = std::string{"/redirect/3"};
  3198. #ifdef CPPHTTPLIB_SSL_ENABLED
  3199. SSLClient cli(host);
  3200. #else
  3201. Client cli(host);
  3202. #endif
  3203. cli.set_follow_location(true);
  3204. auto res = cli.Get(path);
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(RelativeRedirectTest, Redirect_Online) {
  3209. auto host = "httpbingo.org";
  3210. auto path = std::string{"/relative-redirect/3"};
  3211. #ifdef CPPHTTPLIB_SSL_ENABLED
  3212. SSLClient cli(host);
  3213. #else
  3214. Client cli(host);
  3215. #endif
  3216. cli.set_follow_location(true);
  3217. auto res = cli.Get(path);
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(TooManyRedirectTest, Redirect_Online) {
  3222. auto host = "httpbingo.org";
  3223. auto path = std::string{"/redirect/21"};
  3224. #ifdef CPPHTTPLIB_SSL_ENABLED
  3225. SSLClient cli(host);
  3226. #else
  3227. Client cli(host);
  3228. #endif
  3229. cli.set_follow_location(true);
  3230. auto res = cli.Get(path);
  3231. ASSERT_TRUE(!res);
  3232. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3233. }
  3234. #ifdef CPPHTTPLIB_SSL_ENABLED
  3235. TEST(YahooRedirectTest, Redirect_Online) {
  3236. Client cli("yahoo.com");
  3237. auto res = cli.Get("/");
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3240. cli.set_follow_location(true);
  3241. res = cli.Get("/");
  3242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3243. EXPECT_EQ(StatusCode::OK_200, res->status);
  3244. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3245. }
  3246. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3247. #define REDIR_HOST "httpbingo.org"
  3248. #define REDIR_PATH "/redirect-to"
  3249. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3250. SSLClient cli(REDIR_HOST);
  3251. cli.set_follow_location(true);
  3252. auto res =
  3253. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. }
  3257. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3258. SSLClient cli(REDIR_HOST);
  3259. cli.set_follow_location(true);
  3260. Params params;
  3261. params.emplace("url", "http://example.com");
  3262. params.emplace("status_code", "302");
  3263. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. }
  3267. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3268. SSLClient cli(REDIR_HOST);
  3269. cli.set_follow_location(true);
  3270. Params params;
  3271. params.emplace("url", "http://example.com");
  3272. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. EXPECT_EQ(StatusCode::OK_200, res->status);
  3275. }
  3276. TEST(UrlWithSpace, Redirect_Online) {
  3277. SSLClient cli("edge.forgecdn.net");
  3278. cli.set_follow_location(true);
  3279. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3281. EXPECT_EQ(StatusCode::OK_200, res->status);
  3282. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3283. }
  3284. #endif
  3285. #if !defined(_WIN32) && !defined(_WIN64)
  3286. TEST(ReceiveSignals, Signal) {
  3287. auto setupSignalHandlers = []() {
  3288. struct sigaction act;
  3289. sigemptyset(&act.sa_mask);
  3290. act.sa_flags = SA_SIGINFO;
  3291. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3292. switch (sig) {
  3293. case SIGINT:
  3294. default: break;
  3295. }
  3296. };
  3297. ::sigaction(SIGINT, &act, nullptr);
  3298. };
  3299. Server svr;
  3300. int port = 0;
  3301. auto thread = std::thread([&]() {
  3302. setupSignalHandlers();
  3303. port = svr.bind_to_any_port(HOST);
  3304. svr.listen_after_bind();
  3305. });
  3306. auto se = detail::scope_exit([&] {
  3307. svr.stop();
  3308. thread.join();
  3309. ASSERT_FALSE(svr.is_running());
  3310. });
  3311. svr.wait_until_ready();
  3312. ASSERT_TRUE(svr.is_running());
  3313. pthread_kill(thread.native_handle(), SIGINT);
  3314. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3315. ASSERT_TRUE(svr.is_running());
  3316. }
  3317. #endif
  3318. TEST(RedirectToDifferentPort, Redirect) {
  3319. Server svr1;
  3320. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3321. res.set_content("Hello World!", "text/plain");
  3322. });
  3323. int svr1_port = 0;
  3324. auto thread1 = std::thread([&]() {
  3325. svr1_port = svr1.bind_to_any_port(HOST);
  3326. svr1.listen_after_bind();
  3327. });
  3328. Server svr2;
  3329. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3330. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3331. });
  3332. int svr2_port = 0;
  3333. auto thread2 = std::thread([&]() {
  3334. svr2_port = svr2.bind_to_any_port(HOST);
  3335. svr2.listen_after_bind();
  3336. });
  3337. auto se = detail::scope_exit([&] {
  3338. svr2.stop();
  3339. thread2.join();
  3340. svr1.stop();
  3341. thread1.join();
  3342. ASSERT_FALSE(svr2.is_running());
  3343. ASSERT_FALSE(svr1.is_running());
  3344. });
  3345. svr1.wait_until_ready();
  3346. svr2.wait_until_ready();
  3347. Client cli("localhost", svr2_port);
  3348. cli.set_follow_location(true);
  3349. auto res = cli.Get("/2");
  3350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3351. EXPECT_EQ(StatusCode::OK_200, res->status);
  3352. EXPECT_EQ("Hello World!", res->body);
  3353. }
  3354. // GET /redir on one server redirects to /target on another port, so the
  3355. // client follows it with a new client.
  3356. static Result
  3357. GetThroughRedirectToDifferentPort(Server::Handler target,
  3358. const std::function<void(Client &)> &setup,
  3359. const Headers &headers = Headers()) {
  3360. Server target_svr;
  3361. target_svr.Get("/target", target);
  3362. int target_port = 0;
  3363. auto target_thread = std::thread([&]() {
  3364. target_port = target_svr.bind_to_any_port(HOST);
  3365. target_svr.listen_after_bind();
  3366. });
  3367. Server origin_svr;
  3368. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3369. res.set_redirect(
  3370. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3371. });
  3372. int origin_port = 0;
  3373. auto origin_thread = std::thread([&]() {
  3374. origin_port = origin_svr.bind_to_any_port(HOST);
  3375. origin_svr.listen_after_bind();
  3376. });
  3377. auto se = detail::scope_exit([&] {
  3378. origin_svr.stop();
  3379. origin_thread.join();
  3380. target_svr.stop();
  3381. target_thread.join();
  3382. });
  3383. target_svr.wait_until_ready();
  3384. origin_svr.wait_until_ready();
  3385. Client cli("localhost", origin_port);
  3386. cli.set_follow_location(true);
  3387. setup(cli);
  3388. return cli.Get("/redir", headers);
  3389. }
  3390. static void
  3391. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3392. std::string captured_authorization;
  3393. auto result = GetThroughRedirectToDifferentPort(
  3394. [&](const Request &req, Response &res) {
  3395. captured_authorization = req.get_header_value("Authorization");
  3396. res.set_content("OK", "text/plain");
  3397. },
  3398. set_auth);
  3399. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3400. EXPECT_EQ(StatusCode::OK_200, result->status);
  3401. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3402. EXPECT_TRUE(captured_authorization.empty());
  3403. }
  3404. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3405. TestDoNotForwardCredentialsOnRedirect(
  3406. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3407. }
  3408. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3409. TestDoNotForwardCredentialsOnRedirect(
  3410. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3411. }
  3412. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3413. std::string captured_cookie;
  3414. auto result = GetThroughRedirectToDifferentPort(
  3415. [&](const Request &req, Response &res) {
  3416. captured_cookie = req.get_header_value("Cookie");
  3417. res.set_content("OK", "text/plain");
  3418. },
  3419. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3420. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3421. EXPECT_EQ(StatusCode::OK_200, result->status);
  3422. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3423. EXPECT_TRUE(captured_cookie.empty());
  3424. }
  3425. TEST(RedirectToSamePort, ForwardCookie) {
  3426. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3427. // header so that ordinary session flows keep working.
  3428. Server svr;
  3429. std::string captured_cookie;
  3430. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3431. res.set_redirect("/target", 302);
  3432. });
  3433. svr.Get("/target", [&](const Request &req, Response &res) {
  3434. captured_cookie = req.get_header_value("Cookie");
  3435. res.set_content("OK", "text/plain");
  3436. });
  3437. auto port = svr.bind_to_any_port(HOST);
  3438. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3439. auto se = detail::scope_exit([&] {
  3440. svr.stop();
  3441. thread.join();
  3442. ASSERT_FALSE(svr.is_running());
  3443. });
  3444. svr.wait_until_ready();
  3445. Client cli(HOST, port);
  3446. cli.set_follow_location(true);
  3447. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3448. auto res = cli.Get("/redir", headers);
  3449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3450. EXPECT_EQ(StatusCode::OK_200, res->status);
  3451. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3452. }
  3453. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3454. std::string authorization;
  3455. std::string trace_id;
  3456. auto result = GetThroughRedirectToDifferentPort(
  3457. [&](const Request &req, Response &res) {
  3458. authorization = req.get_header_value("Authorization");
  3459. trace_id = req.get_header_value("X-Trace-Id");
  3460. res.set_content("OK", "text/plain");
  3461. },
  3462. [](Client &cli) {
  3463. cli.set_default_headers(
  3464. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3465. });
  3466. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3467. EXPECT_EQ(StatusCode::OK_200, result->status);
  3468. // Like a header given with the request, a default one goes along unless it
  3469. // carries credentials (RFC 9110 15.4).
  3470. EXPECT_TRUE(authorization.empty());
  3471. EXPECT_EQ("42", trace_id);
  3472. }
  3473. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3474. auto result = GetThroughRedirectToDifferentPort(
  3475. [](const Request &, Response &res) {
  3476. res.set_content(std::string(2048, 'x'), "text/plain");
  3477. },
  3478. [](Client &cli) { cli.set_payload_max_length(1024); });
  3479. EXPECT_FALSE(result);
  3480. }
  3481. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3482. auto result = GetThroughRedirectToDifferentPort(
  3483. [](const Request &req, Response &res) {
  3484. // Answer after a second, or once the client gives up.
  3485. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3486. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3487. }
  3488. res.set_content("late", "text/plain");
  3489. },
  3490. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3491. ASSERT_FALSE(result);
  3492. EXPECT_EQ(Error::Read, result.error());
  3493. }
  3494. #ifdef CPPHTTPLIB_SSL_ENABLED
  3495. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3496. auto result = GetThroughRedirectToDifferentPort(
  3497. [](const Request &, Response &res) {
  3498. res.status = StatusCode::Unauthorized_401;
  3499. res.set_header("WWW-Authenticate",
  3500. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3501. },
  3502. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3503. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3504. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3505. }
  3506. #endif
  3507. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3508. Server svr;
  3509. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3510. // Port number that overflows int — should not crash
  3511. res.set_redirect("http://localhost:99999999999999999999/target");
  3512. });
  3513. auto port = svr.bind_to_any_port(HOST);
  3514. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3515. auto se = detail::scope_exit([&] {
  3516. svr.stop();
  3517. thread.join();
  3518. ASSERT_FALSE(svr.is_running());
  3519. });
  3520. svr.wait_until_ready();
  3521. Client cli(HOST, port);
  3522. cli.set_follow_location(true);
  3523. auto res = cli.Get("/redir");
  3524. // Should fail gracefully, not crash (no valid response due to bad port)
  3525. EXPECT_FALSE(res);
  3526. }
  3527. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3528. Server svr;
  3529. auto port = svr.bind_to_any_port(HOST);
  3530. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3531. // The server's own port followed by junk must not be followed
  3532. res.set_redirect("http://" + std::string(HOST) + ":" +
  3533. std::to_string(port) + "junk/target");
  3534. });
  3535. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3536. res.set_content("target", "text/plain");
  3537. });
  3538. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3539. auto se = detail::scope_exit([&] {
  3540. svr.stop();
  3541. thread.join();
  3542. ASSERT_FALSE(svr.is_running());
  3543. });
  3544. svr.wait_until_ready();
  3545. Client cli(HOST, port);
  3546. cli.set_follow_location(true);
  3547. auto res = cli.Get("/redir");
  3548. EXPECT_FALSE(res);
  3549. }
  3550. TEST(RedirectFromPageWithContent, Redirect) {
  3551. Server svr;
  3552. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3553. res.set_content("___", "text/plain");
  3554. res.set_redirect("/2");
  3555. });
  3556. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3557. res.set_content("Hello World!", "text/plain");
  3558. });
  3559. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3560. auto se = detail::scope_exit([&] {
  3561. svr.stop();
  3562. th.join();
  3563. ASSERT_FALSE(svr.is_running());
  3564. });
  3565. svr.wait_until_ready();
  3566. {
  3567. Client cli("localhost", PORT);
  3568. cli.set_follow_location(true);
  3569. std::string body;
  3570. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3571. body.append(data, data_length);
  3572. return true;
  3573. });
  3574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3575. EXPECT_EQ(StatusCode::OK_200, res->status);
  3576. EXPECT_EQ("Hello World!", body);
  3577. }
  3578. {
  3579. Client cli("localhost", PORT);
  3580. std::string body;
  3581. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3582. body.append(data, data_length);
  3583. return true;
  3584. });
  3585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3586. EXPECT_EQ(StatusCode::Found_302, res->status);
  3587. EXPECT_EQ("___", body);
  3588. }
  3589. }
  3590. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3591. Server svr;
  3592. auto port_str = std::to_string(PORT);
  3593. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3594. auto expected_host = "[::1]:" + port_str;
  3595. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3596. res.set_content("___", "text/plain");
  3597. // res.set_redirect("/2");
  3598. res.set_redirect(redirect_url);
  3599. });
  3600. svr.Get("/2", [&](const Request &req, Response &res) {
  3601. auto host_header = req.headers.find("Host");
  3602. ASSERT_TRUE(host_header != req.headers.end());
  3603. EXPECT_EQ(expected_host, host_header->second);
  3604. res.set_content("Hello World!", "text/plain");
  3605. });
  3606. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3607. auto se = detail::scope_exit([&] {
  3608. svr.stop();
  3609. th.join();
  3610. ASSERT_FALSE(svr.is_running());
  3611. });
  3612. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3613. // actually starts anything, so the condition !svr.is_running() will
  3614. // always remain true, and the loop never stops.
  3615. // This basically counts how many milliseconds have passed since the
  3616. // call to svr.listen(), and if after 5 seconds nothing started yet
  3617. // aborts the test.
  3618. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3619. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3620. ASSERT_LT(milliseconds, 5000U);
  3621. }
  3622. {
  3623. Client cli("::1", PORT);
  3624. cli.set_follow_location(true);
  3625. std::string body;
  3626. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3627. body.append(data, data_length);
  3628. return true;
  3629. });
  3630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3631. EXPECT_EQ(StatusCode::OK_200, res->status);
  3632. EXPECT_EQ("Hello World!", body);
  3633. }
  3634. {
  3635. Client cli("::1", PORT);
  3636. std::string body;
  3637. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3638. body.append(data, data_length);
  3639. return true;
  3640. });
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::Found_302, res->status);
  3643. EXPECT_EQ("___", body);
  3644. }
  3645. }
  3646. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3647. Server svr;
  3648. svr.Get("/foo", [](const Request &req, Response &res) {
  3649. auto a = req.params.find("a");
  3650. if (a != req.params.end()) {
  3651. res.set_content((*a).second, "text/plain");
  3652. res.status = StatusCode::OK_200;
  3653. } else {
  3654. res.status = StatusCode::BadRequest_400;
  3655. }
  3656. });
  3657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3658. auto se = detail::scope_exit([&] {
  3659. svr.stop();
  3660. thread.join();
  3661. ASSERT_FALSE(svr.is_running());
  3662. });
  3663. svr.wait_until_ready();
  3664. {
  3665. Client cli(HOST, PORT);
  3666. cli.set_path_encode(false);
  3667. auto res = cli.Get("/foo?a=explicitly+encoded");
  3668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3669. EXPECT_EQ(StatusCode::OK_200, res->status);
  3670. // This expects it back with a space, as the `+` won't have been
  3671. // url-encoded, and server-side the params get decoded turning `+`
  3672. // into spaces.
  3673. EXPECT_EQ("explicitly encoded", res->body);
  3674. }
  3675. }
  3676. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3677. // When path encoding is disabled the client must transmit the supplied
  3678. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3679. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3680. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3681. // than a space (0x20). Assert on the raw wire target to catch this.
  3682. Server svr;
  3683. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3684. svr.Get("/foo", [&](const Request &req, Response &res) {
  3685. EXPECT_EQ(expected_target, req.target);
  3686. res.status = StatusCode::OK_200;
  3687. });
  3688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3689. auto se = detail::scope_exit([&] {
  3690. svr.stop();
  3691. thread.join();
  3692. ASSERT_FALSE(svr.is_running());
  3693. });
  3694. svr.wait_until_ready();
  3695. {
  3696. Client cli(HOST, PORT);
  3697. cli.set_path_encode(false);
  3698. auto res = cli.Get(expected_target.c_str());
  3699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3700. EXPECT_EQ(StatusCode::OK_200, res->status);
  3701. }
  3702. }
  3703. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3704. // `open_stream()` used to skip the path encoding that the buffered send
  3705. // path applies, so the same `path` produced different bytes in the request
  3706. // line depending on which API was used. Assert the two agree.
  3707. Server svr;
  3708. std::string target;
  3709. svr.Get(".*", [&](const Request &req, Response &res) {
  3710. target = req.target;
  3711. res.status = StatusCode::OK_200;
  3712. });
  3713. auto port = svr.bind_to_any_port(HOST);
  3714. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3715. auto se = detail::scope_exit([&] {
  3716. svr.stop();
  3717. thread.join();
  3718. ASSERT_FALSE(svr.is_running());
  3719. });
  3720. svr.wait_until_ready();
  3721. struct {
  3722. const char *path;
  3723. const char *expected;
  3724. } cases[] = {
  3725. {"/a b?x=1", "/a%20b?x=1"},
  3726. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3727. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3728. };
  3729. for (const auto &c : cases) {
  3730. Client cli(HOST, port);
  3731. target.clear();
  3732. auto res = cli.Get(c.path);
  3733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3734. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3735. auto buffered_target = target;
  3736. target.clear();
  3737. auto handle = cli.open_stream("GET", c.path);
  3738. EXPECT_TRUE(handle.is_valid())
  3739. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3740. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3741. }
  3742. }
  3743. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3744. // The `set_path_encode(false)` contract — transmit the supplied target
  3745. // verbatim — must hold for the streaming API too.
  3746. Server svr;
  3747. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3748. std::string target;
  3749. svr.Get("/foo", [&](const Request &req, Response &res) {
  3750. target = req.target;
  3751. res.status = StatusCode::OK_200;
  3752. });
  3753. auto port = svr.bind_to_any_port(HOST);
  3754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3755. auto se = detail::scope_exit([&] {
  3756. svr.stop();
  3757. thread.join();
  3758. ASSERT_FALSE(svr.is_running());
  3759. });
  3760. svr.wait_until_ready();
  3761. {
  3762. Client cli(HOST, port);
  3763. cli.set_path_encode(false);
  3764. auto handle = cli.open_stream("GET", expected_target);
  3765. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3766. EXPECT_EQ(expected_target, target);
  3767. }
  3768. }
  3769. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3770. // With path encoding enabled a CR/LF in the target is percent-encoded
  3771. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3772. // write_request_line still backstops `set_path_encode(false)`, which is
  3773. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3774. Server svr;
  3775. // Captured before routing: the decoded path contains a newline, which a
  3776. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3777. std::string target;
  3778. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3779. target = req.target;
  3780. res.status = StatusCode::OK_200;
  3781. return Server::HandlerResponse::Handled;
  3782. });
  3783. auto port = svr.bind_to_any_port(HOST);
  3784. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3785. auto se = detail::scope_exit([&] {
  3786. svr.stop();
  3787. thread.join();
  3788. ASSERT_FALSE(svr.is_running());
  3789. });
  3790. svr.wait_until_ready();
  3791. {
  3792. Client cli(HOST, port);
  3793. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3794. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3795. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3796. }
  3797. }
  3798. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3799. // Every control character is percent-encoded, not just CR/LF, so the target
  3800. // passes the request-target check in write_request_line.
  3801. Server svr;
  3802. std::string target;
  3803. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3804. target = req.target;
  3805. res.status = StatusCode::OK_200;
  3806. return Server::HandlerResponse::Handled;
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. Client cli(HOST, port);
  3818. auto res = cli.Get("/a\tb\x1b\x7f");
  3819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3820. EXPECT_EQ("/a%09b%1B%7F", target);
  3821. }
  3822. }
  3823. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3824. // Nothing may reach the wire: a raw CR/LF target would split the request
  3825. // line and inject headers.
  3826. Server svr;
  3827. // Pre-routing so that "not called" means nothing reached the server at all,
  3828. // rather than merely failing to match a handler pattern.
  3829. auto handler_called = false;
  3830. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3831. handler_called = true;
  3832. res.status = StatusCode::OK_200;
  3833. return Server::HandlerResponse::Handled;
  3834. });
  3835. auto port = svr.bind_to_any_port(HOST);
  3836. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3837. auto se = detail::scope_exit([&] {
  3838. svr.stop();
  3839. thread.join();
  3840. ASSERT_FALSE(svr.is_running());
  3841. });
  3842. svr.wait_until_ready();
  3843. {
  3844. Client cli(HOST, port);
  3845. cli.set_path_encode(false);
  3846. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3847. EXPECT_FALSE(handle.is_valid());
  3848. EXPECT_EQ(Error::Write, handle.error);
  3849. EXPECT_FALSE(handler_called);
  3850. }
  3851. }
  3852. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3853. // Which of the two branches runs is decided by whether the query component
  3854. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3855. // an empty query and must still fall back to building one from
  3856. // `req.params`, while a non-empty query must win over `req.params`.
  3857. Server svr;
  3858. std::string target;
  3859. svr.Get("/foo", [&](const Request &req, Response &res) {
  3860. target = req.target;
  3861. res.status = StatusCode::OK_200;
  3862. });
  3863. auto port = svr.bind_to_any_port(HOST);
  3864. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3865. auto se = detail::scope_exit([&] {
  3866. svr.stop();
  3867. thread.join();
  3868. ASSERT_FALSE(svr.is_running());
  3869. });
  3870. svr.wait_until_ready();
  3871. {
  3872. // Trailing `?` -> empty query component -> `req.params` is used.
  3873. Client cli(HOST, port);
  3874. Request req;
  3875. req.method = "GET";
  3876. req.path = "/foo?";
  3877. req.params.emplace("a", "1");
  3878. target.clear();
  3879. auto res = cli.send(req);
  3880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3881. EXPECT_EQ("/foo?a=1", target);
  3882. }
  3883. {
  3884. // Non-empty query in `req.path` -> `req.params` is not appended.
  3885. Client cli(HOST, port);
  3886. Request req;
  3887. req.method = "GET";
  3888. req.path = "/foo?b=2";
  3889. req.params.emplace("a", "1");
  3890. target.clear();
  3891. auto res = cli.send(req);
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ("/foo?b=2", target);
  3894. }
  3895. }
  3896. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3897. Server svr;
  3898. svr.Get("/", [](const Request &req, Response &) {
  3899. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3900. });
  3901. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3902. auto se = detail::scope_exit([&] {
  3903. svr.stop();
  3904. thread.join();
  3905. ASSERT_FALSE(svr.is_running());
  3906. });
  3907. svr.wait_until_ready();
  3908. {
  3909. Client cli(HOST, PORT);
  3910. cli.set_path_encode(false);
  3911. auto res = cli.Get("/?something=%0A");
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. }
  3915. }
  3916. TEST(BindServerTest, BindDualStack) {
  3917. Server svr;
  3918. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3919. res.set_content("Hello World!", "text/plain");
  3920. });
  3921. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3922. auto se = detail::scope_exit([&] {
  3923. svr.stop();
  3924. thread.join();
  3925. ASSERT_FALSE(svr.is_running());
  3926. });
  3927. svr.wait_until_ready();
  3928. {
  3929. Client cli("127.0.0.1", PORT);
  3930. auto res = cli.Get("/1");
  3931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3932. EXPECT_EQ(StatusCode::OK_200, res->status);
  3933. EXPECT_EQ("Hello World!", res->body);
  3934. }
  3935. {
  3936. Client cli("::1", PORT);
  3937. auto res = cli.Get("/1");
  3938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3939. EXPECT_EQ(StatusCode::OK_200, res->status);
  3940. EXPECT_EQ("Hello World!", res->body);
  3941. }
  3942. }
  3943. TEST(BindServerTest, BindAndListenSeparately) {
  3944. Server svr;
  3945. int port = svr.bind_to_any_port("0.0.0.0");
  3946. ASSERT_TRUE(svr.is_valid());
  3947. ASSERT_TRUE(port > 0);
  3948. svr.stop();
  3949. }
  3950. // Reports whether anything is still listening on a loopback port. A plain
  3951. // connect() is used instead of a Client request because a socket left bound by
  3952. // mistake accepts the connection into its backlog and never answers, which
  3953. // would hang the test instead of failing it.
  3954. static bool is_loopback_port_accepting(int port) {
  3955. sockaddr_in addr{};
  3956. addr.sin_family = AF_INET;
  3957. addr.sin_port = htons(static_cast<uint16_t>(port));
  3958. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3959. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3960. EXPECT_NE(sock, INVALID_SOCKET);
  3961. if (sock == INVALID_SOCKET) { return false; }
  3962. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3963. static_cast<socklen_t>(sizeof(addr)));
  3964. detail::close_socket(sock);
  3965. return ret == 0;
  3966. }
  3967. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3968. Server svr;
  3969. auto port = svr.bind_to_any_port("127.0.0.1");
  3970. ASSERT_TRUE(port > 0);
  3971. svr.stop();
  3972. // bind_to_any_port() already called listen(2), so until stop() closed the
  3973. // descriptor the port kept accepting connections into the backlog. ASSERT
  3974. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3975. // below blocks forever in the accept loop.
  3976. ASSERT_FALSE(is_loopback_port_accepting(port));
  3977. // Nothing is left to accept on, so listen_after_bind() must report failure
  3978. // instead of returning success without ever serving.
  3979. EXPECT_FALSE(svr.listen_after_bind());
  3980. // The failed listen marks the server decommissioned, so a waiter returns
  3981. // instead of spinning forever.
  3982. svr.wait_until_ready();
  3983. }
  3984. #ifdef CPPHTTPLIB_SSL_ENABLED
  3985. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3987. CLIENT_CA_CERT_DIR);
  3988. int port = svr.bind_to_any_port("0.0.0.0");
  3989. ASSERT_TRUE(svr.is_valid());
  3990. ASSERT_TRUE(port > 0);
  3991. svr.stop();
  3992. }
  3993. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3994. // or a rejected CustomRoute() registration would not stop the server binding.
  3995. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3997. CLIENT_CA_CERT_DIR);
  3998. ASSERT_TRUE(svr.is_valid());
  3999. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4000. EXPECT_FALSE(svr.is_valid());
  4001. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4002. }
  4003. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4004. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4005. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4006. int port = svr.bind_to_any_port("0.0.0.0");
  4007. ASSERT_TRUE(svr.is_valid());
  4008. ASSERT_TRUE(port > 0);
  4009. svr.stop();
  4010. }
  4011. TEST(BindServerTest, UpdateCertsPem) {
  4012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4013. int port = svr.bind_to_any_port("0.0.0.0");
  4014. ASSERT_TRUE(svr.is_valid());
  4015. ASSERT_TRUE(port > 0);
  4016. // Read PEM files
  4017. std::string cert_pem, key_pem, ca_pem;
  4018. read_file(SERVER_CERT_FILE, cert_pem);
  4019. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4020. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4021. // Update server certificates using PEM API
  4022. ASSERT_TRUE(
  4023. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4024. ASSERT_TRUE(svr.is_valid());
  4025. svr.stop();
  4026. }
  4027. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4028. // Start server with client CA (enables client auth)
  4029. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4030. ASSERT_TRUE(svr.is_valid());
  4031. bool handler_called = false;
  4032. svr.Get("/test", [&](const Request &req, Response &res) {
  4033. handler_called = true;
  4034. // Verify client certificate is present
  4035. auto cert = req.peer_cert();
  4036. EXPECT_TRUE(static_cast<bool>(cert));
  4037. res.set_content("ok", "text/plain");
  4038. });
  4039. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4040. auto se = detail::scope_exit([&] {
  4041. svr.stop();
  4042. t.join();
  4043. ASSERT_FALSE(svr.is_running());
  4044. });
  4045. svr.wait_until_ready();
  4046. // Read PEM files
  4047. std::string cert_pem, key_pem, ca_pem;
  4048. read_file(SERVER_CERT_FILE, cert_pem);
  4049. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4050. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4051. // Update server certificates and client CA using PEM API while server running
  4052. ASSERT_TRUE(
  4053. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4054. // Connect with client certificate
  4055. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4056. cli.enable_server_certificate_verification(false);
  4057. cli.set_connection_timeout(30);
  4058. auto res = cli.Get("/test");
  4059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4060. ASSERT_EQ(StatusCode::OK_200, res->status);
  4061. ASSERT_TRUE(handler_called);
  4062. EXPECT_EQ("ok", res->body);
  4063. }
  4064. // Puts a CA that did not sign the client's certificate in the old one's place.
  4065. static bool replace_client_ca(SSLServer &svr) {
  4066. std::string cert_pem, key_pem, ca_pem;
  4067. read_file(SERVER_CERT_FILE, cert_pem);
  4068. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4069. read_file(SERVER_CERT2_FILE, ca_pem);
  4070. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4071. ca_pem.c_str());
  4072. }
  4073. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4075. ASSERT_TRUE(svr.is_valid());
  4076. svr.Get("/test", [](const Request &, Response &res) {
  4077. res.set_content("ok", "text/plain");
  4078. });
  4079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4080. auto se = detail::scope_exit([&] {
  4081. svr.stop();
  4082. t.join();
  4083. ASSERT_FALSE(svr.is_running());
  4084. });
  4085. svr.wait_until_ready();
  4086. auto get = [] {
  4087. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4088. cli.enable_server_certificate_verification(false);
  4089. return cli.Get("/test");
  4090. };
  4091. ASSERT_TRUE(get());
  4092. ASSERT_TRUE(replace_client_ca(svr));
  4093. EXPECT_FALSE(get());
  4094. }
  4095. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4096. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4098. ASSERT_TRUE(svr.is_valid());
  4099. tls::set_verify_callback(svr.tls_context(),
  4100. [](const tls::VerifyContext &) -> bool {
  4101. throw std::runtime_error("verify");
  4102. });
  4103. svr.Get("/test", [](const Request &, Response &res) {
  4104. res.set_content("ok", "text/plain");
  4105. });
  4106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4107. auto se = detail::scope_exit([&] {
  4108. svr.stop();
  4109. t.join();
  4110. ASSERT_FALSE(svr.is_running());
  4111. });
  4112. svr.wait_until_ready();
  4113. auto get = [] {
  4114. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4115. cli.enable_server_certificate_verification(false);
  4116. return cli.Get("/test");
  4117. };
  4118. EXPECT_FALSE(get());
  4119. // The handshake is over, so an update does not wait for it.
  4120. std::string cert_pem, key_pem;
  4121. read_file(SERVER_CERT_FILE, cert_pem);
  4122. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4123. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4124. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4125. return v.preverify_ok;
  4126. });
  4127. auto res = get();
  4128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4129. EXPECT_EQ("ok", res->body);
  4130. }
  4131. #endif
  4132. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4133. // Sends each request over a new connection with a client certificate,
  4134. // resuming the session of the one before when there is one.
  4135. class ResumingClient {
  4136. public:
  4137. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4138. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4139. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4140. SSL_FILETYPE_PEM);
  4141. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4142. // callback, not through SSL_get1_session().
  4143. SSL_CTX_set_app_data(ctx_, this);
  4144. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4145. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4146. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4147. auto self = static_cast<ResumingClient *>(
  4148. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4149. SSL_SESSION_free(self->session_);
  4150. self->session_ = session;
  4151. return 1; // Keeps the reference
  4152. });
  4153. }
  4154. ~ResumingClient() {
  4155. SSL_SESSION_free(session_);
  4156. SSL_CTX_free(ctx_);
  4157. }
  4158. // Tells whether the request was answered.
  4159. bool get() {
  4160. auto error = Error::Success;
  4161. auto sock = detail::create_client_socket(
  4162. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4163. /*connection_timeout_sec=*/5, 0,
  4164. /*read_timeout_sec=*/5, 0,
  4165. /*write_timeout_sec=*/5, 0, std::string(), error);
  4166. if (sock == INVALID_SOCKET) { return false; }
  4167. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4168. auto ssl = SSL_new(ctx_);
  4169. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4170. SSL_set_fd(ssl, static_cast<int>(sock));
  4171. if (session_) { SSL_set_session(ssl, session_); }
  4172. if (SSL_connect(ssl) != 1) { return false; }
  4173. reused_ = SSL_session_reused(ssl) == 1;
  4174. // Reading the response also takes in a TLS 1.3 session ticket.
  4175. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4176. "Connection: close\r\n\r\n";
  4177. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4178. std::string res;
  4179. char buf[256];
  4180. int n;
  4181. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4182. res.append(buf, static_cast<size_t>(n));
  4183. }
  4184. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4185. SSL_shutdown(ssl);
  4186. return res.find("200 OK") != std::string::npos;
  4187. }
  4188. // Whether the last connection resumed a session
  4189. bool reused() const { return reused_; }
  4190. private:
  4191. SSL_CTX *ctx_;
  4192. SSL_SESSION *session_ = nullptr;
  4193. bool reused_ = false;
  4194. };
  4195. // A client that resumes its session gets through, but not once the client CA
  4196. // has changed, as a resumed session does not show the certificate again.
  4197. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4198. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4199. ASSERT_TRUE(svr.is_valid());
  4200. svr.Get("/test", [](const Request &, Response &res) {
  4201. res.set_content("ok", "text/plain");
  4202. });
  4203. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4204. auto se = detail::scope_exit([&] {
  4205. svr.stop();
  4206. t.join();
  4207. ASSERT_FALSE(svr.is_running());
  4208. });
  4209. svr.wait_until_ready();
  4210. ResumingClient cli;
  4211. ASSERT_TRUE(cli.get());
  4212. ASSERT_TRUE(cli.get());
  4213. EXPECT_TRUE(cli.reused());
  4214. ASSERT_TRUE(replace_client_ca(svr));
  4215. EXPECT_FALSE(cli.get());
  4216. }
  4217. // A resumed session does not show the certificate again, so the server does
  4218. // not resume one with a verify callback to run on it.
  4219. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4221. ASSERT_TRUE(svr.is_valid());
  4222. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4223. return v.preverify_ok;
  4224. });
  4225. svr.Get("/test", [](const Request &, Response &res) {
  4226. res.set_content("ok", "text/plain");
  4227. });
  4228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4229. auto se = detail::scope_exit([&] {
  4230. svr.stop();
  4231. t.join();
  4232. ASSERT_FALSE(svr.is_running());
  4233. });
  4234. svr.wait_until_ready();
  4235. ResumingClient cli;
  4236. ASSERT_TRUE(cli.get());
  4237. ASSERT_TRUE(cli.get());
  4238. EXPECT_FALSE(cli.reused());
  4239. }
  4240. #endif
  4241. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4242. // wolfSSL shares its session cache between contexts, so a resumed session
  4243. // could carry a client certificate checked against another server's CA, or
  4244. // against a client CA since replaced.
  4245. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4247. ASSERT_TRUE(svr.is_valid());
  4248. // Trusts a CA that did not sign the client's certificate.
  4249. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4250. ASSERT_TRUE(other.is_valid());
  4251. for (auto s : {&svr, &other}) {
  4252. s->Get("/test", [](const Request &, Response &res) {
  4253. res.set_content("ok", "text/plain");
  4254. });
  4255. }
  4256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4257. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4258. auto se = detail::scope_exit([&] {
  4259. other.stop();
  4260. svr.stop();
  4261. t2.join();
  4262. t.join();
  4263. });
  4264. svr.wait_until_ready();
  4265. other.wait_until_ready();
  4266. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4267. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4268. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4269. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4270. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4271. ASSERT_EQ(WOLFSSL_SUCCESS,
  4272. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4273. WOLFSSL_FILETYPE_PEM));
  4274. WOLFSSL_SESSION *session = nullptr;
  4275. auto session_se = detail::scope_exit([&] {
  4276. if (session) { wolfSSL_SESSION_free(session); }
  4277. });
  4278. // A request over a new connection, resuming `session` when there is one and
  4279. // keeping the connection's own in its place. Tells whether it was answered.
  4280. auto get = [&](int port) {
  4281. auto error = Error::Success;
  4282. auto sock = detail::create_client_socket(
  4283. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4284. /*connection_timeout_sec=*/5, 0,
  4285. /*read_timeout_sec=*/5, 0,
  4286. /*write_timeout_sec=*/5, 0, std::string(), error);
  4287. if (sock == INVALID_SOCKET) { return false; }
  4288. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4289. auto ssl = wolfSSL_new(ctx);
  4290. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4291. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4292. if (session) { wolfSSL_set_session(ssl, session); }
  4293. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4294. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4295. "Connection: close\r\n\r\n";
  4296. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4297. std::string res;
  4298. char buf[256];
  4299. int n;
  4300. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4301. res.append(buf, static_cast<size_t>(n));
  4302. }
  4303. wolfSSL_shutdown(ssl);
  4304. if (session) { wolfSSL_SESSION_free(session); }
  4305. session = wolfSSL_get1_session(ssl);
  4306. return res.find("200 OK") != std::string::npos;
  4307. };
  4308. ASSERT_TRUE(get(PORT));
  4309. EXPECT_FALSE(get(PORT + 1));
  4310. ASSERT_TRUE(get(PORT));
  4311. ASSERT_TRUE(replace_client_ca(svr));
  4312. EXPECT_FALSE(get(PORT));
  4313. }
  4314. #endif
  4315. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4317. ASSERT_TRUE(svr.is_valid());
  4318. svr.Get("/test", [](const Request &, Response &res) {
  4319. res.set_content("ok", "text/plain");
  4320. });
  4321. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4322. auto se = detail::scope_exit([&] {
  4323. svr.stop();
  4324. t.join();
  4325. ASSERT_FALSE(svr.is_running());
  4326. });
  4327. svr.wait_until_ready();
  4328. // A connection that sends no ClientHello keeps its handshake in progress,
  4329. // once the server has had a moment to start it.
  4330. auto error = Error::Success;
  4331. auto sock = detail::create_client_socket(
  4332. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4333. /*connection_timeout_sec=*/5, 0,
  4334. /*read_timeout_sec=*/5, 0,
  4335. /*write_timeout_sec=*/5, 0, std::string(), error);
  4336. ASSERT_NE(INVALID_SOCKET, sock);
  4337. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4338. std::string cert_pem, key_pem;
  4339. read_file(SERVER_CERT_FILE, cert_pem);
  4340. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4341. auto update = std::async(std::launch::async, [&]() {
  4342. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4343. });
  4344. EXPECT_EQ(std::future_status::timeout,
  4345. update.wait_for(std::chrono::milliseconds(200)));
  4346. detail::close_socket(sock);
  4347. EXPECT_TRUE(update.get());
  4348. SSLClient cli(HOST, PORT);
  4349. cli.enable_server_certificate_verification(false);
  4350. auto res = cli.Get("/test");
  4351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. }
  4354. #endif
  4355. TEST(ErrorHandlerTest, ContentLength) {
  4356. Server svr;
  4357. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4358. res.status = StatusCode::OK_200;
  4359. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4360. "text/html"); // <= Content-Length still 13
  4361. });
  4362. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4363. res.set_content("Hello World!\n", "text/plain");
  4364. res.status = 524;
  4365. });
  4366. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4367. auto se = detail::scope_exit([&] {
  4368. svr.stop();
  4369. thread.join();
  4370. ASSERT_FALSE(svr.is_running());
  4371. });
  4372. svr.wait_until_ready();
  4373. {
  4374. Client cli(HOST, PORT);
  4375. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4379. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4380. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4381. }
  4382. }
  4383. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4384. TEST(ExceptionTest, WithoutExceptionHandler) {
  4385. Server svr;
  4386. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4387. throw std::runtime_error("exception...");
  4388. });
  4389. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4390. throw std::runtime_error("exception\r\n...");
  4391. });
  4392. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4393. auto se = detail::scope_exit([&] {
  4394. svr.stop();
  4395. listen_thread.join();
  4396. ASSERT_FALSE(svr.is_running());
  4397. });
  4398. svr.wait_until_ready();
  4399. Client cli("localhost", PORT);
  4400. {
  4401. auto res = cli.Get("/exception");
  4402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4403. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4404. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4405. }
  4406. {
  4407. auto res = cli.Get("/unknown");
  4408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4409. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4410. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4411. }
  4412. }
  4413. TEST(ExceptionTest, WithExceptionHandler) {
  4414. Server svr;
  4415. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4416. std::exception_ptr ep) {
  4417. EXPECT_FALSE(ep == nullptr);
  4418. try {
  4419. std::rethrow_exception(ep);
  4420. } catch (std::exception &e) {
  4421. EXPECT_EQ("abc", std::string(e.what()));
  4422. } catch (...) {}
  4423. res.status = StatusCode::InternalServerError_500;
  4424. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4425. "text/html"); // <= Content-Length still 13 at this point
  4426. });
  4427. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("Hello World!\n", "text/plain");
  4429. throw std::runtime_error("abc");
  4430. });
  4431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. for (size_t i = 0; i < 10; i++) {
  4439. Client cli(HOST, PORT);
  4440. for (size_t j = 0; j < 100; j++) {
  4441. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4443. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4444. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4445. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4446. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4447. }
  4448. cli.set_keep_alive(true);
  4449. for (size_t j = 0; j < 100; j++) {
  4450. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4452. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4453. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4454. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4455. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4456. }
  4457. }
  4458. }
  4459. TEST(ExceptionTest, AndErrorHandler) {
  4460. Server svr;
  4461. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4462. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4463. });
  4464. svr.set_exception_handler(
  4465. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4466. EXPECT_FALSE(ep == nullptr);
  4467. try {
  4468. std::rethrow_exception(ep);
  4469. } catch (std::exception &e) {
  4470. res.set_content(e.what(), "text/html");
  4471. } catch (...) {}
  4472. res.status = StatusCode::InternalServerError_500;
  4473. });
  4474. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4475. throw std::runtime_error("EXCEPTION");
  4476. });
  4477. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4478. res.set_content("ERROR", "text/html");
  4479. res.status = StatusCode::InternalServerError_500;
  4480. });
  4481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4482. auto se = detail::scope_exit([&] {
  4483. svr.stop();
  4484. thread.join();
  4485. ASSERT_FALSE(svr.is_running());
  4486. });
  4487. svr.wait_until_ready();
  4488. Client cli(HOST, PORT);
  4489. {
  4490. auto res = cli.Get("/exception");
  4491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4492. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4493. EXPECT_EQ("EXCEPTION", res->body);
  4494. }
  4495. {
  4496. auto res = cli.Get("/error");
  4497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4498. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4499. EXPECT_EQ("ERROR", res->body);
  4500. }
  4501. {
  4502. auto res = cli.Get("/invalid");
  4503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4504. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4505. EXPECT_EQ("NOT_FOUND", res->body);
  4506. }
  4507. }
  4508. #endif
  4509. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4510. // process_request() wraps only routing() in a try/catch, so an exception from
  4511. // any other user callback used to unwind into the task queue - which does not
  4512. // catch - and terminate the process. Each test below runs the server on a
  4513. // single worker thread: a guard that catches the exception but still loses the
  4514. // thread would otherwise be hidden by a spare worker serving the follow-up
  4515. // request. Note that a regression here aborts the whole test binary rather
  4516. // than failing one test.
  4517. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4518. Server svr;
  4519. svr.new_task_queue = [] { return new ThreadPool(1); };
  4520. std::atomic<int> reported{0};
  4521. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4522. if (err == Error::UserCallbackException) { reported++; }
  4523. });
  4524. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4525. res.set_content_provider(
  4526. 1024, "text/plain",
  4527. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4528. sink.write("hello", 5);
  4529. throw std::runtime_error("from the content provider");
  4530. });
  4531. });
  4532. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4533. res.set_content("ok", "text/plain");
  4534. });
  4535. auto port = svr.bind_to_any_port(HOST);
  4536. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4537. auto se = detail::scope_exit([&] {
  4538. svr.stop();
  4539. listen_thread.join();
  4540. ASSERT_FALSE(svr.is_running());
  4541. });
  4542. svr.wait_until_ready();
  4543. {
  4544. Client cli(HOST, port);
  4545. cli.set_read_timeout(5, 0);
  4546. EXPECT_FALSE(cli.Get("/throw"));
  4547. }
  4548. EXPECT_TRUE(svr.is_running());
  4549. EXPECT_EQ(1, reported.load());
  4550. // A request on a fresh connection is still served.
  4551. {
  4552. Client cli(HOST, port);
  4553. auto res = cli.Get("/ok");
  4554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4555. EXPECT_EQ(StatusCode::OK_200, res->status);
  4556. EXPECT_EQ("ok", res->body);
  4557. }
  4558. }
  4559. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4560. Server svr;
  4561. svr.new_task_queue = [] { return new ThreadPool(1); };
  4562. std::atomic<bool> should_throw{true};
  4563. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4564. res.set_content("hi", "text/plain");
  4565. });
  4566. svr.set_post_routing_handler(
  4567. [&](const Request & /*req*/, Response & /*res*/) {
  4568. if (should_throw) {
  4569. throw std::runtime_error("from the post-routing handler");
  4570. }
  4571. });
  4572. auto port = svr.bind_to_any_port(HOST);
  4573. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4574. auto se = detail::scope_exit([&] {
  4575. svr.stop();
  4576. listen_thread.join();
  4577. ASSERT_FALSE(svr.is_running());
  4578. });
  4579. svr.wait_until_ready();
  4580. {
  4581. Client cli(HOST, port);
  4582. cli.set_read_timeout(5, 0);
  4583. EXPECT_FALSE(cli.Get("/hi"));
  4584. }
  4585. EXPECT_TRUE(svr.is_running());
  4586. should_throw = false;
  4587. {
  4588. Client cli(HOST, port);
  4589. auto res = cli.Get("/hi");
  4590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ("hi", res->body);
  4593. }
  4594. }
  4595. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4596. // The guard reports the caught exception through the error logger, which is
  4597. // a user callback too. A logger that throws has to be contained as well, or
  4598. // the process would terminate from inside the catch.
  4599. Server svr;
  4600. svr.new_task_queue = [] { return new ThreadPool(1); };
  4601. std::atomic<int> reported{0};
  4602. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4603. if (err == Error::UserCallbackException) {
  4604. reported++;
  4605. throw std::runtime_error("from the error logger");
  4606. }
  4607. });
  4608. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4609. res.set_content_provider(
  4610. 1024, "text/plain",
  4611. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4612. sink.write("hello", 5);
  4613. throw std::runtime_error("from the content provider");
  4614. });
  4615. });
  4616. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4617. res.set_content("ok", "text/plain");
  4618. });
  4619. auto port = svr.bind_to_any_port(HOST);
  4620. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4621. auto se = detail::scope_exit([&] {
  4622. svr.stop();
  4623. listen_thread.join();
  4624. ASSERT_FALSE(svr.is_running());
  4625. });
  4626. svr.wait_until_ready();
  4627. {
  4628. Client cli(HOST, port);
  4629. cli.set_read_timeout(5, 0);
  4630. EXPECT_FALSE(cli.Get("/throw"));
  4631. }
  4632. EXPECT_TRUE(svr.is_running());
  4633. EXPECT_EQ(1, reported.load());
  4634. {
  4635. Client cli(HOST, port);
  4636. auto res = cli.Get("/ok");
  4637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4638. EXPECT_EQ(StatusCode::OK_200, res->status);
  4639. EXPECT_EQ("ok", res->body);
  4640. }
  4641. }
  4642. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4643. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4644. // so the exception unwinds through the ws::WebSocket object on its way to
  4645. // the guard. None of the HTTP cases above cross that.
  4646. Server svr;
  4647. svr.new_task_queue = [] { return new ThreadPool(1); };
  4648. std::atomic<int> reported{0};
  4649. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4650. if (err == Error::UserCallbackException) { reported++; }
  4651. });
  4652. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4653. throw std::runtime_error("from the WebSocket handler");
  4654. });
  4655. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4656. res.set_content("ok", "text/plain");
  4657. });
  4658. auto port = svr.bind_to_any_port(HOST);
  4659. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4660. auto se = detail::scope_exit([&] {
  4661. svr.stop();
  4662. listen_thread.join();
  4663. ASSERT_FALSE(svr.is_running());
  4664. });
  4665. svr.wait_until_ready();
  4666. {
  4667. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4668. "/ws");
  4669. auto res = client.connect();
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. // The server dropped the connection instead of dying.
  4672. std::string msg;
  4673. EXPECT_FALSE(client.read(msg));
  4674. client.close();
  4675. }
  4676. EXPECT_TRUE(svr.is_running());
  4677. EXPECT_EQ(1, reported.load());
  4678. {
  4679. Client cli(HOST, port);
  4680. auto res = cli.Get("/ok");
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. EXPECT_EQ(StatusCode::OK_200, res->status);
  4683. EXPECT_EQ("ok", res->body);
  4684. }
  4685. }
  4686. #ifdef CPPHTTPLIB_SSL_ENABLED
  4687. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4688. // SSLServer::process_and_close_socket() is a separate overload with its own
  4689. // guard, so it is exercised on its own.
  4690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4691. ASSERT_TRUE(svr.is_valid());
  4692. svr.new_task_queue = [] { return new ThreadPool(1); };
  4693. std::atomic<int> reported{0};
  4694. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4695. if (err == Error::UserCallbackException) { reported++; }
  4696. });
  4697. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4698. res.set_content_provider(
  4699. 1024, "text/plain",
  4700. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4701. sink.write("hello", 5);
  4702. throw std::runtime_error("from the content provider");
  4703. });
  4704. });
  4705. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4706. res.set_content("ok", "text/plain");
  4707. });
  4708. auto port = svr.bind_to_any_port(HOST);
  4709. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4710. auto se = detail::scope_exit([&] {
  4711. svr.stop();
  4712. listen_thread.join();
  4713. ASSERT_FALSE(svr.is_running());
  4714. });
  4715. svr.wait_until_ready();
  4716. {
  4717. SSLClient cli(HOST, port);
  4718. cli.enable_server_certificate_verification(false);
  4719. cli.set_read_timeout(5, 0);
  4720. EXPECT_FALSE(cli.Get("/throw"));
  4721. }
  4722. EXPECT_TRUE(svr.is_running());
  4723. EXPECT_EQ(1, reported.load());
  4724. {
  4725. SSLClient cli(HOST, port);
  4726. cli.enable_server_certificate_verification(false);
  4727. auto res = cli.Get("/ok");
  4728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("ok", res->body);
  4731. }
  4732. }
  4733. #endif
  4734. #endif
  4735. TEST(NoContentTest, ContentLength) {
  4736. Server svr;
  4737. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4738. res.status = StatusCode::NoContent_204;
  4739. });
  4740. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4741. auto se = detail::scope_exit([&] {
  4742. svr.stop();
  4743. thread.join();
  4744. ASSERT_FALSE(svr.is_running());
  4745. });
  4746. svr.wait_until_ready();
  4747. {
  4748. Client cli(HOST, PORT);
  4749. auto res = cli.Get("/hi");
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4752. // RFC 9110 8.6: none in a 204 response
  4753. EXPECT_FALSE(res->has_header("Content-Length"));
  4754. }
  4755. }
  4756. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4757. Server svr;
  4758. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4759. res.set_header("Content-Length", "5");
  4760. res.set_content("hello world", "text/plain");
  4761. });
  4762. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4763. // A body that reads as the last chunk, were it taken as chunked
  4764. res.set_header("Transfer-Encoding", "chunked");
  4765. res.set_content("0\r\n\r\n", "text/plain");
  4766. });
  4767. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4768. res.set_header("Content-Length", "2");
  4769. res.set_content_provider(5, "text/plain",
  4770. [](size_t offset, size_t length, DataSink &sink) {
  4771. sink.write(&"hello"[offset], length);
  4772. return true;
  4773. });
  4774. });
  4775. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4776. res.set_header("Content-Length", "1234");
  4777. });
  4778. thread t = thread([&] { svr.listen(HOST, PORT); });
  4779. auto se = detail::scope_exit([&] {
  4780. svr.stop();
  4781. t.join();
  4782. ASSERT_FALSE(svr.is_running());
  4783. });
  4784. svr.wait_until_ready();
  4785. Client cli(HOST, PORT);
  4786. cli.set_read_timeout(1, 0);
  4787. auto expect_body = [&](const Result &res, const std::string &body) {
  4788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4789. EXPECT_EQ(body, res->body);
  4790. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4791. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4792. };
  4793. Headers identity{{"Accept-Encoding", ""}};
  4794. expect_body(cli.Get("/body", identity), "hello world");
  4795. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4796. expect_body(cli.Get("/body",
  4797. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4798. "he");
  4799. expect_body(cli.Get("/provider", identity), "hello");
  4800. expect_body(cli.Get("/empty", identity), "");
  4801. // A HEAD response may give the length of the body a GET would get.
  4802. auto res = cli.Head("/empty");
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4805. }
  4806. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4807. Server svr;
  4808. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4809. res.set_content("short", "text/plain");
  4810. });
  4811. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4812. res.body += " with a footer";
  4813. res.set_header("Transfer-Encoding", "chunked");
  4814. });
  4815. thread t = thread([&] { svr.listen(HOST, PORT); });
  4816. auto se = detail::scope_exit([&] {
  4817. svr.stop();
  4818. t.join();
  4819. ASSERT_FALSE(svr.is_running());
  4820. });
  4821. svr.wait_until_ready();
  4822. Client cli(HOST, PORT);
  4823. cli.set_read_timeout(1, 0);
  4824. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. EXPECT_EQ("short with a footer", res->body);
  4827. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4828. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4829. }
  4830. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4831. Server svr;
  4832. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4833. res.set_header("Content-Length", "3");
  4834. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4835. sink.write("abc", 3);
  4836. sink.done();
  4837. return true;
  4838. });
  4839. });
  4840. thread t = thread([&] { svr.listen(HOST, PORT); });
  4841. auto se = detail::scope_exit([&] {
  4842. svr.stop();
  4843. t.join();
  4844. ASSERT_FALSE(svr.is_running());
  4845. });
  4846. svr.wait_until_ready();
  4847. Client cli(HOST, PORT);
  4848. cli.set_keep_alive(true);
  4849. auto res = cli.Get("/");
  4850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4851. EXPECT_EQ("abc", res->body);
  4852. EXPECT_FALSE(res->has_header("Content-Length"));
  4853. EXPECT_EQ("close", res->get_header_value("Connection"));
  4854. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4855. // No body to delimit
  4856. auto head = cli.Head("/");
  4857. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4858. EXPECT_FALSE(head->has_header("Connection"));
  4859. }
  4860. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4861. #ifdef CPPHTTPLIB_SSL_ENABLED
  4862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4863. ASSERT_TRUE(svr.is_valid());
  4864. #else
  4865. Server svr;
  4866. #endif
  4867. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4868. if (req.path == "/routing_handler") {
  4869. res.set_header("PRE_ROUTING", "on");
  4870. res.set_content("Routing Handler", "text/plain");
  4871. return httplib::Server::HandlerResponse::Handled;
  4872. }
  4873. return httplib::Server::HandlerResponse::Unhandled;
  4874. });
  4875. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4876. res.set_content("Error", "text/html");
  4877. });
  4878. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4879. if (req.path == "/routing_handler") {
  4880. res.set_header("POST_ROUTING", "on");
  4881. }
  4882. });
  4883. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4884. res.set_content("Hello World!\n", "text/plain");
  4885. });
  4886. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4887. auto se = detail::scope_exit([&] {
  4888. svr.stop();
  4889. thread.join();
  4890. ASSERT_FALSE(svr.is_running());
  4891. });
  4892. svr.wait_until_ready();
  4893. {
  4894. #ifdef CPPHTTPLIB_SSL_ENABLED
  4895. SSLClient cli(HOST, PORT);
  4896. cli.enable_server_certificate_verification(false);
  4897. #else
  4898. Client cli(HOST, PORT);
  4899. #endif
  4900. auto res = cli.Get("/routing_handler");
  4901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4902. EXPECT_EQ(StatusCode::OK_200, res->status);
  4903. EXPECT_EQ("Routing Handler", res->body);
  4904. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4905. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4906. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4907. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4908. }
  4909. {
  4910. #ifdef CPPHTTPLIB_SSL_ENABLED
  4911. SSLClient cli(HOST, PORT);
  4912. cli.enable_server_certificate_verification(false);
  4913. #else
  4914. Client cli(HOST, PORT);
  4915. #endif
  4916. auto res = cli.Get("/hi");
  4917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4918. EXPECT_EQ(StatusCode::OK_200, res->status);
  4919. EXPECT_EQ("Hello World!\n", res->body);
  4920. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4921. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4922. }
  4923. {
  4924. #ifdef CPPHTTPLIB_SSL_ENABLED
  4925. SSLClient cli(HOST, PORT);
  4926. cli.enable_server_certificate_verification(false);
  4927. #else
  4928. Client cli(HOST, PORT);
  4929. #endif
  4930. auto res = cli.Get("/aaa");
  4931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4932. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4933. EXPECT_EQ("Error", res->body);
  4934. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4935. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4936. }
  4937. }
  4938. TEST(RequestHandlerTest, PreRequestHandler) {
  4939. auto route_path = "/user/:user";
  4940. Server svr;
  4941. svr.Get("/hi", [](const Request &, Response &res) {
  4942. res.set_content("hi", "text/plain");
  4943. });
  4944. svr.Get(route_path, [](const Request &req, Response &res) {
  4945. res.set_content(req.path_params.at("user"), "text/plain");
  4946. });
  4947. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4948. if (req.matched_route == route_path) {
  4949. auto user = req.path_params.at("user");
  4950. if (user != "john") {
  4951. res.status = StatusCode::Forbidden_403;
  4952. res.set_content("error", "text/html");
  4953. return Server::HandlerResponse::Handled;
  4954. }
  4955. }
  4956. return Server::HandlerResponse::Unhandled;
  4957. });
  4958. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4959. auto se = detail::scope_exit([&] {
  4960. svr.stop();
  4961. thread.join();
  4962. ASSERT_FALSE(svr.is_running());
  4963. });
  4964. svr.wait_until_ready();
  4965. Client cli(HOST, PORT);
  4966. {
  4967. auto res = cli.Get("/hi");
  4968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("hi", res->body);
  4971. }
  4972. {
  4973. auto res = cli.Get("/user/john");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ("john", res->body);
  4977. }
  4978. {
  4979. auto res = cli.Get("/user/invalid-user");
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4982. EXPECT_EQ("error", res->body);
  4983. }
  4984. }
  4985. // The pre-request handler must run before the request body is read, so a
  4986. // rejected request never forces the server to buffer a (potentially large)
  4987. // body. Here the posted body is larger than the payload limit: if the body
  4988. // were read first the server would answer 413, but because the pre-request
  4989. // handler runs first it answers 403 and the body is never read.
  4990. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4991. Server svr;
  4992. svr.set_payload_max_length(8);
  4993. auto handler_ran = false;
  4994. svr.Post("/reject", [&](const Request &req, Response &res) {
  4995. handler_ran = true;
  4996. res.set_content(req.body, "text/plain");
  4997. });
  4998. svr.Post("/accept", [](const Request &req, Response &res) {
  4999. res.set_content(req.body, "text/plain");
  5000. });
  5001. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5002. if (req.matched_route == "/reject") {
  5003. res.status = StatusCode::Forbidden_403;
  5004. res.set_content("denied", "text/plain");
  5005. return Server::HandlerResponse::Handled;
  5006. }
  5007. return Server::HandlerResponse::Unhandled;
  5008. });
  5009. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5010. auto se = detail::scope_exit([&] {
  5011. svr.stop();
  5012. thread.join();
  5013. ASSERT_FALSE(svr.is_running());
  5014. });
  5015. svr.wait_until_ready();
  5016. Client cli(HOST, PORT);
  5017. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5018. // rejects with 403 before the body is read, so 413 is never reached.
  5019. {
  5020. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5023. EXPECT_EQ("denied", res->body);
  5024. EXPECT_FALSE(handler_ran);
  5025. }
  5026. // An approved route still reads the body and enforces the payload limit.
  5027. {
  5028. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5030. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5031. }
  5032. }
  5033. TEST(UserDataTest, BasicOperations) {
  5034. httplib::UserData ud;
  5035. // Initially empty
  5036. EXPECT_FALSE(ud.has("key"));
  5037. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5038. // set and get
  5039. ud.set("key", 42);
  5040. EXPECT_TRUE(ud.has("key"));
  5041. auto *p = ud.get<int>("key");
  5042. ASSERT_NE(nullptr, p);
  5043. EXPECT_EQ(42, *p);
  5044. // Type mismatch → nullptr
  5045. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5046. // Overwrite with different type
  5047. ud.set("key", std::string("hello"));
  5048. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5049. auto *s = ud.get<std::string>("key");
  5050. ASSERT_NE(nullptr, s);
  5051. EXPECT_EQ("hello", *s);
  5052. // erase
  5053. ud.erase("key");
  5054. EXPECT_FALSE(ud.has("key"));
  5055. // clear
  5056. ud.set("a", 1);
  5057. ud.set("b", 2);
  5058. ud.clear();
  5059. EXPECT_FALSE(ud.has("a"));
  5060. EXPECT_FALSE(ud.has("b"));
  5061. }
  5062. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5063. struct AuthCtx {
  5064. std::string user_id;
  5065. };
  5066. Server svr;
  5067. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5068. res.user_data.set("auth", AuthCtx{"alice"});
  5069. return Server::HandlerResponse::Unhandled;
  5070. });
  5071. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5072. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5073. ASSERT_NE(nullptr, ctx);
  5074. res.set_content("Hello " + ctx->user_id, "text/plain");
  5075. });
  5076. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5077. auto se = detail::scope_exit([&] {
  5078. svr.stop();
  5079. thread.join();
  5080. ASSERT_FALSE(svr.is_running());
  5081. });
  5082. svr.wait_until_ready();
  5083. Client cli(HOST, PORT);
  5084. auto res = cli.Get("/me");
  5085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5086. EXPECT_EQ(StatusCode::OK_200, res->status);
  5087. EXPECT_EQ("Hello alice", res->body);
  5088. }
  5089. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5090. struct RoleCtx {
  5091. std::string role;
  5092. };
  5093. Server svr;
  5094. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5095. res.user_data.set("role", RoleCtx{"admin"});
  5096. return Server::HandlerResponse::Unhandled;
  5097. });
  5098. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5099. auto *ctx = res.user_data.get<RoleCtx>("role");
  5100. ASSERT_NE(nullptr, ctx);
  5101. res.set_content(ctx->role, "text/plain");
  5102. });
  5103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5104. auto se = detail::scope_exit([&] {
  5105. svr.stop();
  5106. thread.join();
  5107. ASSERT_FALSE(svr.is_running());
  5108. });
  5109. svr.wait_until_ready();
  5110. Client cli(HOST, PORT);
  5111. auto res = cli.Get("/role");
  5112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5113. EXPECT_EQ(StatusCode::OK_200, res->status);
  5114. EXPECT_EQ("admin", res->body);
  5115. }
  5116. TEST(InvalidFormatTest, StatusCode) {
  5117. Server svr;
  5118. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5119. res.set_content("Hello World!\n", "text/plain");
  5120. res.status = 9999; // Status should be a three-digit code...
  5121. });
  5122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5123. auto se = detail::scope_exit([&] {
  5124. svr.stop();
  5125. thread.join();
  5126. ASSERT_FALSE(svr.is_running());
  5127. });
  5128. svr.wait_until_ready();
  5129. {
  5130. Client cli(HOST, PORT);
  5131. auto res = cli.Get("/hi");
  5132. ASSERT_FALSE(res);
  5133. }
  5134. }
  5135. TEST(URLFragmentTest, WithFragment) {
  5136. Server svr;
  5137. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5138. EXPECT_TRUE(req.target == "/hi");
  5139. });
  5140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5141. auto se = detail::scope_exit([&] {
  5142. svr.stop();
  5143. thread.join();
  5144. ASSERT_FALSE(svr.is_running());
  5145. });
  5146. svr.wait_until_ready();
  5147. {
  5148. Client cli(HOST, PORT);
  5149. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5150. EXPECT_TRUE(res);
  5151. EXPECT_EQ(StatusCode::OK_200, res->status);
  5152. res = cli.Get("/hi%23key1=val1=key2=val2");
  5153. EXPECT_TRUE(res);
  5154. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5155. }
  5156. }
  5157. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5158. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5159. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5160. Server svr;
  5161. std::vector<std::string> targets;
  5162. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5163. targets.push_back(req.target);
  5164. });
  5165. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5166. auto se = detail::scope_exit([&] {
  5167. svr.stop();
  5168. thread.join();
  5169. ASSERT_FALSE(svr.is_running());
  5170. });
  5171. svr.wait_until_ready();
  5172. Client cli(HOST, PORT);
  5173. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5174. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5175. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5176. // A '?' after the '#' belongs to the fragment, not to the query.
  5177. Request req;
  5178. req.method = "GET";
  5179. req.path = "/hi#f?x=1";
  5180. req.params.emplace("a", "1");
  5181. Response res;
  5182. auto error = Error::Success;
  5183. EXPECT_TRUE(cli.send(req, res, error));
  5184. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5185. "/hi?a=1"}),
  5186. targets);
  5187. }
  5188. TEST(HeaderWriter, SetHeaderWriter) {
  5189. Server svr;
  5190. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5191. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5192. return detail::write_headers(strm, hdrs);
  5193. });
  5194. svr.Get("/hi", [](const Request &req, Response &res) {
  5195. auto it = req.headers.find("CustomClientHeader");
  5196. EXPECT_TRUE(it != req.headers.end());
  5197. EXPECT_EQ(it->second, "CustomClientValue");
  5198. res.set_content("Hello World!\n", "text/plain");
  5199. });
  5200. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5201. auto se = detail::scope_exit([&] {
  5202. svr.stop();
  5203. thread.join();
  5204. ASSERT_FALSE(svr.is_running());
  5205. });
  5206. svr.wait_until_ready();
  5207. {
  5208. Client cli(HOST, PORT);
  5209. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5210. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5211. return detail::write_headers(strm, hdrs);
  5212. });
  5213. auto res = cli.Get("/hi");
  5214. EXPECT_TRUE(res);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. auto it = res->headers.find("CustomServerHeader");
  5217. EXPECT_TRUE(it != res->headers.end());
  5218. EXPECT_EQ(it->second, "CustomServerValue");
  5219. }
  5220. }
  5221. class ServerTest : public ::testing::Test {
  5222. protected:
  5223. ServerTest()
  5224. : cli_(HOST, PORT)
  5225. #ifdef CPPHTTPLIB_SSL_ENABLED
  5226. ,
  5227. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5228. #endif
  5229. {
  5230. #ifdef CPPHTTPLIB_SSL_ENABLED
  5231. cli_.enable_server_certificate_verification(false);
  5232. #endif
  5233. // Allow LARGE_DATA (100MB) responses
  5234. cli_.set_payload_max_length(200 * 1024 * 1024);
  5235. }
  5236. virtual void SetUp() {
  5237. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5238. svr_.set_payload_max_length(200 * 1024 * 1024);
  5239. svr_.set_mount_point("/", "./www");
  5240. svr_.set_mount_point("/mount", "./www2");
  5241. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5242. svr_.Get("/hi",
  5243. [&](const Request & /*req*/, Response &res) {
  5244. res.set_content("Hello World!", "text/plain");
  5245. })
  5246. .Get("/file_content",
  5247. [&](const Request & /*req*/, Response &res) {
  5248. res.set_file_content("./www/dir/test.html");
  5249. })
  5250. .Get("/file_content_with_content_type",
  5251. [&](const Request & /*req*/, Response &res) {
  5252. res.set_file_content("./www/file", "text/plain");
  5253. })
  5254. .Get("/invalid_file_content",
  5255. [&](const Request & /*req*/, Response &res) {
  5256. res.set_file_content("./www/dir/invalid_file_path");
  5257. })
  5258. .Get("/http_response_splitting",
  5259. [&](const Request & /*req*/, Response &res) {
  5260. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5261. EXPECT_EQ(0U, res.headers.size());
  5262. EXPECT_FALSE(res.has_header("a"));
  5263. res.set_header("a", "1\nSet-Cookie: a=1");
  5264. EXPECT_EQ(0U, res.headers.size());
  5265. EXPECT_FALSE(res.has_header("a"));
  5266. res.set_header("a", "1\rSet-Cookie: a=1");
  5267. EXPECT_EQ(0U, res.headers.size());
  5268. EXPECT_FALSE(res.has_header("a"));
  5269. res.set_header("a\r\nb", "0");
  5270. EXPECT_EQ(0U, res.headers.size());
  5271. EXPECT_FALSE(res.has_header("a"));
  5272. res.set_header("a\rb", "0");
  5273. EXPECT_EQ(0U, res.headers.size());
  5274. EXPECT_FALSE(res.has_header("a"));
  5275. res.set_header("a\nb", "0");
  5276. EXPECT_EQ(0U, res.headers.size());
  5277. EXPECT_FALSE(res.has_header("a"));
  5278. res.set_redirect("1\r\nSet-Cookie: a=1");
  5279. EXPECT_EQ(0U, res.headers.size());
  5280. EXPECT_FALSE(res.has_header("Location"));
  5281. })
  5282. .Get("/slow",
  5283. [&](const Request & /*req*/, Response &res) {
  5284. std::this_thread::sleep_for(std::chrono::seconds(4));
  5285. res.set_content("slow", "text/plain");
  5286. })
  5287. #if 0
  5288. .Post("/slowpost",
  5289. [&](const Request & /*req*/, Response &res) {
  5290. std::this_thread::sleep_for(std::chrono::seconds(2));
  5291. res.set_content("slow", "text/plain");
  5292. })
  5293. #endif
  5294. .Get("/remote_addr",
  5295. [&](const Request &req, Response &res) {
  5296. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5297. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5298. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5299. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5300. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5301. #endif
  5302. res.set_content(req.remote_addr, "text/plain");
  5303. })
  5304. .Get("/local_addr",
  5305. [&](const Request &req, Response &res) {
  5306. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5307. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5308. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5309. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5310. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5311. #endif
  5312. auto local_addr = req.local_addr;
  5313. auto local_port = std::to_string(req.local_port);
  5314. res.set_content(local_addr.append(":").append(local_port),
  5315. "text/plain");
  5316. })
  5317. .Get("/endwith%",
  5318. [&](const Request & /*req*/, Response &res) {
  5319. res.set_content("Hello World!", "text/plain");
  5320. })
  5321. .Get("/a\\+\\+b",
  5322. [&](const Request &req, Response &res) {
  5323. ASSERT_TRUE(req.has_param("a +b"));
  5324. auto val = req.get_param_value("a +b");
  5325. res.set_content(val, "text/plain");
  5326. })
  5327. .Get("/", [&](const Request & /*req*/,
  5328. Response &res) { res.set_redirect("/hi"); })
  5329. .Post("/1",
  5330. [](const Request & /*req*/, Response &res) {
  5331. res.set_redirect("/2", StatusCode::SeeOther_303);
  5332. })
  5333. .Get("/2",
  5334. [](const Request & /*req*/, Response &res) {
  5335. res.set_content("redirected.", "text/plain");
  5336. res.status = StatusCode::OK_200;
  5337. })
  5338. .Post("/person",
  5339. [&](const Request &req, Response &res) {
  5340. if (req.has_param("name") && req.has_param("note")) {
  5341. persons_[req.get_param_value("name")] =
  5342. req.get_param_value("note");
  5343. } else {
  5344. res.status = StatusCode::BadRequest_400;
  5345. }
  5346. })
  5347. .Put("/person",
  5348. [&](const Request &req, Response &res) {
  5349. if (req.has_param("name") && req.has_param("note")) {
  5350. persons_[req.get_param_value("name")] =
  5351. req.get_param_value("note");
  5352. } else {
  5353. res.status = StatusCode::BadRequest_400;
  5354. }
  5355. })
  5356. .Get("/person/(.*)",
  5357. [&](const Request &req, Response &res) {
  5358. string name = req.matches[1];
  5359. if (persons_.find(name) != persons_.end()) {
  5360. auto note = persons_[name];
  5361. res.set_content(note, "text/plain");
  5362. } else {
  5363. res.status = StatusCode::NotFound_404;
  5364. }
  5365. })
  5366. .Delete("/person",
  5367. [&](const Request &req, Response &res) {
  5368. if (req.has_param("name")) {
  5369. string name = req.get_param_value("name");
  5370. if (persons_.find(name) != persons_.end()) {
  5371. persons_.erase(name);
  5372. res.set_content("DELETED", "text/plain");
  5373. } else {
  5374. res.status = StatusCode::NotFound_404;
  5375. }
  5376. } else {
  5377. res.status = StatusCode::BadRequest_400;
  5378. }
  5379. })
  5380. .Post("/x-www-form-urlencoded-json",
  5381. [&](const Request &req, Response &res) {
  5382. auto json = req.get_param_value("json");
  5383. ASSERT_EQ(JSON_DATA, json);
  5384. res.set_content(json, "appliation/json");
  5385. res.status = StatusCode::OK_200;
  5386. })
  5387. .Get("/streamed-chunked",
  5388. [&](const Request & /*req*/, Response &res) {
  5389. res.set_chunked_content_provider(
  5390. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5391. sink.os << "123";
  5392. sink.os << "456";
  5393. sink.os << "789";
  5394. sink.done();
  5395. return true;
  5396. });
  5397. })
  5398. .Get("/streamed-chunked-with-prohibited-trailer",
  5399. [&](const Request & /*req*/, Response &res) {
  5400. auto i = new int(0);
  5401. // Declare both a prohibited trailer (Content-Length) and an
  5402. // allowed one
  5403. res.set_header("Trailer", "Content-Length, X-Allowed");
  5404. res.set_chunked_content_provider(
  5405. "text/plain",
  5406. [i](size_t /*offset*/, DataSink &sink) {
  5407. switch (*i) {
  5408. case 0: sink.os << "123"; break;
  5409. case 1: sink.os << "456"; break;
  5410. case 2: sink.os << "789"; break;
  5411. case 3: {
  5412. sink.done_with_trailer(
  5413. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5414. } break;
  5415. }
  5416. (*i)++;
  5417. return true;
  5418. },
  5419. [i](bool success) {
  5420. EXPECT_TRUE(success);
  5421. delete i;
  5422. });
  5423. })
  5424. .Get("/streamed-chunked2",
  5425. [&](const Request & /*req*/, Response &res) {
  5426. auto i = new int(0);
  5427. res.set_chunked_content_provider(
  5428. "text/plain",
  5429. [i](size_t /*offset*/, DataSink &sink) {
  5430. switch (*i) {
  5431. case 0: sink.os << "123"; break;
  5432. case 1: sink.os << "456"; break;
  5433. case 2: sink.os << "789"; break;
  5434. case 3: sink.done(); break;
  5435. }
  5436. (*i)++;
  5437. return true;
  5438. },
  5439. [i](bool success) {
  5440. EXPECT_TRUE(success);
  5441. delete i;
  5442. });
  5443. })
  5444. .Get("/streamed-chunked-with-trailer",
  5445. [&](const Request & /*req*/, Response &res) {
  5446. auto i = new int(0);
  5447. res.set_header("Trailer", "Dummy1, Dummy2");
  5448. res.set_chunked_content_provider(
  5449. "text/plain",
  5450. [i](size_t /*offset*/, DataSink &sink) {
  5451. switch (*i) {
  5452. case 0: sink.os << "123"; break;
  5453. case 1: sink.os << "456"; break;
  5454. case 2: sink.os << "789"; break;
  5455. case 3: {
  5456. sink.done_with_trailer(
  5457. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5458. } break;
  5459. }
  5460. (*i)++;
  5461. return true;
  5462. },
  5463. [i](bool success) {
  5464. EXPECT_TRUE(success);
  5465. delete i;
  5466. });
  5467. })
  5468. .Get("/streamed",
  5469. [&](const Request & /*req*/, Response &res) {
  5470. res.set_content_provider(
  5471. 6, "text/plain",
  5472. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5473. sink.os << (offset < 3 ? "a" : "b");
  5474. return true;
  5475. });
  5476. })
  5477. .Get("/streamed-without-length",
  5478. [&](const Request & /*req*/, Response &res) {
  5479. auto data = new std::string("abcdefg");
  5480. res.set_content_provider(
  5481. "text/plain",
  5482. [data](size_t offset, DataSink &sink) {
  5483. if (offset < data->size()) {
  5484. sink.os << data->substr(offset);
  5485. }
  5486. sink.done();
  5487. return true;
  5488. },
  5489. [data](bool success) {
  5490. EXPECT_TRUE(success);
  5491. delete data;
  5492. });
  5493. })
  5494. .Get("/streamed-with-range",
  5495. [&](const Request &req, Response &res) {
  5496. auto data = new std::string("abcdefg");
  5497. // An explicit status keeps the server from picking the 206 it
  5498. // would otherwise choose for a ranged request, so the response
  5499. // is not a partial representation.
  5500. auto status = req.get_param_value("status");
  5501. if (status == "200") {
  5502. res.status = StatusCode::OK_200;
  5503. } else if (status == "403") {
  5504. res.status = StatusCode::Forbidden_403;
  5505. }
  5506. res.set_content_provider(
  5507. data->size(), "text/plain",
  5508. [data](size_t offset, size_t length, DataSink &sink) {
  5509. size_t DATA_CHUNK_SIZE = 4;
  5510. const auto &d = *data;
  5511. auto out_len =
  5512. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5513. auto ret =
  5514. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5515. EXPECT_TRUE(ret);
  5516. return true;
  5517. },
  5518. [data, &req](bool success) {
  5519. EXPECT_EQ(success, !req.has_param("error"));
  5520. delete data;
  5521. });
  5522. })
  5523. .Get("/streamed-cancel",
  5524. [&](const Request & /*req*/, Response &res) {
  5525. res.set_content_provider(
  5526. size_t(-1), "text/plain",
  5527. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5528. sink.os << "data_chunk";
  5529. return true;
  5530. });
  5531. })
  5532. .Get("/regex-with-delimiter",
  5533. [&](const Request &req, Response & /*res*/) {
  5534. ASSERT_TRUE(req.has_param("key"));
  5535. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5536. })
  5537. .Get("/with-range",
  5538. [&](const Request & /*req*/, Response &res) {
  5539. res.set_content("abcdefg", "text/plain");
  5540. })
  5541. .Get("/test-start-time",
  5542. [&](const Request &req, Response & /*res*/) {
  5543. EXPECT_NE(req.start_time_,
  5544. std::chrono::steady_clock::time_point::min());
  5545. })
  5546. .Get("/with-range-customized-response",
  5547. [&](const Request & /*req*/, Response &res) {
  5548. res.status = StatusCode::BadRequest_400;
  5549. res.set_content(JSON_DATA, "application/json");
  5550. })
  5551. .Post("/chunked",
  5552. [&](const Request &req, Response & /*res*/) {
  5553. EXPECT_EQ(req.body, "dechunked post body");
  5554. })
  5555. .Post("/large-chunked",
  5556. [&](const Request &req, Response & /*res*/) {
  5557. std::string expected(6 * 30 * 1024u, 'a');
  5558. EXPECT_EQ(req.body, expected);
  5559. })
  5560. .Post("/multipart",
  5561. [&](const Request &req, Response & /*res*/) {
  5562. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5563. req.form.get_field_count("text2") +
  5564. req.form.get_field_count("file3") +
  5565. req.form.get_field_count("file4"));
  5566. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5567. req.form.get_file_count("file2"));
  5568. ASSERT_TRUE(!req.form.has_file("???"));
  5569. ASSERT_TRUE(!req.form.has_field("???"));
  5570. ASSERT_TRUE(req.body.empty());
  5571. {
  5572. const auto &text = req.form.get_field("text1");
  5573. EXPECT_EQ("text default", text);
  5574. }
  5575. {
  5576. const auto &text = req.form.get_field("text2");
  5577. EXPECT_EQ("aωb", text);
  5578. }
  5579. {
  5580. const auto &file = req.form.get_file("file1");
  5581. EXPECT_EQ("hello.txt", file.filename);
  5582. EXPECT_EQ("text/plain", file.content_type);
  5583. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5584. }
  5585. {
  5586. const auto &file = req.form.get_file("file2");
  5587. EXPECT_EQ("world.json", file.filename);
  5588. EXPECT_EQ("application/json", file.content_type);
  5589. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5590. }
  5591. {
  5592. const auto &text = req.form.get_field("file3");
  5593. EXPECT_EQ(0u, text.size());
  5594. }
  5595. {
  5596. const auto &text = req.form.get_field("file4");
  5597. EXPECT_EQ(0u, text.size());
  5598. }
  5599. })
  5600. .Post("/multipart/multi_file_values",
  5601. [&](const Request &req, Response & /*res*/) {
  5602. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5603. req.form.get_field_count("multi_text1"));
  5604. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5605. ASSERT_TRUE(!req.form.has_file("???"));
  5606. ASSERT_TRUE(!req.form.has_field("???"));
  5607. ASSERT_TRUE(req.body.empty());
  5608. {
  5609. const auto &text = req.form.get_field("text");
  5610. EXPECT_EQ("default text", text);
  5611. }
  5612. {
  5613. const auto &text1_values = req.form.get_fields("multi_text1");
  5614. EXPECT_EQ(2u, text1_values.size());
  5615. EXPECT_EQ("aaaaa", text1_values[0]);
  5616. EXPECT_EQ("bbbbb", text1_values[1]);
  5617. }
  5618. {
  5619. const auto &file1_values = req.form.get_files("multi_file1");
  5620. EXPECT_EQ(2u, file1_values.size());
  5621. auto file1 = file1_values[0];
  5622. EXPECT_EQ(file1.filename, "hello.txt");
  5623. EXPECT_EQ(file1.content_type, "text/plain");
  5624. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5625. auto file2 = file1_values[1];
  5626. EXPECT_EQ(file2.filename, "world.json");
  5627. EXPECT_EQ(file2.content_type, "application/json");
  5628. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5629. }
  5630. })
  5631. .Post("/empty",
  5632. [&](const Request &req, Response &res) {
  5633. EXPECT_EQ(req.body, "");
  5634. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5635. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5636. res.set_content("empty", "text/plain");
  5637. })
  5638. .Post("/empty-no-content-type",
  5639. [&](const Request &req, Response &res) {
  5640. EXPECT_EQ(req.body, "");
  5641. EXPECT_FALSE(req.has_header("Content-Type"));
  5642. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5643. res.set_content("empty-no-content-type", "text/plain");
  5644. })
  5645. .Post("/path-only",
  5646. [&](const Request &req, Response &res) {
  5647. EXPECT_EQ(req.body, "");
  5648. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5649. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5650. res.set_content("path-only", "text/plain");
  5651. })
  5652. .Post("/path-headers-only",
  5653. [&](const Request &req, Response &res) {
  5654. EXPECT_EQ(req.body, "");
  5655. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5656. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5657. EXPECT_EQ("world", req.get_header_value("hello"));
  5658. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5659. res.set_content("path-headers-only", "text/plain");
  5660. })
  5661. .Post("/post-large",
  5662. [&](const Request &req, Response &res) {
  5663. EXPECT_EQ(req.body, LARGE_DATA);
  5664. res.set_content(req.body, "text/plain");
  5665. })
  5666. .Post("/post-loopback",
  5667. [&](const Request &, Response &res,
  5668. ContentReader const &content_reader) {
  5669. std::string body;
  5670. content_reader([&](const char *data, size_t data_length) {
  5671. body.append(data, data_length);
  5672. return true;
  5673. });
  5674. res.set_content(body, "text/plain");
  5675. })
  5676. .Put("/put-loopback",
  5677. [&](const Request &, Response &res,
  5678. ContentReader const &content_reader) {
  5679. std::string body;
  5680. content_reader([&](const char *data, size_t data_length) {
  5681. body.append(data, data_length);
  5682. return true;
  5683. });
  5684. res.set_content(body, "text/plain");
  5685. })
  5686. .Patch("/patch-loopback",
  5687. [&](const Request &, Response &res,
  5688. ContentReader const &content_reader) {
  5689. std::string body;
  5690. content_reader([&](const char *data, size_t data_length) {
  5691. body.append(data, data_length);
  5692. return true;
  5693. });
  5694. res.set_content(body, "text/plain");
  5695. })
  5696. .Put("/empty-no-content-type",
  5697. [&](const Request &req, Response &res) {
  5698. EXPECT_EQ(req.body, "");
  5699. EXPECT_FALSE(req.has_header("Content-Type"));
  5700. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5701. res.set_content("empty-no-content-type", "text/plain");
  5702. })
  5703. .Put("/put",
  5704. [&](const Request &req, Response &res) {
  5705. EXPECT_EQ(req.body, "PUT");
  5706. res.set_content(req.body, "text/plain");
  5707. })
  5708. .Put("/put-large",
  5709. [&](const Request &req, Response &res) {
  5710. EXPECT_EQ(req.body, LARGE_DATA);
  5711. res.set_content(req.body, "text/plain");
  5712. })
  5713. .Patch("/patch",
  5714. [&](const Request &req, Response &res) {
  5715. EXPECT_EQ(req.body, "PATCH");
  5716. res.set_content(req.body, "text/plain");
  5717. })
  5718. .Delete("/delete",
  5719. [&](const Request & /*req*/, Response &res) {
  5720. res.set_content("DELETE", "text/plain");
  5721. })
  5722. .Delete("/delete-body",
  5723. [&](const Request &req, Response &res) {
  5724. EXPECT_EQ(req.body, "content");
  5725. res.set_content(req.body, "text/plain");
  5726. })
  5727. .Options(R"(\*)",
  5728. [&](const Request & /*req*/, Response &res) {
  5729. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5730. })
  5731. .CustomRoute("PROPFIND", "/dav/:id",
  5732. [&](const Request &req, Response &res) {
  5733. res.set_header("x-body-size",
  5734. std::to_string(req.body.size()));
  5735. res.set_header("x-matched-route", req.matched_route);
  5736. res.set_header("x-dav-id", req.path_params.at("id"));
  5737. res.status = StatusCode::MultiStatus_207;
  5738. res.set_content(req.body, "application/xml");
  5739. })
  5740. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5741. [&](const Request &req, Response &res) {
  5742. res.set_header("x-dav-match", req.matches[1]);
  5743. res.status = StatusCode::MultiStatus_207;
  5744. })
  5745. .CustomRoute("MKCOL", "/dav-mkcol",
  5746. [&](const Request &req, Response &res) {
  5747. EXPECT_TRUE(req.body.empty());
  5748. res.status = StatusCode::Created_201;
  5749. })
  5750. .CustomRoute(
  5751. "REPORT", "/dav-report",
  5752. [&](const Request & /*req*/, Response &res,
  5753. const ContentReader &content_reader) {
  5754. std::string body;
  5755. content_reader([&](const char *data, size_t data_length) {
  5756. body.append(data, data_length);
  5757. return true;
  5758. });
  5759. res.set_header("x-body-size", std::to_string(body.size()));
  5760. res.status = StatusCode::MultiStatus_207;
  5761. res.set_content(body, "application/xml");
  5762. })
  5763. .Get("/request-target",
  5764. [&](const Request &req, Response & /*res*/) {
  5765. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5766. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5767. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5768. })
  5769. .Get("/long-query-value",
  5770. [&](const Request &req, Response & /*res*/) {
  5771. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5772. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5773. })
  5774. .Get("/too-long-query-value",
  5775. [&](const Request &req, Response & /*res*/) {
  5776. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5777. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5778. })
  5779. .Get("/array-param",
  5780. [&](const Request &req, Response & /*res*/) {
  5781. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5782. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5783. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5784. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5785. })
  5786. .Get("/array-param-values",
  5787. [&](const Request &req, Response & /*res*/) {
  5788. auto values = req.get_param_values("array");
  5789. EXPECT_EQ(3u, values.size());
  5790. EXPECT_EQ("value1", values[0]);
  5791. EXPECT_EQ("value2", values[1]);
  5792. EXPECT_EQ("value3", values[2]);
  5793. auto empty = req.get_param_values("nonexistent");
  5794. EXPECT_TRUE(empty.empty());
  5795. })
  5796. .Post("/validate-no-multiple-headers",
  5797. [&](const Request &req, Response & /*res*/) {
  5798. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5799. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5800. })
  5801. .Post("/content_receiver",
  5802. [&](const Request &req, Response &res,
  5803. const ContentReader &content_reader) {
  5804. if (req.is_multipart_form_data()) {
  5805. std::vector<FormData> items;
  5806. content_reader(
  5807. [&](const FormData &file) {
  5808. items.push_back(file);
  5809. return true;
  5810. },
  5811. [&](const char *data, size_t data_length) {
  5812. items.back().content.append(data, data_length);
  5813. return true;
  5814. });
  5815. EXPECT_EQ(5u, items.size());
  5816. {
  5817. const auto &file = get_file_value(items, "text1");
  5818. EXPECT_TRUE(file.filename.empty());
  5819. EXPECT_EQ("text default", file.content);
  5820. }
  5821. {
  5822. const auto &file = get_file_value(items, "text2");
  5823. EXPECT_TRUE(file.filename.empty());
  5824. EXPECT_EQ("aωb", file.content);
  5825. }
  5826. {
  5827. const auto &file = get_file_value(items, "file1");
  5828. EXPECT_EQ("hello.txt", file.filename);
  5829. EXPECT_EQ("text/plain", file.content_type);
  5830. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5831. }
  5832. {
  5833. const auto &file = get_file_value(items, "file2");
  5834. EXPECT_EQ("world.json", file.filename);
  5835. EXPECT_EQ("application/json", file.content_type);
  5836. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5837. }
  5838. {
  5839. const auto &file = get_file_value(items, "file3");
  5840. EXPECT_TRUE(file.filename.empty());
  5841. EXPECT_EQ("application/octet-stream", file.content_type);
  5842. EXPECT_EQ(0u, file.content.size());
  5843. }
  5844. } else {
  5845. std::string body;
  5846. content_reader([&](const char *data, size_t data_length) {
  5847. EXPECT_EQ(7U, data_length);
  5848. body.append(data, data_length);
  5849. return true;
  5850. });
  5851. EXPECT_EQ(body, "content");
  5852. res.set_content(body, "text/plain");
  5853. }
  5854. })
  5855. .Put("/content_receiver",
  5856. [&](const Request & /*req*/, Response &res,
  5857. const ContentReader &content_reader) {
  5858. std::string body;
  5859. content_reader([&](const char *data, size_t data_length) {
  5860. body.append(data, data_length);
  5861. return true;
  5862. });
  5863. EXPECT_EQ(body, "content");
  5864. res.set_content(body, "text/plain");
  5865. })
  5866. .Patch("/content_receiver",
  5867. [&](const Request & /*req*/, Response &res,
  5868. const ContentReader &content_reader) {
  5869. std::string body;
  5870. content_reader([&](const char *data, size_t data_length) {
  5871. body.append(data, data_length);
  5872. return true;
  5873. });
  5874. EXPECT_EQ(body, "content");
  5875. res.set_content(body, "text/plain");
  5876. })
  5877. .Post("/query-string-and-body",
  5878. [&](const Request &req, Response & /*res*/) {
  5879. ASSERT_TRUE(req.has_param("key"));
  5880. EXPECT_EQ(req.get_param_value("key"), "value");
  5881. EXPECT_EQ(req.body, "content");
  5882. })
  5883. .Get("/last-request",
  5884. [&](const Request &req, Response & /*res*/) {
  5885. EXPECT_EQ("close", req.get_header_value("Connection"));
  5886. })
  5887. .Get(R"(/redirect/(\d+))",
  5888. [&](const Request &req, Response &res) {
  5889. auto num = std::stoi(req.matches[1]) + 1;
  5890. std::string url = "/redirect/" + std::to_string(num);
  5891. res.set_redirect(url);
  5892. })
  5893. .Post("/binary",
  5894. [&](const Request &req, Response &res) {
  5895. EXPECT_EQ(4U, req.body.size());
  5896. EXPECT_EQ("application/octet-stream",
  5897. req.get_header_value("Content-Type"));
  5898. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5899. res.set_content(req.body, "application/octet-stream");
  5900. })
  5901. .Put("/binary",
  5902. [&](const Request &req, Response &res) {
  5903. EXPECT_EQ(4U, req.body.size());
  5904. EXPECT_EQ("application/octet-stream",
  5905. req.get_header_value("Content-Type"));
  5906. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5907. res.set_content(req.body, "application/octet-stream");
  5908. })
  5909. .Patch("/binary",
  5910. [&](const Request &req, Response &res) {
  5911. EXPECT_EQ(4U, req.body.size());
  5912. EXPECT_EQ("application/octet-stream",
  5913. req.get_header_value("Content-Type"));
  5914. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5915. res.set_content(req.body, "application/octet-stream");
  5916. })
  5917. .Delete("/binary",
  5918. [&](const Request &req, Response &res) {
  5919. EXPECT_EQ(4U, req.body.size());
  5920. EXPECT_EQ("application/octet-stream",
  5921. req.get_header_value("Content-Type"));
  5922. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5923. res.set_content(req.body, "application/octet-stream");
  5924. })
  5925. .Get("/issue1772",
  5926. [&](const Request & /*req*/, Response &res) {
  5927. res.status = 401;
  5928. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5929. })
  5930. .Delete("/issue609",
  5931. [](const httplib::Request &, httplib::Response &res,
  5932. const httplib::ContentReader &) {
  5933. res.set_content("ok", "text/plain");
  5934. })
  5935. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5936. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5937. .Get("/compress",
  5938. [&](const Request & /*req*/, Response &res) {
  5939. res.set_content(
  5940. "12345678901234567890123456789012345678901234567890123456789"
  5941. "01234567890123456789012345678901234567890",
  5942. "text/plain");
  5943. })
  5944. .Get("/compress-with-charset",
  5945. [&](const Request & /*req*/, Response &res) {
  5946. res.set_content(
  5947. "12345678901234567890123456789012345678901234567890123456789"
  5948. "01234567890123456789012345678901234567890",
  5949. "application/json; charset=utf-8");
  5950. })
  5951. .Get("/nocompress",
  5952. [&](const Request & /*req*/, Response &res) {
  5953. res.set_content(
  5954. "12345678901234567890123456789012345678901234567890123456789"
  5955. "01234567890123456789012345678901234567890",
  5956. "application/octet-stream");
  5957. })
  5958. .Post("/compress-multipart",
  5959. [&](const Request &req, Response & /*res*/) {
  5960. EXPECT_EQ(2u, req.form.fields.size());
  5961. ASSERT_TRUE(!req.form.has_field("???"));
  5962. {
  5963. const auto &text = req.form.get_field("key1");
  5964. EXPECT_EQ("test", text);
  5965. }
  5966. {
  5967. const auto &text = req.form.get_field("key2");
  5968. EXPECT_EQ("--abcdefg123", text);
  5969. }
  5970. })
  5971. #endif
  5972. ;
  5973. persons_["john"] = "programmer";
  5974. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5975. svr_.wait_until_ready();
  5976. }
  5977. virtual void TearDown() {
  5978. svr_.stop();
  5979. if (!request_threads_.empty()) {
  5980. std::this_thread::sleep_for(std::chrono::seconds(1));
  5981. for (auto &t : request_threads_) {
  5982. t.join();
  5983. }
  5984. }
  5985. t_.join();
  5986. }
  5987. map<string, string> persons_;
  5988. #ifdef CPPHTTPLIB_SSL_ENABLED
  5989. SSLClient cli_;
  5990. SSLServer svr_;
  5991. #else
  5992. Client cli_;
  5993. Server svr_;
  5994. #endif
  5995. thread t_;
  5996. std::vector<thread> request_threads_;
  5997. };
  5998. TEST_F(ServerTest, GetMethod200) {
  5999. auto res = cli_.Get("/hi");
  6000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6001. EXPECT_EQ("HTTP/1.1", res->version);
  6002. EXPECT_EQ(StatusCode::OK_200, res->status);
  6003. EXPECT_EQ("OK", res->reason);
  6004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6005. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6006. EXPECT_EQ("Hello World!", res->body);
  6007. }
  6008. TEST_F(ServerTest, GetEmptyFile) {
  6009. auto res = cli_.Get("/empty_file");
  6010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6011. EXPECT_EQ(StatusCode::OK_200, res->status);
  6012. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6013. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6014. EXPECT_EQ("", res->body);
  6015. }
  6016. TEST_F(ServerTest, GetFileContent) {
  6017. auto res = cli_.Get("/file_content");
  6018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6021. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6022. EXPECT_EQ("test.html", res->body);
  6023. }
  6024. TEST_F(ServerTest, GetFileContentWithRange) {
  6025. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6028. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6030. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6031. EXPECT_EQ("est", res->body);
  6032. }
  6033. TEST_F(ServerTest, GetFileContentWithContentType) {
  6034. auto res = cli_.Get("/file_content_with_content_type");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. EXPECT_EQ(StatusCode::OK_200, res->status);
  6037. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6038. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6039. EXPECT_EQ("file\n", res->body);
  6040. }
  6041. TEST_F(ServerTest, GetInvalidFileContent) {
  6042. auto res = cli_.Get("/invalid_file_content");
  6043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6044. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6045. }
  6046. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6047. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. EXPECT_EQ("HTTP/1.1", res->version);
  6050. EXPECT_EQ(StatusCode::OK_200, res->status);
  6051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6052. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6053. EXPECT_EQ("Hello World!", res->body);
  6054. }
  6055. TEST_F(ServerTest, GetMethod302) {
  6056. auto res = cli_.Get("/");
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. EXPECT_EQ(StatusCode::Found_302, res->status);
  6059. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6060. }
  6061. TEST_F(ServerTest, GetMethod302Redirect) {
  6062. cli_.set_follow_location(true);
  6063. auto res = cli_.Get("/");
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. EXPECT_EQ(StatusCode::OK_200, res->status);
  6066. EXPECT_EQ("Hello World!", res->body);
  6067. EXPECT_EQ("/hi", res->location);
  6068. }
  6069. TEST_F(ServerTest, GetMethod404) {
  6070. auto res = cli_.Get("/invalid");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6073. }
  6074. TEST_F(ServerTest, HeadMethod200) {
  6075. auto res = cli_.Head("/hi");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::OK_200, res->status);
  6078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6079. EXPECT_TRUE(res->body.empty());
  6080. }
  6081. TEST_F(ServerTest, HeadMethod200Static) {
  6082. auto res = cli_.Head("/mount/dir/index.html");
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::OK_200, res->status);
  6085. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6086. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6087. EXPECT_TRUE(res->body.empty());
  6088. }
  6089. TEST_F(ServerTest, HeadMethod404) {
  6090. auto res = cli_.Head("/invalid");
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6093. EXPECT_TRUE(res->body.empty());
  6094. }
  6095. TEST_F(ServerTest, GetMethodPersonJohn) {
  6096. auto res = cli_.Get("/person/john");
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::OK_200, res->status);
  6099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6100. EXPECT_EQ("programmer", res->body);
  6101. }
  6102. TEST_F(ServerTest, PostMethod1) {
  6103. auto res = cli_.Get("/person/john1");
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6106. res = cli_.Post("/person", "name=john1&note=coder",
  6107. "application/x-www-form-urlencoded");
  6108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6109. ASSERT_EQ(StatusCode::OK_200, res->status);
  6110. res = cli_.Get("/person/john1");
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. ASSERT_EQ(StatusCode::OK_200, res->status);
  6113. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6114. ASSERT_EQ("coder", res->body);
  6115. }
  6116. TEST_F(ServerTest, PostMethod2) {
  6117. auto res = cli_.Get("/person/john2");
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6120. Params params;
  6121. params.emplace("name", "john2");
  6122. params.emplace("note", "coder");
  6123. res = cli_.Post("/person", params);
  6124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6125. ASSERT_EQ(StatusCode::OK_200, res->status);
  6126. res = cli_.Get("/person/john2");
  6127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6128. ASSERT_EQ(StatusCode::OK_200, res->status);
  6129. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6130. ASSERT_EQ("coder", res->body);
  6131. }
  6132. TEST_F(ServerTest, PutMethod3) {
  6133. auto res = cli_.Get("/person/john3");
  6134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6135. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6136. Params params;
  6137. params.emplace("name", "john3");
  6138. params.emplace("note", "coder");
  6139. res = cli_.Put("/person", params);
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. ASSERT_EQ(StatusCode::OK_200, res->status);
  6142. res = cli_.Get("/person/john3");
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. ASSERT_EQ(StatusCode::OK_200, res->status);
  6145. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6146. ASSERT_EQ("coder", res->body);
  6147. }
  6148. TEST_F(ServerTest, DeleteMethod1) {
  6149. auto res = cli_.Get("/person/john4");
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6152. Params params;
  6153. params.emplace("name", "john4");
  6154. params.emplace("note", "coder");
  6155. res = cli_.Post("/person", params);
  6156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6157. ASSERT_EQ(StatusCode::OK_200, res->status);
  6158. res = cli_.Get("/person/john4");
  6159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6160. ASSERT_EQ(StatusCode::OK_200, res->status);
  6161. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6162. ASSERT_EQ("coder", res->body);
  6163. Params delete_params;
  6164. delete_params.emplace("name", "john4");
  6165. res = cli_.Delete("/person", delete_params);
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. ASSERT_EQ(StatusCode::OK_200, res->status);
  6168. ASSERT_EQ("DELETED", res->body);
  6169. res = cli_.Get("/person/john4");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6172. }
  6173. TEST_F(ServerTest, DeleteMethod2) {
  6174. auto res = cli_.Get("/person/john5");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6177. Params params;
  6178. params.emplace("name", "john5");
  6179. params.emplace("note", "developer");
  6180. res = cli_.Post("/person", params);
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. ASSERT_EQ(StatusCode::OK_200, res->status);
  6183. res = cli_.Get("/person/john5");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. ASSERT_EQ(StatusCode::OK_200, res->status);
  6186. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6187. ASSERT_EQ("developer", res->body);
  6188. Params delete_params;
  6189. delete_params.emplace("name", "john5");
  6190. Headers headers;
  6191. headers.emplace("Custom-Header", "test-value");
  6192. res = cli_.Delete("/person", headers, delete_params);
  6193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6194. ASSERT_EQ(StatusCode::OK_200, res->status);
  6195. ASSERT_EQ("DELETED", res->body);
  6196. res = cli_.Get("/person/john5");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6199. }
  6200. TEST_F(ServerTest, DeleteMethod3) {
  6201. auto res = cli_.Get("/person/john6");
  6202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6203. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6204. Params params;
  6205. params.emplace("name", "john6");
  6206. params.emplace("note", "tester");
  6207. res = cli_.Post("/person", params);
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. ASSERT_EQ(StatusCode::OK_200, res->status);
  6210. res = cli_.Get("/person/john6");
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. ASSERT_EQ(StatusCode::OK_200, res->status);
  6213. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6214. ASSERT_EQ("tester", res->body);
  6215. Params delete_params;
  6216. delete_params.emplace("name", "john6");
  6217. Headers headers;
  6218. headers.emplace("Custom-Header", "test-value");
  6219. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. ASSERT_EQ(StatusCode::OK_200, res->status);
  6222. ASSERT_EQ("DELETED", res->body);
  6223. res = cli_.Get("/person/john6");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6226. }
  6227. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6228. Params params;
  6229. params.emplace("json", JSON_DATA);
  6230. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. ASSERT_EQ(JSON_DATA, res->body);
  6234. }
  6235. TEST_F(ServerTest, PostEmptyContent) {
  6236. auto res = cli_.Post("/empty", "", "text/plain");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. ASSERT_EQ(StatusCode::OK_200, res->status);
  6239. ASSERT_EQ("empty", res->body);
  6240. }
  6241. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6242. auto res = cli_.Post("/empty-no-content-type");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. ASSERT_EQ(StatusCode::OK_200, res->status);
  6245. ASSERT_EQ("empty-no-content-type", res->body);
  6246. }
  6247. TEST_F(ServerTest, PostPathOnly) {
  6248. auto res = cli_.Post("/path-only");
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. ASSERT_EQ(StatusCode::OK_200, res->status);
  6251. ASSERT_EQ("path-only", res->body);
  6252. }
  6253. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6254. auto res = cli_.Post("/path-headers-only",
  6255. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. ASSERT_EQ(StatusCode::OK_200, res->status);
  6258. ASSERT_EQ("path-headers-only", res->body);
  6259. }
  6260. TEST_F(ServerTest, PostLarge) {
  6261. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6263. ASSERT_EQ(StatusCode::OK_200, res->status);
  6264. EXPECT_EQ(LARGE_DATA, res->body);
  6265. }
  6266. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6267. auto res = cli_.Put("/empty-no-content-type");
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. ASSERT_EQ(StatusCode::OK_200, res->status);
  6270. ASSERT_EQ("empty-no-content-type", res->body);
  6271. }
  6272. TEST_F(ServerTest, GetMethodDir) {
  6273. auto res = cli_.Get("/dir/");
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::OK_200, res->status);
  6276. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6277. auto body = R"(<html>
  6278. <head>
  6279. </head>
  6280. <body>
  6281. <a href="/dir/test.html">Test</a>
  6282. <a href="/hi">hi</a>
  6283. </body>
  6284. </html>
  6285. )";
  6286. EXPECT_EQ(body, res->body);
  6287. }
  6288. TEST_F(ServerTest, GetMethodDirTest) {
  6289. auto res = cli_.Get("/dir/test.html");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::OK_200, res->status);
  6292. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6293. EXPECT_EQ("test.html", res->body);
  6294. }
  6295. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6296. auto res = cli_.Get("/dir/../dir/test.html");
  6297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6298. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6299. }
  6300. TEST_F(ServerTest, GetMethodInvalidPath) {
  6301. auto res = cli_.Get("/dir/../test.html");
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6304. }
  6305. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6306. auto res = cli_.Get("/../www/dir/test.html");
  6307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6309. }
  6310. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6311. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6314. }
  6315. TEST_F(ServerTest, GetMethodDirMountTest) {
  6316. auto res = cli_.Get("/mount/dir/test.html");
  6317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6320. EXPECT_EQ("test.html", res->body);
  6321. }
  6322. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6323. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6326. }
  6327. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6328. auto res = cli_.Get("/mount/dir/../test.html");
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6331. }
  6332. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6333. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6336. }
  6337. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6338. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6341. }
  6342. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6343. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6346. }
  6347. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6348. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6351. }
  6352. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6353. auto res = cli_.Get("/mount/dir");
  6354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6355. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6356. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6357. }
  6358. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6359. auto res = cli_.Get("//dir");
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6362. EXPECT_FALSE(res->has_header("Location"));
  6363. }
  6364. TEST_F(ServerTest, PostMethod303) {
  6365. auto res = cli_.Post("/1", "body", "text/plain");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6368. EXPECT_EQ("/2", res->get_header_value("Location"));
  6369. }
  6370. TEST_F(ServerTest, PostMethod303Redirect) {
  6371. cli_.set_follow_location(true);
  6372. auto res = cli_.Post("/1", "body", "text/plain");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::OK_200, res->status);
  6375. EXPECT_EQ("redirected.", res->body);
  6376. EXPECT_EQ("/2", res->location);
  6377. }
  6378. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6379. auto res = cli_.Get("/dir/test.abcde");
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. EXPECT_EQ(StatusCode::OK_200, res->status);
  6382. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6383. EXPECT_EQ("abcde", res->body);
  6384. }
  6385. TEST_F(ServerTest, StaticFileRange) {
  6386. auto res =
  6387. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6390. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6391. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6392. EXPECT_EQ(true, res->has_header("Content-Range"));
  6393. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6394. EXPECT_EQ(std::string("cd"), res->body);
  6395. }
  6396. TEST_F(ServerTest, StaticFileRanges) {
  6397. auto res = cli_.Get("/dir/test.abcde",
  6398. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6401. EXPECT_TRUE(
  6402. res->get_header_value("Content-Type")
  6403. .find(
  6404. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6405. 0);
  6406. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6407. }
  6408. TEST_F(ServerTest, StaticFileRangeHead) {
  6409. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6412. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6413. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6414. EXPECT_EQ(true, res->has_header("Content-Range"));
  6415. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6416. }
  6417. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6418. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6420. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6422. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6423. EXPECT_EQ(true, res->has_header("Content-Range"));
  6424. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6425. res->get_header_value("Content-Range"));
  6426. EXPECT_EQ("LAST\n", res->body);
  6427. }
  6428. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6429. auto res =
  6430. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6434. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6435. EXPECT_EQ(true, res->has_header("Content-Range"));
  6436. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6437. }
  6438. TEST_F(ServerTest, StaticFileBigFile) {
  6439. auto res = cli_.Get("/dir/1MB.txt");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6443. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6444. }
  6445. TEST_F(ServerTest, InvalidBaseDirMount) {
  6446. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6447. }
  6448. TEST_F(ServerTest, Binary) {
  6449. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6450. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6451. "application/octet-stream");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. ASSERT_EQ(StatusCode::OK_200, res->status);
  6454. ASSERT_EQ(4U, res->body.size());
  6455. res = cli_.Put("/binary", binary.data(), binary.size(),
  6456. "application/octet-stream");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. ASSERT_EQ(StatusCode::OK_200, res->status);
  6459. ASSERT_EQ(4U, res->body.size());
  6460. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6461. "application/octet-stream");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. ASSERT_EQ(StatusCode::OK_200, res->status);
  6464. ASSERT_EQ(4U, res->body.size());
  6465. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6466. "application/octet-stream");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. ASSERT_EQ(StatusCode::OK_200, res->status);
  6469. ASSERT_EQ(4U, res->body.size());
  6470. }
  6471. TEST_F(ServerTest, BinaryString) {
  6472. auto binary = std::string("\x00\x01\x02\x03", 4);
  6473. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. ASSERT_EQ(StatusCode::OK_200, res->status);
  6476. ASSERT_EQ(4U, res->body.size());
  6477. res = cli_.Put("/binary", binary, "application/octet-stream");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. ASSERT_EQ(StatusCode::OK_200, res->status);
  6480. ASSERT_EQ(4U, res->body.size());
  6481. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6483. ASSERT_EQ(StatusCode::OK_200, res->status);
  6484. ASSERT_EQ(4U, res->body.size());
  6485. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. ASSERT_EQ(StatusCode::OK_200, res->status);
  6488. ASSERT_EQ(4U, res->body.size());
  6489. }
  6490. TEST_F(ServerTest, EmptyRequest) {
  6491. auto res = cli_.Get("");
  6492. ASSERT_TRUE(!res);
  6493. EXPECT_EQ(Error::Connection, res.error());
  6494. }
  6495. TEST_F(ServerTest, LongRequest) {
  6496. std::string request;
  6497. for (size_t i = 0; i < 545; i++) {
  6498. request += "/TooLongRequest";
  6499. }
  6500. request += "OK";
  6501. auto res = cli_.Get(request.c_str());
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6504. }
  6505. TEST_F(ServerTest, TooLongRequest) {
  6506. std::string request;
  6507. for (size_t i = 0; i < 546; i++) {
  6508. request += "/TooLongRequest";
  6509. }
  6510. request += "_NG";
  6511. auto start = std::chrono::high_resolution_clock::now();
  6512. cli_.set_keep_alive(true);
  6513. auto res = cli_.Get(request.c_str());
  6514. auto end = std::chrono::high_resolution_clock::now();
  6515. auto elapsed =
  6516. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6517. .count();
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6520. EXPECT_LE(elapsed, 1000);
  6521. EXPECT_EQ("close", res->get_header_value("Connection"));
  6522. EXPECT_FALSE(cli_.is_socket_open());
  6523. }
  6524. TEST_F(ServerTest, AlmostTooLongRequest) {
  6525. // test for #2046 - URI length check shouldn't include other content on req
  6526. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6527. // leading /, space, HTTP/1.1)
  6528. std::string request =
  6529. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6530. auto res = cli_.Get(request.c_str());
  6531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6532. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6533. }
  6534. TEST_F(ServerTest, LongHeader) {
  6535. Request req;
  6536. req.method = "GET";
  6537. req.path = "/hi";
  6538. std::string host_and_port;
  6539. host_and_port += HOST;
  6540. host_and_port += ":";
  6541. host_and_port += std::to_string(PORT);
  6542. req.headers.emplace("Host", host_and_port.c_str());
  6543. req.headers.emplace("Accept", "*/*");
  6544. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6545. req.headers.emplace(
  6546. "Header-Name",
  6547. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6548. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6549. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@");
  6576. auto res = std::make_shared<Response>();
  6577. auto error = Error::Success;
  6578. auto ret = cli_.send(req, *res, error);
  6579. ASSERT_TRUE(ret);
  6580. EXPECT_EQ(StatusCode::OK_200, res->status);
  6581. }
  6582. TEST_F(ServerTest, LongQueryValue) {
  6583. auto start = std::chrono::high_resolution_clock::now();
  6584. cli_.set_keep_alive(true);
  6585. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6586. auto end = std::chrono::high_resolution_clock::now();
  6587. auto elapsed =
  6588. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6589. .count();
  6590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6591. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6592. EXPECT_LE(elapsed, 1000);
  6593. EXPECT_EQ("close", res->get_header_value("Connection"));
  6594. EXPECT_FALSE(cli_.is_socket_open());
  6595. }
  6596. TEST_F(ServerTest, TooLongQueryValue) {
  6597. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6598. ASSERT_FALSE(res);
  6599. EXPECT_EQ(Error::Read, res.error());
  6600. }
  6601. TEST_F(ServerTest, TooLongHeader) {
  6602. Request req;
  6603. req.method = "GET";
  6604. req.path = "/hi";
  6605. std::string host_and_port;
  6606. host_and_port += HOST;
  6607. host_and_port += ":";
  6608. host_and_port += std::to_string(PORT);
  6609. req.headers.emplace("Host", host_and_port.c_str());
  6610. req.headers.emplace("Accept", "*/*");
  6611. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6612. req.headers.emplace(
  6613. "Header-Name",
  6614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@");
  6643. auto res = std::make_shared<Response>();
  6644. auto error = Error::Success;
  6645. auto ret = cli_.send(req, *res, error);
  6646. ASSERT_TRUE(ret);
  6647. EXPECT_EQ(StatusCode::OK_200, res->status);
  6648. }
  6649. TEST_F(ServerTest, HeaderCountAtLimit) {
  6650. // Test with headers just under the 100 limit
  6651. httplib::Headers headers;
  6652. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6653. // This should keep us just under the 100 header limit
  6654. for (int i = 0; i < 95; i++) {
  6655. std::string name = "X-Test-Header-" + std::to_string(i);
  6656. std::string value = "value" + std::to_string(i);
  6657. headers.emplace(name, value);
  6658. }
  6659. // This should work fine as we're under the limit
  6660. auto res = cli_.Get("/hi", headers);
  6661. EXPECT_TRUE(res);
  6662. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6663. }
  6664. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6665. // Test with many headers to exceed the 100 limit
  6666. httplib::Headers headers;
  6667. // Add 150 headers to definitely exceed the 100 limit
  6668. for (int i = 0; i < 150; i++) {
  6669. std::string name = "X-Test-Header-" + std::to_string(i);
  6670. std::string value = "value" + std::to_string(i);
  6671. headers.emplace(name, value);
  6672. }
  6673. // This should fail due to exceeding header count limit
  6674. cli_.set_keep_alive(true);
  6675. auto res = cli_.Get("/hi", headers);
  6676. // The server should respond with 400 Bad Request
  6677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6678. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6679. EXPECT_EQ("close", res->get_header_value("Connection"));
  6680. EXPECT_FALSE(cli_.is_socket_open());
  6681. }
  6682. TEST_F(ServerTest, PercentEncoding) {
  6683. auto res = cli_.Get("/e%6edwith%");
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. }
  6687. TEST_F(ServerTest, PercentEncodingUnicode) {
  6688. auto res = cli_.Get("/e%u006edwith%");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. EXPECT_EQ(StatusCode::OK_200, res->status);
  6691. }
  6692. TEST_F(ServerTest, InvalidPercentEncoding) {
  6693. auto res = cli_.Get("/%endwith%");
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6696. }
  6697. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6698. auto res = cli_.Get("/%uendwith%");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6701. }
  6702. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6703. auto res = cli_.Get("/hello?aaa=bbb%");
  6704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6705. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6706. }
  6707. TEST_F(ServerTest, PlusSignEncoding) {
  6708. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. EXPECT_EQ("a +b", res->body);
  6712. }
  6713. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6714. // This test simulates a potential DoS attack using many headers
  6715. // to verify our security fix prevents memory exhaustion
  6716. httplib::Headers attack_headers;
  6717. // Attempt to add many headers like an attacker would (200 headers to far
  6718. // exceed limit)
  6719. for (int i = 0; i < 200; i++) {
  6720. std::string name = "X-Attack-Header-" + std::to_string(i);
  6721. std::string value = "attack_payload_" + std::to_string(i);
  6722. attack_headers.emplace(name, value);
  6723. }
  6724. // Try to POST with excessive headers
  6725. cli_.set_keep_alive(true);
  6726. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6727. // Should either fail or return 400 Bad Request due to security limit
  6728. if (res) {
  6729. // If we get a response, it should be 400 Bad Request
  6730. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6731. EXPECT_EQ("close", res->get_header_value("Connection"));
  6732. }
  6733. EXPECT_FALSE(cli_.is_socket_open());
  6734. }
  6735. TEST_F(ServerTest, MultipartFormData) {
  6736. UploadFormDataItems items = {
  6737. {"text1", "text default", "", ""},
  6738. {"text2", "aωb", "", ""},
  6739. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6740. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6741. {"file3", "", "", "application/octet-stream"},
  6742. {"file4", "", "", " application/json tmp-string "}};
  6743. auto res = cli_.Post("/multipart", items);
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. }
  6747. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6748. UploadFormDataItems items = {
  6749. {"text", "default text", "", ""},
  6750. {"multi_text1", "aaaaa", "", ""},
  6751. {"multi_text1", "bbbbb", "", ""},
  6752. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6753. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6754. "application/json"},
  6755. };
  6756. auto res = cli_.Post("/multipart/multi_file_values", items);
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::OK_200, res->status);
  6759. }
  6760. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6761. auto res = cli_.Get("/hi");
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. EXPECT_EQ(StatusCode::OK_200, res->status);
  6764. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6765. EXPECT_EQ("Hello World!", res->body);
  6766. }
  6767. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6768. Request req;
  6769. req.method = "POST";
  6770. req.path = "/chunked";
  6771. std::string host_and_port;
  6772. host_and_port += HOST;
  6773. host_and_port += ":";
  6774. host_and_port += std::to_string(PORT);
  6775. req.headers.emplace("Host", host_and_port.c_str());
  6776. req.headers.emplace("Accept", "*/*");
  6777. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6778. req.headers.emplace("Content-Type", "text/plain");
  6779. req.headers.emplace("Content-Length", "0");
  6780. req.headers.emplace(
  6781. "Transfer-Encoding",
  6782. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6783. // Client does not chunk, so make a chunked body manually.
  6784. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6785. auto res = std::make_shared<Response>();
  6786. auto error = Error::Success;
  6787. auto ret = cli_.send(req, *res, error);
  6788. ASSERT_TRUE(ret);
  6789. EXPECT_EQ(StatusCode::OK_200, res->status);
  6790. }
  6791. template <typename ClientT>
  6792. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6793. int expected_status) {
  6794. Request req;
  6795. req.method = "POST";
  6796. req.path = "/chunked";
  6797. std::string host_and_port;
  6798. host_and_port += HOST;
  6799. host_and_port += ":";
  6800. host_and_port += std::to_string(PORT);
  6801. req.headers.emplace("Host", host_and_port.c_str());
  6802. req.headers.emplace("Content-Length", "0");
  6803. req.headers.emplace("Transfer-Encoding", "chunked");
  6804. req.body = body;
  6805. auto res = std::make_shared<Response>();
  6806. auto error = Error::Success;
  6807. ASSERT_TRUE(cli.send(req, *res, error));
  6808. EXPECT_EQ(expected_status, res->status);
  6809. }
  6810. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6811. // rather than treat them as valid lengths.
  6812. template <typename ClientT>
  6813. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6814. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6815. }
  6816. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6817. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6818. }
  6819. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6820. expect_chunked_body_rejected(
  6821. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6822. }
  6823. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6824. // chunk-size line carries no CR, LF or other control character ahead of its
  6825. // terminator. Such a line must be refused rather than read as extension text.
  6826. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6827. expect_chunked_body_rejected(
  6828. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6829. }
  6830. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6831. expect_chunked_body_rejected(
  6832. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6833. }
  6834. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6835. expect_chunked_body_rejected(
  6836. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6837. }
  6838. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6839. // The literal stays split: a hex escape consumes every hex digit that
  6840. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6841. expect_chunked_body_rejected(
  6842. cli_, "4;a\x01"
  6843. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6844. }
  6845. TEST_F(ServerTest, AcceptsChunkExtension) {
  6846. expect_chunked_body_status(cli_,
  6847. "4;name=value\r\ndech\r\n"
  6848. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6849. "0;last\r\n\r\n",
  6850. StatusCode::OK_200);
  6851. }
  6852. TEST_F(ServerTest, GetStreamed2) {
  6853. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6855. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6856. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6857. EXPECT_EQ(true, res->has_header("Content-Range"));
  6858. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6859. EXPECT_EQ(std::string("ab"), res->body);
  6860. }
  6861. TEST_F(ServerTest, GetStreamed) {
  6862. auto res = cli_.Get("/streamed");
  6863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6864. EXPECT_EQ(StatusCode::OK_200, res->status);
  6865. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6866. EXPECT_EQ(std::string("aaabbb"), res->body);
  6867. }
  6868. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6869. auto res = cli_.Get("/streamed-without-length",
  6870. Headers{make_range_header({{0, -1}})});
  6871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6872. EXPECT_EQ(StatusCode::OK_200, res->status);
  6873. EXPECT_EQ(false, res->has_header("Content-Length"));
  6874. EXPECT_EQ(false, res->has_header("Content-Range"));
  6875. EXPECT_EQ(std::string("abcdefg"), res->body);
  6876. }
  6877. TEST_F(ServerTest, GetStreamedWithRange1) {
  6878. auto res =
  6879. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6882. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6883. EXPECT_EQ(true, res->has_header("Content-Range"));
  6884. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6885. EXPECT_EQ(std::string("def"), res->body);
  6886. }
  6887. TEST_F(ServerTest, GetStreamedWithRange2) {
  6888. auto res =
  6889. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6891. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6892. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6893. EXPECT_EQ(true, res->has_header("Content-Range"));
  6894. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6895. EXPECT_EQ(std::string("bcdefg"), res->body);
  6896. }
  6897. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6898. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6901. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6902. EXPECT_EQ(true, res->has_header("Content-Range"));
  6903. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6904. EXPECT_EQ(std::string("efg"), res->body);
  6905. }
  6906. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6907. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6908. // the entire representation.
  6909. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6910. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6913. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6914. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6915. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6916. }
  6917. }
  6918. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6919. auto res =
  6920. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6923. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6924. EXPECT_EQ(false, res->has_header("Content-Range"));
  6925. EXPECT_EQ(0U, res->body.size());
  6926. }
  6927. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6928. // Only a 206 is served as a partial representation. Under any other status
  6929. // `apply_ranges()` reported the full content length, so the body must match
  6930. // that header, and the content provider must never be asked for an offset
  6931. // outside the representation.
  6932. auto check = [&](int status, const char *range) {
  6933. auto path =
  6934. std::string("/streamed-with-range?status=") + std::to_string(status);
  6935. auto ctx = path + " Range: " + range;
  6936. auto res = cli_.Get(path, Headers{{"Range", range}});
  6937. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6938. EXPECT_EQ(status, res->status) << ctx;
  6939. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6941. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6942. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6943. };
  6944. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6945. check(403, "bytes=3-5");
  6946. // The offset is far past the representation.
  6947. check(403, "bytes=100000-100200");
  6948. // `first_pos` is still -1 here, and the bounds asserts in
  6949. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6950. check(403, "bytes=-3");
  6951. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6952. // multipart branch would have written one that is empty.
  6953. check(403, "bytes=1-2, 4-5");
  6954. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6955. // covers the whole representation.
  6956. check(200, "bytes=3-5");
  6957. check(200, "bytes=1-2, 4-5");
  6958. }
  6959. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6960. auto res =
  6961. cli_.Get("/streamed-with-range",
  6962. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6963. "92233720368547758079223372036854775807"}});
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6966. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6967. EXPECT_EQ(false, res->has_header("Content-Range"));
  6968. EXPECT_EQ(0U, res->body.size());
  6969. }
  6970. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6971. auto res = cli_.Get(
  6972. "/with-range",
  6973. Headers{{"Range",
  6974. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6975. {"Accept-Encoding", ""}});
  6976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6978. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6979. EXPECT_EQ(true, res->has_header("Content-Range"));
  6980. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6981. EXPECT_EQ(std::string("abcdefg"), res->body);
  6982. }
  6983. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6984. auto res = cli_.Get("/with-range", Headers{
  6985. {"Range", "bytes=0-"},
  6986. {"Accept-Encoding", ""},
  6987. });
  6988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6989. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6990. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6991. EXPECT_EQ(true, res->has_header("Content-Range"));
  6992. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6993. EXPECT_EQ(std::string("abcdefg"), res->body);
  6994. }
  6995. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6996. auto res = cli_.Get("/streamed-with-range",
  6997. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7000. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7001. EXPECT_EQ(false, res->has_header("Content-Range"));
  7002. EXPECT_EQ(267U, res->body.size());
  7003. // Check that both range contents are present
  7004. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7005. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7006. // Check that Content-Range headers are present for both ranges
  7007. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7008. std::string::npos);
  7009. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7010. std::string::npos);
  7011. }
  7012. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7013. Ranges ranges;
  7014. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7015. ranges.emplace_back(0, -1);
  7016. }
  7017. auto res = cli_.Get("/streamed-with-range?error",
  7018. Headers{{make_range_header(ranges)}});
  7019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7020. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7021. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7022. EXPECT_EQ(false, res->has_header("Content-Range"));
  7023. EXPECT_EQ(0U, res->body.size());
  7024. }
  7025. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7026. auto res = cli_.Get("/streamed-with-range",
  7027. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7029. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7030. EXPECT_EQ(5U, res->body.size());
  7031. // Check that overlapping ranges are coalesced into a single range
  7032. EXPECT_EQ("bcdef", res->body);
  7033. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7034. // Should be single range, not multipart
  7035. EXPECT_TRUE(res->has_header("Content-Range"));
  7036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7037. }
  7038. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7039. auto res = cli_.Get("/streamed-with-range",
  7040. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7042. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7043. EXPECT_EQ(268U, res->body.size());
  7044. // Check that both range contents are present
  7045. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7046. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7047. // Check that Content-Range headers are present for both ranges
  7048. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7049. std::string::npos);
  7050. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7051. std::string::npos);
  7052. }
  7053. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7054. auto res = cli_.Get("/streamed-with-range",
  7055. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7057. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7058. EXPECT_EQ(269U, res->body.size());
  7059. // Check that both duplicate range contents are present
  7060. size_t first_abc = res->body.find("abc\r\n");
  7061. EXPECT_TRUE(first_abc != std::string::npos);
  7062. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7063. EXPECT_TRUE(second_abc != std::string::npos);
  7064. // Check that Content-Range headers are present for both ranges
  7065. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7066. EXPECT_TRUE(first_range != std::string::npos);
  7067. size_t second_range =
  7068. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7069. EXPECT_TRUE(second_range != std::string::npos);
  7070. }
  7071. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7072. auto res =
  7073. cli_.Get("/streamed-with-range?error",
  7074. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7076. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7077. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7078. EXPECT_EQ(false, res->has_header("Content-Range"));
  7079. EXPECT_EQ(0U, res->body.size());
  7080. }
  7081. TEST_F(ServerTest, GetStreamedEndless) {
  7082. uint64_t offset = 0;
  7083. auto res = cli_.Get("/streamed-cancel",
  7084. [&](const char * /*data*/, uint64_t data_length) {
  7085. if (offset < 100) {
  7086. offset += data_length;
  7087. return true;
  7088. }
  7089. return false;
  7090. });
  7091. ASSERT_TRUE(!res);
  7092. EXPECT_EQ(Error::Canceled, res.error());
  7093. }
  7094. TEST_F(ServerTest, ClientStop) {
  7095. std::atomic_size_t count{4};
  7096. std::vector<std::thread> threads;
  7097. for (auto i = count.load(); i != 0; --i) {
  7098. threads.emplace_back([&]() {
  7099. auto res = cli_.Get("/streamed-cancel",
  7100. [&](const char *, uint64_t) { return true; });
  7101. --count;
  7102. ASSERT_TRUE(!res);
  7103. EXPECT_TRUE(res.error() == Error::Canceled ||
  7104. res.error() == Error::Read || res.error() == Error::Write);
  7105. });
  7106. }
  7107. std::this_thread::sleep_for(std::chrono::seconds(2));
  7108. while (count != 0) {
  7109. cli_.stop();
  7110. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7111. }
  7112. for (auto &t : threads) {
  7113. t.join();
  7114. }
  7115. }
  7116. TEST_F(ServerTest, GetWithRange1) {
  7117. auto res = cli_.Get("/with-range", Headers{
  7118. make_range_header({{3, 5}}),
  7119. {"Accept-Encoding", ""},
  7120. });
  7121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7122. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7123. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7124. EXPECT_EQ(true, res->has_header("Content-Range"));
  7125. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7126. EXPECT_EQ(std::string("def"), res->body);
  7127. }
  7128. TEST_F(ServerTest, GetWithRange2) {
  7129. auto res = cli_.Get("/with-range", Headers{
  7130. make_range_header({{1, -1}}),
  7131. {"Accept-Encoding", ""},
  7132. });
  7133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7134. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7135. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7136. EXPECT_EQ(true, res->has_header("Content-Range"));
  7137. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7138. EXPECT_EQ(std::string("bcdefg"), res->body);
  7139. }
  7140. TEST_F(ServerTest, GetWithRange3) {
  7141. auto res = cli_.Get("/with-range", Headers{
  7142. make_range_header({{0, 0}}),
  7143. {"Accept-Encoding", ""},
  7144. });
  7145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7146. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7147. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7148. EXPECT_EQ(true, res->has_header("Content-Range"));
  7149. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7150. EXPECT_EQ(std::string("a"), res->body);
  7151. }
  7152. TEST_F(ServerTest, GetWithRange4) {
  7153. auto res = cli_.Get("/with-range", Headers{
  7154. make_range_header({{-1, 2}}),
  7155. {"Accept-Encoding", ""},
  7156. });
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7159. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7160. EXPECT_EQ(true, res->has_header("Content-Range"));
  7161. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7162. EXPECT_EQ(std::string("fg"), res->body);
  7163. }
  7164. TEST_F(ServerTest, GetWithRange5) {
  7165. auto res = cli_.Get("/with-range", Headers{
  7166. make_range_header({{0, 5}}),
  7167. {"Accept-Encoding", ""},
  7168. });
  7169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7171. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7172. EXPECT_EQ(true, res->has_header("Content-Range"));
  7173. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7174. EXPECT_EQ(std::string("abcdef"), res->body);
  7175. }
  7176. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7177. auto res =
  7178. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7180. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7181. }
  7182. TEST_F(ServerTest, GetWithRangeMultipart) {
  7183. auto res =
  7184. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7187. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(false, res->has_header("Content-Range"));
  7189. EXPECT_EQ(267U, res->body.size());
  7190. }
  7191. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7192. auto res = cli_.Get("/with-range",
  7193. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7195. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7196. }
  7197. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7198. auto res = cli_.Get("/with-range-customized-response",
  7199. Headers{{make_range_header({{1, 2}})}});
  7200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7201. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7202. EXPECT_EQ(true, res->has_header("Content-Length"));
  7203. EXPECT_EQ(false, res->has_header("Content-Range"));
  7204. EXPECT_EQ(JSON_DATA, res->body);
  7205. }
  7206. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7207. auto res = cli_.Get("/with-range-customized-response",
  7208. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7211. EXPECT_EQ(true, res->has_header("Content-Length"));
  7212. EXPECT_EQ(false, res->has_header("Content-Range"));
  7213. EXPECT_EQ(JSON_DATA, res->body);
  7214. }
  7215. TEST_F(ServerTest, Issue1772) {
  7216. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7219. }
  7220. TEST_F(ServerTest, Issue609) {
  7221. auto res = cli_.Delete("/issue609");
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::OK_200, res->status);
  7224. EXPECT_EQ(std::string("ok"), res->body);
  7225. }
  7226. TEST_F(ServerTest, GetStreamedChunked) {
  7227. auto res = cli_.Get("/streamed-chunked");
  7228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7229. EXPECT_EQ(StatusCode::OK_200, res->status);
  7230. EXPECT_EQ(std::string("123456789"), res->body);
  7231. }
  7232. TEST_F(ServerTest, GetStreamedChunked2) {
  7233. auto res = cli_.Get("/streamed-chunked2");
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::OK_200, res->status);
  7236. EXPECT_EQ(std::string("123456789"), res->body);
  7237. }
  7238. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7239. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7241. EXPECT_EQ(StatusCode::OK_200, res->status);
  7242. EXPECT_EQ(std::string("123456789"), res->body);
  7243. EXPECT_TRUE(res->has_header("Trailer"));
  7244. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7245. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7246. // Trailers are now stored separately from headers (security fix)
  7247. EXPECT_EQ(2U, res->trailers.size());
  7248. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7249. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7250. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7251. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7252. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7253. // Verify trailers are NOT in headers (security verification)
  7254. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7255. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7256. }
  7257. TEST_F(ServerTest, LargeChunkedPost) {
  7258. Request req;
  7259. req.method = "POST";
  7260. req.path = "/large-chunked";
  7261. std::string host_and_port;
  7262. host_and_port += HOST;
  7263. host_and_port += ":";
  7264. host_and_port += std::to_string(PORT);
  7265. req.headers.emplace("Host", host_and_port.c_str());
  7266. req.headers.emplace("Accept", "*/*");
  7267. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7268. req.headers.emplace("Content-Type", "text/plain");
  7269. req.headers.emplace("Content-Length", "0");
  7270. req.headers.emplace("Transfer-Encoding", "chunked");
  7271. std::string long_string(30 * 1024u, 'a');
  7272. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7273. // Attempt to make a large enough post to exceed OS buffers, to test that
  7274. // the server handles short reads if the full chunk data isn't available.
  7275. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7276. auto res = std::make_shared<Response>();
  7277. auto error = Error::Success;
  7278. auto ret = cli_.send(req, *res, error);
  7279. ASSERT_TRUE(ret);
  7280. EXPECT_EQ(StatusCode::OK_200, res->status);
  7281. }
  7282. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7283. auto res = cli_.Get("/remote_addr");
  7284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7285. EXPECT_EQ(StatusCode::OK_200, res->status);
  7286. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7287. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7288. }
  7289. TEST_F(ServerTest, GetMethodLocalAddr) {
  7290. auto res = cli_.Get("/local_addr");
  7291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7292. EXPECT_EQ(StatusCode::OK_200, res->status);
  7293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7294. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7295. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7296. }
  7297. TEST_F(ServerTest, HTTPResponseSplitting) {
  7298. auto res = cli_.Get("/http_response_splitting");
  7299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7300. EXPECT_EQ(StatusCode::OK_200, res->status);
  7301. }
  7302. TEST_F(ServerTest, SlowRequest) {
  7303. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7304. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7305. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7306. }
  7307. #if 0
  7308. TEST_F(ServerTest, SlowPost) {
  7309. char buffer[64 * 1024];
  7310. memset(buffer, 0x42, sizeof(buffer));
  7311. auto res = cli_.Post(
  7312. "/slowpost", 64 * 1024 * 1024,
  7313. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7314. auto ret = sink.write(buffer, sizeof(buffer));
  7315. EXPECT_TRUE(ret);
  7316. return true;
  7317. },
  7318. "text/plain");
  7319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7320. EXPECT_EQ(StatusCode::OK_200, res->status);
  7321. }
  7322. TEST_F(ServerTest, SlowPostFail) {
  7323. char buffer[64 * 1024];
  7324. memset(buffer, 0x42, sizeof(buffer));
  7325. cli_.set_write_timeout(std::chrono::seconds(0));
  7326. auto res = cli_.Post(
  7327. "/slowpost", 64 * 1024 * 1024,
  7328. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7329. sink.write(buffer, sizeof(buffer));
  7330. return true;
  7331. },
  7332. "text/plain");
  7333. ASSERT_TRUE(!res);
  7334. EXPECT_EQ(Error::Write, res.error());
  7335. }
  7336. #endif
  7337. TEST_F(ServerTest, Put) {
  7338. auto res = cli_.Put("/put", "PUT", "text/plain");
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ(StatusCode::OK_200, res->status);
  7341. EXPECT_EQ("PUT", res->body);
  7342. }
  7343. TEST_F(ServerTest, PutWithContentProvider) {
  7344. auto res = cli_.Put(
  7345. "/put", 3,
  7346. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7347. sink.os << "PUT";
  7348. return true;
  7349. },
  7350. "text/plain");
  7351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7352. EXPECT_EQ(StatusCode::OK_200, res->status);
  7353. EXPECT_EQ("PUT", res->body);
  7354. }
  7355. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7356. auto res = cli_.Post(
  7357. "/post", 42,
  7358. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7359. return false;
  7360. },
  7361. "text/plain");
  7362. ASSERT_TRUE(!res);
  7363. EXPECT_EQ(Error::Canceled, res.error());
  7364. }
  7365. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7366. auto res = cli_.Put(
  7367. "/put",
  7368. [](size_t /*offset*/, DataSink &sink) {
  7369. sink.os << "PUT";
  7370. sink.done();
  7371. return true;
  7372. },
  7373. "text/plain");
  7374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7375. EXPECT_EQ(StatusCode::OK_200, res->status);
  7376. EXPECT_EQ("PUT", res->body);
  7377. }
  7378. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7379. auto res = cli_.Post(
  7380. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7381. "text/plain");
  7382. ASSERT_TRUE(!res);
  7383. EXPECT_EQ(Error::Canceled, res.error());
  7384. }
  7385. TEST_F(ServerTest, PostLoopBack) {
  7386. std::string body;
  7387. auto res = cli_.Post(
  7388. "/post-loopback", 9,
  7389. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7390. EXPECT_EQ(9u, length);
  7391. sink.write("123", 3);
  7392. sink.write("456", 3);
  7393. sink.write("789", 3);
  7394. return true;
  7395. },
  7396. "text/plain",
  7397. [&body](const char *data, size_t data_length) {
  7398. body.append(data, data_length);
  7399. return true;
  7400. });
  7401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7402. EXPECT_EQ(StatusCode::OK_200, res->status);
  7403. EXPECT_EQ("123456789", body);
  7404. }
  7405. TEST_F(ServerTest, PutLoopBack) {
  7406. std::string body;
  7407. auto res = cli_.Put(
  7408. "/put-loopback", 9,
  7409. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7410. EXPECT_EQ(9u, length);
  7411. sink.write("123", 3);
  7412. sink.write("456", 3);
  7413. sink.write("789", 3);
  7414. return true;
  7415. },
  7416. "text/plain",
  7417. [&body](const char *data, size_t data_length) {
  7418. body.append(data, data_length);
  7419. return true;
  7420. });
  7421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7422. EXPECT_EQ(StatusCode::OK_200, res->status);
  7423. EXPECT_EQ("123456789", body);
  7424. }
  7425. TEST_F(ServerTest, PatchLoopBack) {
  7426. std::string body;
  7427. auto res = cli_.Patch(
  7428. "/patch-loopback", 9,
  7429. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7430. EXPECT_EQ(9u, length);
  7431. sink.write("123", 3);
  7432. sink.write("456", 3);
  7433. sink.write("789", 3);
  7434. return true;
  7435. },
  7436. "text/plain",
  7437. [&body](const char *data, size_t data_length) {
  7438. body.append(data, data_length);
  7439. return true;
  7440. });
  7441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7442. EXPECT_EQ(StatusCode::OK_200, res->status);
  7443. EXPECT_EQ("123456789", body);
  7444. }
  7445. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7446. std::string body;
  7447. auto res = cli_.Post(
  7448. "/post-loopback",
  7449. [](size_t /*offset*/, DataSink &sink) {
  7450. sink.write("123", 3);
  7451. sink.write("456", 3);
  7452. sink.write("789", 3);
  7453. sink.done();
  7454. return true;
  7455. },
  7456. "text/plain",
  7457. [&body](const char *data, size_t data_length) {
  7458. body.append(data, data_length);
  7459. return true;
  7460. });
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. EXPECT_EQ("123456789", body);
  7464. }
  7465. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7466. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7467. cli_.set_compress(true);
  7468. auto res = cli_.Put(
  7469. "/put", 3,
  7470. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7471. sink.os << "PUT";
  7472. return true;
  7473. },
  7474. "text/plain");
  7475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7476. EXPECT_EQ(StatusCode::OK_200, res->status);
  7477. EXPECT_EQ("PUT", res->body);
  7478. }
  7479. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7480. cli_.set_compress(true);
  7481. auto res = cli_.Post(
  7482. "/post", 42,
  7483. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7484. return false;
  7485. },
  7486. "text/plain");
  7487. ASSERT_TRUE(!res);
  7488. EXPECT_EQ(Error::Canceled, res.error());
  7489. }
  7490. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7491. cli_.set_compress(true);
  7492. auto res = cli_.Put(
  7493. "/put",
  7494. [](size_t /*offset*/, DataSink &sink) {
  7495. sink.os << "PUT";
  7496. sink.done();
  7497. return true;
  7498. },
  7499. "text/plain");
  7500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7501. EXPECT_EQ(StatusCode::OK_200, res->status);
  7502. EXPECT_EQ("PUT", res->body);
  7503. }
  7504. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7505. cli_.set_compress(true);
  7506. auto res = cli_.Post(
  7507. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7508. "text/plain");
  7509. ASSERT_TRUE(!res);
  7510. EXPECT_EQ(Error::Canceled, res.error());
  7511. }
  7512. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7513. cli_.set_compress(true);
  7514. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. EXPECT_EQ(LARGE_DATA, res->body);
  7518. }
  7519. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7520. #ifdef CPPHTTPLIB_SSL_ENABLED
  7521. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7522. Client cli(s.c_str());
  7523. cli.enable_server_certificate_verification(false);
  7524. #else
  7525. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7526. Client cli(s.c_str());
  7527. #endif
  7528. cli.set_compress(true);
  7529. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7531. EXPECT_EQ(StatusCode::OK_200, res->status);
  7532. EXPECT_EQ(LARGE_DATA, res->body);
  7533. // The compressed size should be less than a 10th of the original. May vary
  7534. // depending on the zlib library.
  7535. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7536. static_cast<uint64_t>(10 * 1024 * 1024));
  7537. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7538. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7539. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7540. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7541. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7542. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7543. #endif
  7544. }
  7545. TEST_F(ServerTest, PutContentWithDeflate) {
  7546. cli_.set_compress(false);
  7547. Headers headers;
  7548. headers.emplace("Content-Encoding", "deflate");
  7549. // PUT in deflate format:
  7550. auto res = cli_.Put("/put", headers,
  7551. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7553. EXPECT_EQ(StatusCode::OK_200, res->status);
  7554. EXPECT_EQ("PUT", res->body);
  7555. }
  7556. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7557. Headers headers;
  7558. headers.emplace("Accept-Encoding", "gzip, deflate");
  7559. auto res = cli_.Get("/streamed-chunked", headers);
  7560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7561. EXPECT_EQ(StatusCode::OK_200, res->status);
  7562. EXPECT_EQ(std::string("123456789"), res->body);
  7563. }
  7564. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7565. Headers headers;
  7566. headers.emplace("Accept-Encoding", "gzip, deflate");
  7567. auto res = cli_.Get("/streamed-chunked2", headers);
  7568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7569. EXPECT_EQ(StatusCode::OK_200, res->status);
  7570. EXPECT_EQ(std::string("123456789"), res->body);
  7571. }
  7572. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7573. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7575. EXPECT_EQ(StatusCode::OK_200, res->status);
  7576. }
  7577. TEST(GzipDecompressor, ChunkedDecompression) {
  7578. std::string data;
  7579. for (size_t i = 0; i < 32 * 1024; ++i) {
  7580. data.push_back(static_cast<char>('a' + i % 26));
  7581. }
  7582. std::string compressed_data;
  7583. {
  7584. httplib::detail::gzip_compressor compressor;
  7585. bool result = compressor.compress(
  7586. data.data(), data.size(),
  7587. /*last=*/true,
  7588. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7589. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7590. compressed_data_size);
  7591. return true;
  7592. });
  7593. ASSERT_TRUE(result);
  7594. }
  7595. std::string decompressed_data;
  7596. {
  7597. httplib::detail::gzip_decompressor decompressor;
  7598. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7599. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7600. size_t chunk_size = 130;
  7601. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7602. chunk_begin += chunk_size) {
  7603. size_t current_chunk_size =
  7604. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7605. bool result = decompressor.decompress(
  7606. compressed_data.data() + chunk_begin, current_chunk_size,
  7607. [&](const char *decompressed_data_chunk,
  7608. size_t decompressed_data_chunk_size) {
  7609. decompressed_data.insert(decompressed_data.size(),
  7610. decompressed_data_chunk,
  7611. decompressed_data_chunk_size);
  7612. return true;
  7613. });
  7614. ASSERT_TRUE(result);
  7615. }
  7616. }
  7617. ASSERT_EQ(data, decompressed_data);
  7618. }
  7619. TEST(GzipDecompressor, DeflateDecompression) {
  7620. std::string original_text = "Raw deflate without gzip";
  7621. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7622. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7623. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7624. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7625. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7626. std::string decompressed_data;
  7627. {
  7628. httplib::detail::gzip_decompressor decompressor;
  7629. bool result = decompressor.decompress(
  7630. compressed_data.data(), compressed_data.size(),
  7631. [&](const char *decompressed_data_chunk,
  7632. size_t decompressed_data_chunk_size) {
  7633. decompressed_data.insert(decompressed_data.size(),
  7634. decompressed_data_chunk,
  7635. decompressed_data_chunk_size);
  7636. return true;
  7637. });
  7638. ASSERT_TRUE(result);
  7639. }
  7640. ASSERT_EQ(original_text, decompressed_data);
  7641. }
  7642. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7643. std::string original_text = "Raw deflate without gzip";
  7644. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7645. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7646. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7647. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7648. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7649. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7650. std::string decompressed_data;
  7651. {
  7652. httplib::detail::gzip_decompressor decompressor;
  7653. bool result = decompressor.decompress(
  7654. compressed_data.data(), compressed_data.size(),
  7655. [&](const char *decompressed_data_chunk,
  7656. size_t decompressed_data_chunk_size) {
  7657. decompressed_data.insert(decompressed_data.size(),
  7658. decompressed_data_chunk,
  7659. decompressed_data_chunk_size);
  7660. return true;
  7661. });
  7662. ASSERT_TRUE(result);
  7663. }
  7664. ASSERT_EQ(original_text, decompressed_data);
  7665. }
  7666. #endif
  7667. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7668. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7669. Headers headers;
  7670. headers.emplace("Accept-Encoding", "br");
  7671. auto res = cli_.Get("/streamed-chunked", headers);
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::OK_200, res->status);
  7674. EXPECT_EQ(std::string("123456789"), res->body);
  7675. }
  7676. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7677. Headers headers;
  7678. headers.emplace("Accept-Encoding", "br");
  7679. auto res = cli_.Get("/streamed-chunked2", headers);
  7680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7681. EXPECT_EQ(StatusCode::OK_200, res->status);
  7682. EXPECT_EQ(std::string("123456789"), res->body);
  7683. }
  7684. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7685. cli_.set_compress(true);
  7686. auto res = cli_.Put(
  7687. "/put", 3,
  7688. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7689. sink.os << "PUT";
  7690. return true;
  7691. },
  7692. "text/plain");
  7693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7694. EXPECT_EQ(StatusCode::OK_200, res->status);
  7695. EXPECT_EQ("PUT", res->body);
  7696. }
  7697. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7698. cli_.set_compress(true);
  7699. auto res = cli_.Put(
  7700. "/put",
  7701. [](size_t /*offset*/, DataSink &sink) {
  7702. sink.os << "PUT";
  7703. sink.done();
  7704. return true;
  7705. },
  7706. "text/plain");
  7707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7708. EXPECT_EQ(StatusCode::OK_200, res->status);
  7709. EXPECT_EQ("PUT", res->body);
  7710. }
  7711. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7712. cli_.set_compress(true);
  7713. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7715. EXPECT_EQ(StatusCode::OK_200, res->status);
  7716. EXPECT_EQ(LARGE_DATA, res->body);
  7717. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7718. }
  7719. #endif
  7720. TEST_F(ServerTest, Patch) {
  7721. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7723. EXPECT_EQ(StatusCode::OK_200, res->status);
  7724. EXPECT_EQ("PATCH", res->body);
  7725. }
  7726. TEST_F(ServerTest, Delete) {
  7727. auto res = cli_.Delete("/delete");
  7728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7729. EXPECT_EQ(StatusCode::OK_200, res->status);
  7730. EXPECT_EQ("DELETE", res->body);
  7731. }
  7732. TEST_F(ServerTest, DeleteContentReceiver) {
  7733. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7735. EXPECT_EQ(StatusCode::OK_200, res->status);
  7736. EXPECT_EQ("content", res->body);
  7737. }
  7738. TEST_F(ServerTest, Options) {
  7739. auto res = cli_.Options("*");
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. EXPECT_EQ(StatusCode::OK_200, res->status);
  7742. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7743. EXPECT_TRUE(res->body.empty());
  7744. }
  7745. TEST_F(ServerTest, URL) {
  7746. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. }
  7750. TEST_F(ServerTest, ArrayParam) {
  7751. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. }
  7755. TEST_F(ServerTest, ArrayParamValues) {
  7756. auto res =
  7757. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7759. EXPECT_EQ(StatusCode::OK_200, res->status);
  7760. }
  7761. TEST_F(ServerTest, NoMultipleHeaders) {
  7762. Headers headers = {{"Content-Length", "5"}};
  7763. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7764. "text/plain");
  7765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7766. EXPECT_EQ(StatusCode::OK_200, res->status);
  7767. }
  7768. TEST_F(ServerTest, PostContentReceiver) {
  7769. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. ASSERT_EQ(StatusCode::OK_200, res->status);
  7772. ASSERT_EQ("content", res->body);
  7773. }
  7774. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7775. UploadFormDataItems items = {
  7776. {"text1", "text default", "", ""},
  7777. {"text2", "aωb", "", ""},
  7778. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7779. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7780. {"file3", "", "", "application/octet-stream"},
  7781. };
  7782. auto res = cli_.Post("/content_receiver", items);
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::OK_200, res->status);
  7785. }
  7786. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7787. UploadFormDataItems items = {
  7788. {"text1", "text default", "", ""},
  7789. {"text2", "aωb", "", ""},
  7790. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7791. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7792. {"file3", "", "", "application/octet-stream"},
  7793. };
  7794. auto boundary = std::string("+++++");
  7795. std::string body;
  7796. for (const auto &item : items) {
  7797. body += "--" + boundary + "\r\n";
  7798. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7799. if (!item.filename.empty()) {
  7800. body += "; filename=\"" + item.filename + "\"";
  7801. }
  7802. body += "\r\n";
  7803. if (!item.content_type.empty()) {
  7804. body += "Content-Type: " + item.content_type + "\r\n";
  7805. }
  7806. body += "\r\n";
  7807. body += item.content + "\r\n";
  7808. }
  7809. body += "--" + boundary + "--\r\n";
  7810. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7811. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7813. EXPECT_EQ(StatusCode::OK_200, res->status);
  7814. }
  7815. TEST(MultipartFormDataTest, FieldEscaping) {
  7816. Server svr;
  7817. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7818. const ContentReader &content_reader) {
  7819. ASSERT_TRUE(req.is_multipart_form_data());
  7820. std::vector<FormData> received;
  7821. content_reader(
  7822. [&](const FormData &file) {
  7823. received.push_back(file);
  7824. return true;
  7825. },
  7826. [&](const char *data, size_t data_length) {
  7827. received.back().content.append(data, data_length);
  7828. return true;
  7829. });
  7830. // '"', CR and LF in names and filenames are escaped following the
  7831. // WHATWG HTML standard, so each part still parses as a single part
  7832. // with no injected headers. Content types get CR/LF escaped too,
  7833. // while '"' (legal there, e.g. quoted charset) is preserved.
  7834. ASSERT_EQ(4U, received.size());
  7835. EXPECT_EQ("na%22me", received[0].name);
  7836. EXPECT_EQ("quoted name", received[0].content);
  7837. EXPECT_EQ("file", received[1].name);
  7838. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7839. received[1].filename);
  7840. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7841. EXPECT_EQ("injected", received[1].content);
  7842. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7843. EXPECT_EQ("my%22file.txt", received[2].filename);
  7844. EXPECT_EQ("cr lf name", received[2].content);
  7845. EXPECT_EQ("typed", received[3].name);
  7846. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7847. received[3].content_type);
  7848. EXPECT_EQ("typed content", received[3].content);
  7849. });
  7850. auto port = svr.bind_to_any_port("localhost");
  7851. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7852. auto se = detail::scope_exit([&] {
  7853. svr.stop();
  7854. t.join();
  7855. ASSERT_FALSE(svr.is_running());
  7856. });
  7857. svr.wait_until_ready();
  7858. Client cli("localhost", port);
  7859. UploadFormDataItems items = {
  7860. {"na\"me", "quoted name", "", ""},
  7861. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7862. "application/octet-stream"},
  7863. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7864. {"typed", "typed content", "",
  7865. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7866. };
  7867. auto res = cli.Post("/post", items);
  7868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7869. EXPECT_EQ(StatusCode::OK_200, res->status);
  7870. }
  7871. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7872. const UploadFormDataItems items = {
  7873. {"name1", "Content 1", "", ""},
  7874. {"name2", "Content 2", "file2.txt", "text/plain"},
  7875. };
  7876. Server svr;
  7877. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7878. const ContentReader &content_reader) {
  7879. ASSERT_TRUE(req.is_multipart_form_data());
  7880. std::vector<FormData> received;
  7881. content_reader(
  7882. [&](const FormData &file) {
  7883. received.push_back(file);
  7884. return true;
  7885. },
  7886. [&](const char *data, size_t data_length) {
  7887. received.back().content.append(data, data_length);
  7888. return true;
  7889. });
  7890. ASSERT_EQ(2U, received.size());
  7891. EXPECT_EQ("name1", received[0].name);
  7892. EXPECT_EQ("Content 1", received[0].content);
  7893. EXPECT_EQ("name2", received[1].name);
  7894. EXPECT_EQ("Content 2", received[1].content);
  7895. EXPECT_EQ("file2.txt", received[1].filename);
  7896. EXPECT_EQ("text/plain", received[1].content_type);
  7897. });
  7898. auto port = svr.bind_to_any_port("localhost");
  7899. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7900. auto se = detail::scope_exit([&] {
  7901. svr.stop();
  7902. t.join();
  7903. ASSERT_FALSE(svr.is_running());
  7904. });
  7905. svr.wait_until_ready();
  7906. Client cli("localhost", port);
  7907. // Whole-body serialization with a generated boundary
  7908. {
  7909. MultipartFormDataWriter writer;
  7910. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7911. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7912. writer.content_type());
  7913. auto body = writer.serialize(items);
  7914. EXPECT_EQ(body.size(), writer.content_length(items));
  7915. auto res = cli.Post("/post", body, writer.content_type());
  7916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7917. EXPECT_EQ(StatusCode::OK_200, res->status);
  7918. }
  7919. // Per-part framing with a custom boundary via a content provider
  7920. {
  7921. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7922. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7923. MultipartFormDataWriter writer("custom-boundary_123");
  7924. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7925. std::string body;
  7926. for (const auto &item : items) {
  7927. body += writer.item_begin(item);
  7928. body += item.content;
  7929. body += MultipartFormDataWriter::item_end();
  7930. }
  7931. body += writer.finish();
  7932. EXPECT_EQ(body.size(), writer.content_length(items));
  7933. auto res = cli.Post(
  7934. "/post", body.size(),
  7935. [&](size_t offset, size_t length, DataSink &sink) {
  7936. sink.write(body.data() + offset, length);
  7937. return true;
  7938. },
  7939. writer.content_type());
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ(StatusCode::OK_200, res->status);
  7942. }
  7943. }
  7944. TEST_F(ServerTest, PostContentReceiverGzip) {
  7945. cli_.set_compress(true);
  7946. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7948. ASSERT_EQ(StatusCode::OK_200, res->status);
  7949. ASSERT_EQ("content", res->body);
  7950. }
  7951. TEST_F(ServerTest, PutContentReceiver) {
  7952. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7954. ASSERT_EQ(StatusCode::OK_200, res->status);
  7955. ASSERT_EQ("content", res->body);
  7956. }
  7957. TEST_F(ServerTest, PatchContentReceiver) {
  7958. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. ASSERT_EQ(StatusCode::OK_200, res->status);
  7961. ASSERT_EQ("content", res->body);
  7962. }
  7963. template <typename ClientType>
  7964. void TestWithHeadersAndContentReceiver(
  7965. ClientType &cli,
  7966. std::function<Result(ClientType &, const std::string &, const Headers &,
  7967. const std::string &, const std::string &,
  7968. ContentReceiver, DownloadProgress)>
  7969. request_func) {
  7970. Headers headers;
  7971. headers.emplace("X-Custom-Header", "test-value");
  7972. std::string received_body;
  7973. auto res = request_func(
  7974. cli, "/content_receiver", headers, "content", "application/json",
  7975. [&](const char *data, size_t data_length) {
  7976. received_body.append(data, data_length);
  7977. return true;
  7978. },
  7979. nullptr);
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ(StatusCode::OK_200, res->status);
  7982. EXPECT_EQ("content", received_body);
  7983. }
  7984. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7985. #ifdef CPPHTTPLIB_SSL_ENABLED
  7986. using ClientT = SSLClient;
  7987. #else
  7988. using ClientT = Client;
  7989. #endif
  7990. TestWithHeadersAndContentReceiver<ClientT>(
  7991. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7992. const std::string &body, const std::string &content_type,
  7993. ContentReceiver receiver, DownloadProgress progress) {
  7994. return cli.Post(path, headers, body, content_type, receiver, progress);
  7995. });
  7996. }
  7997. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7998. #ifdef CPPHTTPLIB_SSL_ENABLED
  7999. using ClientT = SSLClient;
  8000. #else
  8001. using ClientT = Client;
  8002. #endif
  8003. TestWithHeadersAndContentReceiver<ClientT>(
  8004. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8005. const std::string &body, const std::string &content_type,
  8006. ContentReceiver receiver, DownloadProgress progress) {
  8007. return cli.Put(path, headers, body, content_type, receiver, progress);
  8008. });
  8009. }
  8010. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8011. #ifdef CPPHTTPLIB_SSL_ENABLED
  8012. using ClientT = SSLClient;
  8013. #else
  8014. using ClientT = Client;
  8015. #endif
  8016. TestWithHeadersAndContentReceiver<ClientT>(
  8017. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8018. const std::string &body, const std::string &content_type,
  8019. ContentReceiver receiver, DownloadProgress progress) {
  8020. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8021. });
  8022. }
  8023. template <typename ClientType>
  8024. void TestWithHeadersAndContentReceiverWithProgress(
  8025. ClientType &cli,
  8026. std::function<Result(ClientType &, const std::string &, const Headers &,
  8027. const std::string &, const std::string &,
  8028. ContentReceiver, DownloadProgress)>
  8029. request_func) {
  8030. Headers headers;
  8031. headers.emplace("X-Test-Header", "progress-test");
  8032. std::string received_body;
  8033. auto progress_called = false;
  8034. auto res = request_func(
  8035. cli, "/content_receiver", headers, "content", "text/plain",
  8036. [&](const char *data, size_t data_length) {
  8037. received_body.append(data, data_length);
  8038. return true;
  8039. },
  8040. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8041. progress_called = true;
  8042. return true;
  8043. });
  8044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8045. EXPECT_EQ(StatusCode::OK_200, res->status);
  8046. EXPECT_EQ("content", received_body);
  8047. EXPECT_TRUE(progress_called);
  8048. }
  8049. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8050. #ifdef CPPHTTPLIB_SSL_ENABLED
  8051. using ClientT = SSLClient;
  8052. #else
  8053. using ClientT = Client;
  8054. #endif
  8055. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8056. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8057. const std::string &body, const std::string &content_type,
  8058. ContentReceiver receiver, DownloadProgress progress) {
  8059. return cli.Post(path, headers, body, content_type, receiver, progress);
  8060. });
  8061. }
  8062. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8063. #ifdef CPPHTTPLIB_SSL_ENABLED
  8064. using ClientT = SSLClient;
  8065. #else
  8066. using ClientT = Client;
  8067. #endif
  8068. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8069. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8070. const std::string &body, const std::string &content_type,
  8071. ContentReceiver receiver, DownloadProgress progress) {
  8072. return cli.Put(path, headers, body, content_type, receiver, progress);
  8073. });
  8074. }
  8075. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8076. #ifdef CPPHTTPLIB_SSL_ENABLED
  8077. using ClientT = SSLClient;
  8078. #else
  8079. using ClientT = Client;
  8080. #endif
  8081. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8082. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8083. const std::string &body, const std::string &content_type,
  8084. ContentReceiver receiver, DownloadProgress progress) {
  8085. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8086. });
  8087. }
  8088. template <typename ClientType>
  8089. void TestWithHeadersAndContentReceiverError(
  8090. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8091. const Headers &, const std::string &,
  8092. const std::string &, ContentReceiver)>
  8093. request_func) {
  8094. Headers headers;
  8095. headers.emplace("X-Error-Test", "true");
  8096. std::string received_body;
  8097. auto receiver_failed = false;
  8098. auto res =
  8099. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8100. [&](const char *data, size_t data_length) {
  8101. received_body.append(data, data_length);
  8102. receiver_failed = true;
  8103. return false;
  8104. });
  8105. ASSERT_FALSE(res);
  8106. EXPECT_TRUE(receiver_failed);
  8107. }
  8108. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8109. #ifdef CPPHTTPLIB_SSL_ENABLED
  8110. using ClientT = SSLClient;
  8111. #else
  8112. using ClientT = Client;
  8113. #endif
  8114. TestWithHeadersAndContentReceiverError<ClientT>(
  8115. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8116. const std::string &body, const std::string &content_type,
  8117. ContentReceiver receiver) {
  8118. return cli.Post(path, headers, body, content_type, receiver);
  8119. });
  8120. }
  8121. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8122. #ifdef CPPHTTPLIB_SSL_ENABLED
  8123. using ClientT = SSLClient;
  8124. #else
  8125. using ClientT = Client;
  8126. #endif
  8127. TestWithHeadersAndContentReceiverError<ClientT>(
  8128. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8129. const std::string &body, const std::string &content_type,
  8130. ContentReceiver receiver) {
  8131. return cli.Put(path, headers, body, content_type, receiver);
  8132. });
  8133. }
  8134. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8135. #ifdef CPPHTTPLIB_SSL_ENABLED
  8136. using ClientT = SSLClient;
  8137. #else
  8138. using ClientT = Client;
  8139. #endif
  8140. TestWithHeadersAndContentReceiverError<ClientT>(
  8141. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8142. const std::string &body, const std::string &content_type,
  8143. ContentReceiver receiver) {
  8144. return cli.Patch(path, headers, body, content_type, receiver);
  8145. });
  8146. }
  8147. TEST_F(ServerTest, PostQueryStringAndBody) {
  8148. auto res =
  8149. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8151. ASSERT_EQ(StatusCode::OK_200, res->status);
  8152. }
  8153. TEST_F(ServerTest, HTTP2Magic) {
  8154. Request req;
  8155. req.method = "PRI";
  8156. req.path = "*";
  8157. req.body = "SM";
  8158. auto res = std::make_shared<Response>();
  8159. auto error = Error::Success;
  8160. auto ret = cli_.send(req, *res, error);
  8161. ASSERT_TRUE(ret);
  8162. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8163. }
  8164. TEST_F(ServerTest, KeepAlive) {
  8165. auto res = cli_.Get("/hi");
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. EXPECT_EQ(StatusCode::OK_200, res->status);
  8168. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8169. EXPECT_EQ("Hello World!", res->body);
  8170. res = cli_.Get("/hi");
  8171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8172. EXPECT_EQ(StatusCode::OK_200, res->status);
  8173. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8174. EXPECT_EQ("Hello World!", res->body);
  8175. res = cli_.Get("/hi");
  8176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8177. EXPECT_EQ(StatusCode::OK_200, res->status);
  8178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8179. EXPECT_EQ("Hello World!", res->body);
  8180. res = cli_.Get("/not-exist");
  8181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8182. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8183. res = cli_.Post("/empty", "", "text/plain");
  8184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8185. EXPECT_EQ(StatusCode::OK_200, res->status);
  8186. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8187. EXPECT_EQ("empty", res->body);
  8188. EXPECT_EQ("close", res->get_header_value("Connection"));
  8189. res = cli_.Post(
  8190. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8191. "text/plain");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8195. EXPECT_EQ("empty", res->body);
  8196. cli_.set_keep_alive(false);
  8197. res = cli_.Get("/last-request");
  8198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8199. EXPECT_EQ(StatusCode::OK_200, res->status);
  8200. EXPECT_EQ("close", res->get_header_value("Connection"));
  8201. }
  8202. TEST_F(ServerTest, TooManyRedirect) {
  8203. cli_.set_follow_location(true);
  8204. auto res = cli_.Get("/redirect/0");
  8205. ASSERT_TRUE(!res);
  8206. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8207. }
  8208. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8209. Request req;
  8210. req.method = "FOOBAR";
  8211. req.path = "/hi";
  8212. cli_.set_keep_alive(true);
  8213. auto res = cli_.send(req);
  8214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8215. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8216. EXPECT_EQ("close", res->get_header_value("Connection"));
  8217. EXPECT_FALSE(cli_.is_socket_open());
  8218. }
  8219. TEST_F(ServerTest, CustomRouteReadsBody) {
  8220. const std::string xml =
  8221. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8222. Request req;
  8223. req.method = "PROPFIND";
  8224. req.path = "/dav/dir";
  8225. req.set_header("Depth", "1");
  8226. req.body = xml;
  8227. auto res = cli_.send(req);
  8228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8229. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8230. EXPECT_EQ(xml, res->body);
  8231. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8232. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8233. }
  8234. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8235. Request req;
  8236. req.method = "PROPFIND";
  8237. req.path = "/dav/42";
  8238. auto res = cli_.send(req);
  8239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8240. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8241. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8242. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8243. }
  8244. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8245. Request req;
  8246. req.method = "PROPFIND";
  8247. req.path = "/dav-re/123";
  8248. auto res = cli_.send(req);
  8249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8250. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8251. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8252. }
  8253. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8254. Request req;
  8255. req.method = "MKCOL";
  8256. req.path = "/dav-mkcol";
  8257. auto res = cli_.send(req);
  8258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8259. EXPECT_EQ(StatusCode::Created_201, res->status);
  8260. }
  8261. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8262. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8263. Request req;
  8264. req.method = "REPORT";
  8265. req.path = "/dav-report";
  8266. req.body = xml;
  8267. auto res = cli_.send(req);
  8268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8269. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8270. EXPECT_EQ(xml, res->body);
  8271. }
  8272. // A content reader route must fire even when the request carries no body,
  8273. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8274. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8275. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8276. Request req;
  8277. req.method = "REPORT";
  8278. req.path = "/dav-report";
  8279. auto res = cli_.send(req);
  8280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8281. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8282. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8283. }
  8284. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8285. Request req;
  8286. req.method = "PROPFIND";
  8287. req.path = "/not-dav";
  8288. auto res = cli_.send(req);
  8289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8291. }
  8292. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8293. Request req;
  8294. req.method = "UNLOCK";
  8295. req.path = "/dav/dir";
  8296. cli_.set_keep_alive(true);
  8297. auto res = cli_.send(req);
  8298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8299. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8300. EXPECT_EQ("close", res->get_header_value("Connection"));
  8301. EXPECT_FALSE(cli_.is_socket_open());
  8302. }
  8303. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8304. // The mount point serves this path, but only for GET and HEAD.
  8305. auto get_res = cli_.Get("/dir/index.html");
  8306. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8307. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8308. Request req;
  8309. req.method = "PROPFIND";
  8310. req.path = "/dir/index.html";
  8311. auto res = cli_.send(req);
  8312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8313. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8314. }
  8315. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8316. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8317. cli_.set_keep_alive(true);
  8318. for (auto i = 0; i < 2; i++) {
  8319. Request req;
  8320. req.method = "PROPFIND";
  8321. req.path = "/dav/dir";
  8322. req.body = xml;
  8323. auto res = cli_.send(req);
  8324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8325. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8326. EXPECT_EQ(xml, res->body);
  8327. EXPECT_TRUE(cli_.is_socket_open());
  8328. }
  8329. // A built-in method must still be served on the same connection.
  8330. cli_.set_keep_alive(false);
  8331. auto res = cli_.Get("/hi");
  8332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8333. EXPECT_EQ(StatusCode::OK_200, res->status);
  8334. EXPECT_EQ("close", res->get_header_value("Connection"));
  8335. }
  8336. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8337. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8338. Request req;
  8339. req.method = "PROPFIND";
  8340. req.path = "/dav/dir";
  8341. req.set_header("Expect", "100-continue");
  8342. req.body = xml;
  8343. auto res = cli_.send(req);
  8344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8345. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8346. EXPECT_EQ(xml, res->body);
  8347. }
  8348. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8349. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8350. TEST_F(ServerTest, Gzip) {
  8351. Headers headers;
  8352. headers.emplace("Accept-Encoding", "gzip, deflate");
  8353. auto res = cli_.Get("/compress", headers);
  8354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8355. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8356. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8357. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8358. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8359. "7890123456789012345678901234567890",
  8360. res->body);
  8361. EXPECT_EQ(StatusCode::OK_200, res->status);
  8362. }
  8363. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8364. Headers headers;
  8365. headers.emplace("Accept-Encoding", "gzip, deflate");
  8366. auto res = cli_.Get("/compress-with-charset", headers);
  8367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8368. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8369. EXPECT_EQ("application/json; charset=utf-8",
  8370. res->get_header_value("Content-Type"));
  8371. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8372. "7890123456789012345678901234567890",
  8373. res->body);
  8374. EXPECT_EQ(StatusCode::OK_200, res->status);
  8375. }
  8376. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8377. Headers headers;
  8378. headers.emplace("Accept-Encoding", "");
  8379. auto res = cli_.Get("/compress", headers);
  8380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8381. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8382. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8383. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8384. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8385. "7890123456789012345678901234567890",
  8386. res->body);
  8387. EXPECT_EQ(StatusCode::OK_200, res->status);
  8388. }
  8389. TEST_F(ServerTest, GzipWithContentReceiver) {
  8390. Headers headers;
  8391. headers.emplace("Accept-Encoding", "gzip, deflate");
  8392. std::string body;
  8393. auto res =
  8394. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8395. EXPECT_EQ(100U, data_length);
  8396. body.append(data, data_length);
  8397. return true;
  8398. });
  8399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8400. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8402. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8403. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8404. "7890123456789012345678901234567890",
  8405. body);
  8406. EXPECT_EQ(StatusCode::OK_200, res->status);
  8407. }
  8408. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8409. Headers headers;
  8410. headers.emplace("Accept-Encoding", "gzip, deflate");
  8411. cli_.set_decompress(false);
  8412. auto res = cli_.Get("/compress", headers);
  8413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8414. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8415. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8416. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8417. EXPECT_EQ(33U, res->body.size());
  8418. EXPECT_EQ(StatusCode::OK_200, res->status);
  8419. }
  8420. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8421. Headers headers;
  8422. headers.emplace("Accept-Encoding", "");
  8423. std::string body;
  8424. auto res =
  8425. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8426. EXPECT_EQ(100U, data_length);
  8427. body.append(data, data_length);
  8428. return true;
  8429. });
  8430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8431. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8432. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8433. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8434. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8435. "7890123456789012345678901234567890",
  8436. body);
  8437. EXPECT_EQ(StatusCode::OK_200, res->status);
  8438. }
  8439. TEST_F(ServerTest, NoGzip) {
  8440. Headers headers;
  8441. headers.emplace("Accept-Encoding", "gzip, deflate");
  8442. auto res = cli_.Get("/nocompress", headers);
  8443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8444. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8445. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8446. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8447. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8448. "7890123456789012345678901234567890",
  8449. res->body);
  8450. EXPECT_EQ(StatusCode::OK_200, res->status);
  8451. }
  8452. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8453. Headers headers;
  8454. headers.emplace("Accept-Encoding", "gzip, deflate");
  8455. std::string body;
  8456. auto res = cli_.Get("/nocompress", headers,
  8457. [&](const char *data, size_t data_length) {
  8458. EXPECT_EQ(100U, data_length);
  8459. body.append(data, data_length);
  8460. return true;
  8461. });
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8464. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8465. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8466. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8467. "7890123456789012345678901234567890",
  8468. body);
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. }
  8471. TEST_F(ServerTest, MultipartFormDataGzip) {
  8472. UploadFormDataItems items = {
  8473. {"key1", "test", "", ""},
  8474. {"key2", "--abcdefg123", "", ""},
  8475. };
  8476. cli_.set_compress(true);
  8477. auto res = cli_.Post("/compress-multipart", items);
  8478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8479. EXPECT_EQ(StatusCode::OK_200, res->status);
  8480. }
  8481. #endif
  8482. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8483. // Static file compression is opt-in, so these run their own server rather than
  8484. // flipping it on for the shared ServerTest fixture, which would silently
  8485. // rewrite what every other static file test is asserting.
  8486. class StaticFileCompressionTest : public ::testing::Test {
  8487. protected:
  8488. void TearDown() override {
  8489. if (t_.joinable()) {
  8490. svr_.stop();
  8491. t_.join();
  8492. }
  8493. }
  8494. int start(const std::function<void(Server &)> &configure = nullptr) {
  8495. // Serves the same tree as a directory of build-time compressed assets
  8496. // would be served: the mount point names the coding the files are already
  8497. // stored in. Registered before "/" so it is the one that matches.
  8498. svr_.set_mount_point("/pre-encoded", "./www",
  8499. {{"Content-Encoding", "gzip"}});
  8500. svr_.set_mount_point("/", "./www");
  8501. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8502. res.set_file_content("./www/dir/index.html", "text/html");
  8503. });
  8504. svr_.Get("/pre-encoded-file-content",
  8505. [](const Request & /*req*/, Response &res) {
  8506. res.set_header("Content-Encoding", "gzip");
  8507. res.set_file_content("./www/dir/index.html", "text/html");
  8508. });
  8509. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8510. res.set_content_provider(
  8511. 6, "text/plain",
  8512. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8513. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8514. return true;
  8515. });
  8516. });
  8517. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8518. res.set_content_provider(
  8519. 1000, "text/plain",
  8520. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8521. if (offset < 100) {
  8522. std::string data(100, 'A');
  8523. sink.write(data.data(), data.size());
  8524. return true;
  8525. }
  8526. std::this_thread::sleep_for(std::chrono::seconds(2));
  8527. std::string data(900, 'B');
  8528. sink.write(data.data(), data.size());
  8529. return true;
  8530. });
  8531. });
  8532. if (configure) { configure(svr_); }
  8533. auto port = svr_.bind_to_any_port(HOST);
  8534. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8535. svr_.wait_until_ready();
  8536. return port;
  8537. }
  8538. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8539. // Every file under ./www except 1MB.txt is smaller than the default
  8540. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8541. // it out of the way.
  8542. static void enable_without_floor(Server &svr) {
  8543. svr.set_static_file_compression(true);
  8544. svr.set_static_file_compression_min_length(0);
  8545. }
  8546. Server svr_;
  8547. std::thread t_;
  8548. };
  8549. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8550. auto port = start();
  8551. Client cli(HOST, port);
  8552. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_EQ(StatusCode::OK_200, res->status);
  8555. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8556. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8557. EXPECT_EQ(1048576U, res->body.size());
  8558. }
  8559. TEST_F(StaticFileCompressionTest, MountPoint) {
  8560. auto port = start(enable);
  8561. Client cli(HOST, port);
  8562. cli.set_decompress(false);
  8563. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8565. EXPECT_EQ(StatusCode::OK_200, res->status);
  8566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8567. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8568. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8569. // The response stays self-delimiting: a length, not a chunked body.
  8570. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8571. EXPECT_EQ(std::to_string(res->body.size()),
  8572. res->get_header_value("Content-Length"));
  8573. EXPECT_LT(res->body.size(), 1048576U);
  8574. EXPECT_FALSE(res->body.empty());
  8575. }
  8576. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8577. auto port = start(enable);
  8578. Client cli(HOST, port);
  8579. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8581. EXPECT_EQ(StatusCode::OK_200, res->status);
  8582. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8583. EXPECT_EQ(1048576U, res->body.size());
  8584. }
  8585. TEST_F(StaticFileCompressionTest, FileContent) {
  8586. auto port = start(enable_without_floor);
  8587. Client cli(HOST, port);
  8588. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8590. EXPECT_EQ(StatusCode::OK_200, res->status);
  8591. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8592. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8593. EXPECT_EQ(104U, res->body.size());
  8594. }
  8595. // A handler that serves an already-encoded file names the coding itself. The
  8596. // file-backed path decided its coding from Accept-Encoding and the content
  8597. // type alone, so it compressed the stored bytes a second time and appended a
  8598. // second Content-Encoding field line.
  8599. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8600. auto port = start(enable_without_floor);
  8601. Client cli(HOST, port);
  8602. cli.set_decompress(false);
  8603. auto res = cli.Get("/pre-encoded-file-content",
  8604. Headers{{"Accept-Encoding", "gzip"}});
  8605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8606. EXPECT_EQ(StatusCode::OK_200, res->status);
  8607. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8608. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8609. // Vary belongs to a coding the server chose, and it chose none here.
  8610. EXPECT_FALSE(res->has_header("Vary"));
  8611. // The file travels exactly as it is stored on disk.
  8612. EXPECT_EQ(104U, res->body.size());
  8613. }
  8614. // The 1MB file clears the default floor, so this one runs the configuration a
  8615. // deployment would actually have.
  8616. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8617. auto port = start(enable);
  8618. Client cli(HOST, port);
  8619. cli.set_decompress(false);
  8620. auto res =
  8621. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8623. EXPECT_EQ(StatusCode::OK_200, res->status);
  8624. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8625. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8626. EXPECT_FALSE(res->has_header("Vary"));
  8627. EXPECT_EQ(1048576U, res->body.size());
  8628. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8629. }
  8630. TEST_F(StaticFileCompressionTest, Head) {
  8631. auto port = start(enable);
  8632. Client cli(HOST, port);
  8633. cli.set_decompress(false);
  8634. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8635. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8636. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8638. EXPECT_EQ(StatusCode::OK_200, res->status);
  8639. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8640. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8641. // HEAD still reports the size a GET would return.
  8642. EXPECT_EQ(get->get_header_value("Content-Length"),
  8643. res->get_header_value("Content-Length"));
  8644. EXPECT_TRUE(res->body.empty());
  8645. }
  8646. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8647. auto port = start(enable);
  8648. Client cli(HOST, port);
  8649. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8650. {"Accept-Encoding", "gzip"}});
  8651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8652. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8653. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8654. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8655. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8656. EXPECT_EQ("cd", res->body);
  8657. }
  8658. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8659. auto port = start(enable);
  8660. Client cli(HOST, port);
  8661. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8663. EXPECT_EQ(StatusCode::OK_200, res->status);
  8664. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8665. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8666. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8667. }
  8668. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8669. auto port = start(enable);
  8670. Client cli(HOST, port);
  8671. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8673. EXPECT_EQ(StatusCode::OK_200, res->status);
  8674. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8675. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8676. EXPECT_TRUE(res->body.empty());
  8677. }
  8678. TEST_F(StaticFileCompressionTest, MinLength) {
  8679. auto port = start(enable);
  8680. Client cli(HOST, port);
  8681. // 104 bytes, well under the default floor. Compressing it would add the
  8682. // gzip header and trailer to a body that already fits in one packet.
  8683. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8685. EXPECT_EQ(StatusCode::OK_200, res->status);
  8686. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8687. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8688. }
  8689. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8690. auto port = start([](Server &svr) {
  8691. svr.set_static_file_compression(true);
  8692. svr.set_static_file_compression_min_length(1);
  8693. });
  8694. Client cli(HOST, port);
  8695. cli.set_decompress(false);
  8696. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8698. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8699. // A 9-byte file comes back larger than it went in, because gzip's header and
  8700. // trailer outweigh anything deflate can save. That is the end of the range
  8701. // the floor exists to keep out.
  8702. EXPECT_GT(res->body.size(), 9U);
  8703. }
  8704. TEST_F(StaticFileCompressionTest, MaxLength) {
  8705. auto port = start([](Server &svr) {
  8706. svr.set_static_file_compression(true);
  8707. svr.set_static_file_compression_min_length(0);
  8708. svr.set_static_file_compression_max_length(1024);
  8709. });
  8710. Client cli(HOST, port);
  8711. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8712. // defines `small` as a macro on Windows.
  8713. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8714. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8715. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8716. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8717. // Under it: compressed.
  8718. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8719. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8720. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8721. }
  8722. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8723. auto port = start(enable_without_floor);
  8724. Client cli(HOST, port);
  8725. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8726. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8727. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8728. auto identity_etag = identity->get_header_value("ETag");
  8729. ASSERT_FALSE(identity_etag.empty());
  8730. auto gzipped =
  8731. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8732. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8733. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8734. auto gzip_etag = gzipped->get_header_value("ETag");
  8735. ASSERT_FALSE(gzip_etag.empty());
  8736. // Two representations, two validators.
  8737. EXPECT_NE(identity_etag, gzip_etag);
  8738. // Each one revalidates against the request that would produce it...
  8739. auto fresh =
  8740. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8741. {"If-None-Match", gzip_etag}});
  8742. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8743. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8744. auto fresh_identity =
  8745. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8746. {"If-None-Match", identity_etag}});
  8747. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8748. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8749. // ...and not against the other representation.
  8750. auto crossed =
  8751. cli.Get("/dir/index.html",
  8752. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8753. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8754. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8755. }
  8756. // The opt-in covers responses the server reads off disk itself. A caller's own
  8757. // known-length provider keeps its Content-Length and, more importantly, keeps
  8758. // delivering incrementally: routing it through a compressor would hold every
  8759. // write back until zlib's window filled.
  8760. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8761. auto port = start(enable);
  8762. Client cli(HOST, port);
  8763. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8765. EXPECT_EQ(StatusCode::OK_200, res->status);
  8766. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8767. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8768. EXPECT_EQ("aaabbb", res->body);
  8769. }
  8770. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8771. auto port = start(enable);
  8772. Client cli(HOST, port);
  8773. cli.set_read_timeout(1, 0);
  8774. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8775. Headers{{"Accept-Encoding", "gzip"}});
  8776. ASSERT_TRUE(handle.is_valid());
  8777. // The provider writes 100 bytes and then stalls for longer than the read
  8778. // timeout. Those first bytes have to arrive anyway: run the response through
  8779. // a compressor and zlib holds them until its window fills, so the read would
  8780. // come back empty instead.
  8781. char buf[256];
  8782. auto n = handle.read(buf, sizeof(buf));
  8783. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8784. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8785. }
  8786. #endif
  8787. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8788. TEST_F(ServerTest, Brotli) {
  8789. Headers headers;
  8790. headers.emplace("Accept-Encoding", "br");
  8791. auto res = cli_.Get("/compress", headers);
  8792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8793. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8794. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8795. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8796. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8797. "7890123456789012345678901234567890",
  8798. res->body);
  8799. EXPECT_EQ(StatusCode::OK_200, res->status);
  8800. }
  8801. #endif
  8802. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8803. TEST_F(ServerTest, Zstd) {
  8804. Headers headers;
  8805. headers.emplace("Accept-Encoding", "zstd");
  8806. auto res = cli_.Get("/compress", headers);
  8807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8808. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8809. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8810. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8811. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8812. "7890123456789012345678901234567890",
  8813. res->body);
  8814. EXPECT_EQ(StatusCode::OK_200, res->status);
  8815. }
  8816. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8817. Headers headers;
  8818. headers.emplace("Accept-Encoding", "");
  8819. auto res = cli_.Get("/compress", headers);
  8820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8821. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8822. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8823. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8824. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8825. "7890123456789012345678901234567890",
  8826. res->body);
  8827. EXPECT_EQ(StatusCode::OK_200, res->status);
  8828. }
  8829. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8830. Headers headers;
  8831. headers.emplace("Accept-Encoding", "zstd");
  8832. std::string body;
  8833. auto res =
  8834. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8835. EXPECT_EQ(100U, data_length);
  8836. body.append(data, data_length);
  8837. return true;
  8838. });
  8839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8840. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8841. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8842. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8843. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8844. "7890123456789012345678901234567890",
  8845. body);
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. }
  8848. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8849. Headers headers;
  8850. headers.emplace("Accept-Encoding", "zstd");
  8851. cli_.set_decompress(false);
  8852. auto res = cli_.Get("/compress", headers);
  8853. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8854. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8855. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8856. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8858. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8859. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8860. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8861. EXPECT_EQ(StatusCode::OK_200, res->status);
  8862. ASSERT_EQ(26U, res->body.size());
  8863. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8864. 0);
  8865. }
  8866. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8867. Headers headers;
  8868. headers.emplace("Accept-Encoding", "");
  8869. std::string body;
  8870. auto res =
  8871. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8872. EXPECT_EQ(100U, data_length);
  8873. body.append(data, data_length);
  8874. return true;
  8875. });
  8876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8877. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8878. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8879. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8880. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8881. "7890123456789012345678901234567890",
  8882. body);
  8883. EXPECT_EQ(StatusCode::OK_200, res->status);
  8884. }
  8885. TEST_F(ServerTest, NoZstd) {
  8886. Headers headers;
  8887. headers.emplace("Accept-Encoding", "zstd");
  8888. auto res = cli_.Get("/nocompress", headers);
  8889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8890. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8891. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8892. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8893. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8894. "7890123456789012345678901234567890",
  8895. res->body);
  8896. EXPECT_EQ(StatusCode::OK_200, res->status);
  8897. }
  8898. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8899. Headers headers;
  8900. headers.emplace("Accept-Encoding", "zstd");
  8901. std::string body;
  8902. auto res = cli_.Get("/nocompress", headers,
  8903. [&](const char *data, size_t data_length) {
  8904. EXPECT_EQ(100U, data_length);
  8905. body.append(data, data_length);
  8906. return true;
  8907. });
  8908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8909. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8910. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8911. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8912. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8913. "7890123456789012345678901234567890",
  8914. body);
  8915. EXPECT_EQ(StatusCode::OK_200, res->status);
  8916. }
  8917. // TODO: How to enable zstd ??
  8918. TEST_F(ServerTest, MultipartFormDataZstd) {
  8919. UploadFormDataItems items = {
  8920. {"key1", "test", "", ""},
  8921. {"key2", "--abcdefg123", "", ""},
  8922. };
  8923. Headers headers;
  8924. headers.emplace("Accept-Encoding", "zstd");
  8925. cli_.set_compress(true);
  8926. auto res = cli_.Post("/compress-multipart", headers, items);
  8927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8928. EXPECT_EQ(StatusCode::OK_200, res->status);
  8929. }
  8930. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8931. Headers headers;
  8932. headers.emplace("Accept-Encoding", "zstd");
  8933. cli_.set_compress(true);
  8934. auto res = cli_.Put(
  8935. "/put", headers, 3,
  8936. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8937. sink.os << "PUT";
  8938. return true;
  8939. },
  8940. "text/plain");
  8941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8942. EXPECT_EQ(StatusCode::OK_200, res->status);
  8943. EXPECT_EQ("PUT", res->body);
  8944. }
  8945. // Pre-compression logging tests
  8946. TEST_F(ServerTest, PreCompressionLogging) {
  8947. // Test data for compression (matches the actual /compress endpoint content)
  8948. const std::string test_content =
  8949. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8950. "3456789012345678901234567890";
  8951. // Variables to capture logging data
  8952. std::string pre_compression_body;
  8953. std::string pre_compression_content_type;
  8954. std::string pre_compression_content_encoding;
  8955. std::string post_compression_body;
  8956. std::string post_compression_content_type;
  8957. std::string post_compression_content_encoding;
  8958. // Set up pre-compression logger
  8959. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8960. const Response &res) {
  8961. pre_compression_body = res.body;
  8962. pre_compression_content_type = res.get_header_value("Content-Type");
  8963. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8964. });
  8965. // Set up post-compression logger
  8966. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8967. post_compression_body = res.body;
  8968. post_compression_content_type = res.get_header_value("Content-Type");
  8969. post_compression_content_encoding =
  8970. res.get_header_value("Content-Encoding");
  8971. });
  8972. // Test with gzip compression
  8973. Headers headers;
  8974. headers.emplace("Accept-Encoding", "gzip");
  8975. auto res = cli_.Get("/compress", headers);
  8976. // Verify response was compressed
  8977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8978. EXPECT_EQ(StatusCode::OK_200, res->status);
  8979. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8980. // Verify pre-compression logger captured uncompressed content
  8981. EXPECT_EQ(test_content, pre_compression_body);
  8982. EXPECT_EQ("text/plain", pre_compression_content_type);
  8983. EXPECT_TRUE(pre_compression_content_encoding
  8984. .empty()); // No encoding header before compression
  8985. // Verify post-compression logger captured compressed content
  8986. EXPECT_NE(test_content,
  8987. post_compression_body); // Should be different after compression
  8988. EXPECT_EQ("text/plain", post_compression_content_type);
  8989. EXPECT_EQ("gzip", post_compression_content_encoding);
  8990. // Verify compressed content is smaller
  8991. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8992. }
  8993. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8994. const std::string test_content =
  8995. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8996. "3456789012345678901234567890";
  8997. std::string pre_compression_body;
  8998. std::string post_compression_body;
  8999. svr_.set_pre_compression_logger(
  9000. [&](const Request & /*req*/, const Response &res) {
  9001. pre_compression_body = res.body;
  9002. });
  9003. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9004. post_compression_body = res.body;
  9005. });
  9006. Headers headers;
  9007. headers.emplace("Accept-Encoding", "br");
  9008. auto res = cli_.Get("/compress", headers);
  9009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9010. EXPECT_EQ(StatusCode::OK_200, res->status);
  9011. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9012. // Verify pre-compression content is uncompressed
  9013. EXPECT_EQ(test_content, pre_compression_body);
  9014. // Verify post-compression content is compressed
  9015. EXPECT_NE(test_content, post_compression_body);
  9016. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9017. }
  9018. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9019. const std::string test_content =
  9020. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9021. "3456789012345678901234567890";
  9022. std::string pre_compression_body;
  9023. std::string post_compression_body;
  9024. svr_.set_pre_compression_logger(
  9025. [&](const Request & /*req*/, const Response &res) {
  9026. pre_compression_body = res.body;
  9027. });
  9028. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9029. post_compression_body = res.body;
  9030. });
  9031. // Request without compression (use /nocompress endpoint)
  9032. Headers headers;
  9033. auto res = cli_.Get("/nocompress", headers);
  9034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9035. EXPECT_EQ(StatusCode::OK_200, res->status);
  9036. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9037. // Pre-compression logger should not be called when no compression is applied
  9038. EXPECT_TRUE(
  9039. pre_compression_body.empty()); // Pre-compression logger not called
  9040. EXPECT_EQ(
  9041. test_content,
  9042. post_compression_body); // Post-compression logger captures final content
  9043. }
  9044. TEST_F(ServerTest, LoggerSeesContentLength) {
  9045. size_t logged_content_length = 0;
  9046. std::string logged_content_length_header;
  9047. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9048. logged_content_length = res.content_length_;
  9049. logged_content_length_header = res.get_header_value("Content-Length");
  9050. });
  9051. auto res = cli_.Get("/nocompress");
  9052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9053. EXPECT_EQ(StatusCode::OK_200, res->status);
  9054. EXPECT_EQ(res->body.size(), logged_content_length);
  9055. EXPECT_EQ(std::to_string(logged_content_length),
  9056. logged_content_length_header);
  9057. }
  9058. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9059. const std::string test_content =
  9060. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9061. "3456789012345678901234567890";
  9062. std::string pre_compression_body;
  9063. bool pre_logger_called = false;
  9064. // Set only pre-compression logger
  9065. svr_.set_pre_compression_logger(
  9066. [&](const Request & /*req*/, const Response &res) {
  9067. pre_compression_body = res.body;
  9068. pre_logger_called = true;
  9069. });
  9070. Headers headers;
  9071. headers.emplace("Accept-Encoding", "gzip");
  9072. auto res = cli_.Get("/compress", headers);
  9073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9074. EXPECT_EQ(StatusCode::OK_200, res->status);
  9075. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9076. // Verify pre-compression logger was called
  9077. EXPECT_TRUE(pre_logger_called);
  9078. EXPECT_EQ(test_content, pre_compression_body);
  9079. }
  9080. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9081. {
  9082. // Test with Expect: 100-continue header - success case
  9083. // Server returns 100 Continue, client sends body, server returns 200 OK
  9084. Request req;
  9085. req.method = "POST";
  9086. req.path = "/post-large";
  9087. req.set_header("Expect", "100-continue");
  9088. req.body = LARGE_DATA;
  9089. Response res;
  9090. auto error = Error::Success;
  9091. cli_.set_keep_alive(true);
  9092. auto ret = cli_.send(req, res, error);
  9093. EXPECT_TRUE(ret);
  9094. EXPECT_EQ(StatusCode::OK_200, res.status);
  9095. EXPECT_EQ(LARGE_DATA, res.body);
  9096. }
  9097. {
  9098. // Test with Expect: 100-continue header - error case
  9099. // Client should not send the body when server returns an error
  9100. Request req;
  9101. req.method = "POST";
  9102. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9103. req.set_header("Expect", "100-continue");
  9104. req.body = LARGE_DATA;
  9105. Response res;
  9106. auto error = Error::Success;
  9107. auto start = std::chrono::high_resolution_clock::now();
  9108. cli_.set_keep_alive(true);
  9109. auto ret = cli_.send(req, res, error);
  9110. auto end = std::chrono::high_resolution_clock::now();
  9111. auto elapsed =
  9112. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9113. .count();
  9114. // With Expect: 100-continue, request completes successfully but with error
  9115. EXPECT_TRUE(ret);
  9116. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9117. EXPECT_EQ("close", res.get_header_value("Connection"));
  9118. EXPECT_FALSE(cli_.is_socket_open());
  9119. EXPECT_LE(elapsed, 2000);
  9120. }
  9121. {
  9122. // Send an extra GET request to ensure error recovery without hanging
  9123. Request req;
  9124. req.method = "GET";
  9125. req.path = "/hi";
  9126. auto start = std::chrono::high_resolution_clock::now();
  9127. auto res = cli_.send(req);
  9128. auto end = std::chrono::high_resolution_clock::now();
  9129. auto elapsed =
  9130. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9131. .count();
  9132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9133. EXPECT_EQ(StatusCode::OK_200, res->status);
  9134. EXPECT_EQ("Hello World!", res->body);
  9135. EXPECT_LE(elapsed, 500);
  9136. }
  9137. }
  9138. TEST(ZstdDecompressor, ChunkedDecompression) {
  9139. std::string data;
  9140. for (size_t i = 0; i < 32 * 1024; ++i) {
  9141. data.push_back(static_cast<char>('a' + i % 26));
  9142. }
  9143. std::string compressed_data;
  9144. {
  9145. httplib::detail::zstd_compressor compressor;
  9146. bool result = compressor.compress(
  9147. data.data(), data.size(),
  9148. /*last=*/true,
  9149. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9150. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9151. compressed_data_size);
  9152. return true;
  9153. });
  9154. ASSERT_TRUE(result);
  9155. }
  9156. std::string decompressed_data;
  9157. {
  9158. httplib::detail::zstd_decompressor decompressor;
  9159. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9160. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9161. size_t chunk_size = 130;
  9162. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9163. chunk_begin += chunk_size) {
  9164. size_t current_chunk_size =
  9165. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9166. bool result = decompressor.decompress(
  9167. compressed_data.data() + chunk_begin, current_chunk_size,
  9168. [&](const char *decompressed_data_chunk,
  9169. size_t decompressed_data_chunk_size) {
  9170. decompressed_data.insert(decompressed_data.size(),
  9171. decompressed_data_chunk,
  9172. decompressed_data_chunk_size);
  9173. return true;
  9174. });
  9175. ASSERT_TRUE(result);
  9176. }
  9177. }
  9178. ASSERT_EQ(data, decompressed_data);
  9179. }
  9180. TEST(ZstdDecompressor, Decompress) {
  9181. std::string original_text = "Compressed with ZSTD";
  9182. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9183. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9184. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9185. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9186. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9187. std::string decompressed_data;
  9188. {
  9189. httplib::detail::zstd_decompressor decompressor;
  9190. bool result = decompressor.decompress(
  9191. compressed_data.data(), compressed_data.size(),
  9192. [&](const char *decompressed_data_chunk,
  9193. size_t decompressed_data_chunk_size) {
  9194. decompressed_data.insert(decompressed_data.size(),
  9195. decompressed_data_chunk,
  9196. decompressed_data_chunk_size);
  9197. return true;
  9198. });
  9199. ASSERT_TRUE(result);
  9200. }
  9201. ASSERT_EQ(original_text, decompressed_data);
  9202. }
  9203. #endif
  9204. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9205. // separate chunks so that the server sees each part in its own read(). Used to
  9206. // place a read boundary at a specific offset of a request body.
  9207. static bool send_request_in_parts(time_t read_timeout_sec,
  9208. const std::vector<std::string> &parts,
  9209. std::string *resp = nullptr,
  9210. int port = PORT) {
  9211. auto error = Error::Success;
  9212. auto client_sock = detail::create_client_socket(
  9213. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9214. /*connection_timeout_sec=*/5, 0,
  9215. /*read_timeout_sec=*/5, 0,
  9216. /*write_timeout_sec=*/5, 0, std::string(), error);
  9217. if (client_sock == INVALID_SOCKET) { return false; }
  9218. auto ret = detail::process_client_socket(
  9219. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9220. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9221. for (size_t i = 0; i < parts.size(); i++) {
  9222. const auto &part = parts[i];
  9223. if (part.size() !=
  9224. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9225. return false;
  9226. }
  9227. if (i + 1 < parts.size()) {
  9228. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9229. }
  9230. }
  9231. char buf[512];
  9232. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9233. while (line_reader.getline()) {
  9234. if (resp) { *resp += line_reader.ptr(); }
  9235. }
  9236. return true;
  9237. });
  9238. detail::close_socket(client_sock);
  9239. return ret;
  9240. }
  9241. // Sends a raw request to a server listening at HOST:PORT.
  9242. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9243. std::string *resp = nullptr, int port = PORT) {
  9244. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9245. }
  9246. #ifdef CPPHTTPLIB_SSL_ENABLED
  9247. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9248. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9249. ASSERT_TRUE(svr.is_valid());
  9250. svr.set_read_timeout(1, 0);
  9251. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9252. auto se = detail::scope_exit([&] {
  9253. svr.stop();
  9254. t.join();
  9255. ASSERT_FALSE(svr.is_running());
  9256. });
  9257. svr.wait_until_ready();
  9258. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9259. // keeps each wait well within the read timeout. The server gives up a
  9260. // second in, so the bytes sent after that fail.
  9261. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9262. parts.resize(26, std::string(1, '\0'));
  9263. EXPECT_FALSE(send_request_in_parts(5, parts));
  9264. }
  9265. #endif
  9266. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9267. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9268. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9269. const std::vector<std::string> &parts,
  9270. std::string *resp = nullptr,
  9271. int port = PORT) {
  9272. auto error = Error::Success;
  9273. auto sock = detail::create_client_socket(
  9274. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9275. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9276. /*write_timeout_sec=*/5, 0, std::string(), error);
  9277. if (sock == INVALID_SOCKET) { return false; }
  9278. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9279. auto ctx = SSL_CTX_new(TLS_client_method());
  9280. auto ssl = SSL_new(ctx);
  9281. auto ssl_se = detail::scope_exit([&] {
  9282. SSL_free(ssl);
  9283. SSL_CTX_free(ctx);
  9284. });
  9285. SSL_set_fd(ssl, static_cast<int>(sock));
  9286. if (SSL_connect(ssl) != 1) { return false; }
  9287. for (size_t i = 0; i < parts.size(); i++) {
  9288. const auto &part = parts[i];
  9289. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9290. static_cast<int>(part.size())) {
  9291. return false;
  9292. }
  9293. if (i + 1 < parts.size()) {
  9294. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9295. }
  9296. }
  9297. char buf[512];
  9298. int n;
  9299. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9300. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9301. }
  9302. return true;
  9303. }
  9304. #endif
  9305. // The request line, then a header value a byte at a time.
  9306. static std::vector<std::string> slow_request_head_parts() {
  9307. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9308. parts.resize(26, "a");
  9309. parts.emplace_back("\r\n\r\n");
  9310. return parts;
  9311. }
  9312. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9313. // within the one-second read timeout. The server gives up a second in, before
  9314. // the head is complete.
  9315. static void
  9316. expect_slow_request_head_dropped(Server &svr,
  9317. const std::function<std::string()> &send) {
  9318. std::atomic<bool> handled(false);
  9319. svr.Get("/", [&](const Request &, Response &res) {
  9320. handled = true;
  9321. res.set_content("ok", "text/plain");
  9322. });
  9323. svr.set_read_timeout(1, 0);
  9324. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9325. auto se = detail::scope_exit([&] {
  9326. svr.stop();
  9327. t.join();
  9328. ASSERT_FALSE(svr.is_running());
  9329. });
  9330. svr.wait_until_ready();
  9331. auto resp = send();
  9332. EXPECT_FALSE(handled);
  9333. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9334. }
  9335. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9336. Server svr;
  9337. expect_slow_request_head_dropped(svr, [] {
  9338. std::string resp;
  9339. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9340. return resp;
  9341. });
  9342. }
  9343. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9344. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9345. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9346. ASSERT_TRUE(svr.is_valid());
  9347. expect_slow_request_head_dropped(svr, [] {
  9348. std::string resp;
  9349. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9350. return resp;
  9351. });
  9352. }
  9353. #endif
  9354. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9355. Server svr;
  9356. std::string header_value;
  9357. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9358. header_value = req.get_header_value("foo");
  9359. res.set_content("ok", "text/plain");
  9360. });
  9361. thread t = thread([&] { svr.listen(HOST, PORT); });
  9362. auto se = detail::scope_exit([&] {
  9363. svr.stop();
  9364. t.join();
  9365. ASSERT_FALSE(svr.is_running());
  9366. });
  9367. svr.wait_until_ready();
  9368. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9369. // like characters are not treated the same - use vertical tab and escape.
  9370. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9371. "foo: \t \v bar \x1B\t \r\n"
  9372. "Connection: close\r\n"
  9373. "\r\n";
  9374. std::string res;
  9375. ASSERT_TRUE(send_request(5, req, &res));
  9376. EXPECT_EQ(header_value, "");
  9377. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9378. }
  9379. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9380. Server svr;
  9381. std::string received;
  9382. svr.Get("/order", [&](const Request &req, Response &res) {
  9383. received = entries_to_string(req.headers);
  9384. res.set_content("ok", "text/plain");
  9385. });
  9386. auto port = svr.bind_to_any_port(HOST);
  9387. thread t = thread([&] { svr.listen_after_bind(); });
  9388. auto se = detail::scope_exit([&] {
  9389. svr.stop();
  9390. t.join();
  9391. ASSERT_FALSE(svr.is_running());
  9392. });
  9393. svr.wait_until_ready();
  9394. const std::string req = "GET /order HTTP/1.1\r\n"
  9395. "Host: localhost\r\n"
  9396. "X-First: 1\r\n"
  9397. "X-Dup: a\r\n"
  9398. "X-Second: 2\r\n"
  9399. "X-Dup: b\r\n"
  9400. "Connection: close\r\n"
  9401. "\r\n";
  9402. std::string res;
  9403. ASSERT_TRUE(send_request(5, req, &res, port));
  9404. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9405. EXPECT_EQ(
  9406. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9407. received);
  9408. }
  9409. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9410. Server svr;
  9411. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9412. res.set_header("Set-Cookie", "first=1");
  9413. res.set_header("X-Between", "y");
  9414. res.set_header("Set-Cookie", "second=2");
  9415. res.set_content("ok", "text/plain");
  9416. });
  9417. auto port = svr.bind_to_any_port(HOST);
  9418. thread t = thread([&] { svr.listen_after_bind(); });
  9419. auto se = detail::scope_exit([&] {
  9420. svr.stop();
  9421. t.join();
  9422. ASSERT_FALSE(svr.is_running());
  9423. });
  9424. svr.wait_until_ready();
  9425. Client cli(HOST, port);
  9426. auto res = cli.Get("/cookies");
  9427. ASSERT_TRUE(res);
  9428. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9429. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9430. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9431. }
  9432. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9433. Server svr;
  9434. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9435. auto i = new int(0);
  9436. res.set_header("Trailer", "X-Safe, X-Reflected");
  9437. res.set_chunked_content_provider(
  9438. "text/plain",
  9439. [i](size_t /*offset*/, DataSink &sink) {
  9440. if (*i == 0) {
  9441. sink.os << "body";
  9442. } else {
  9443. Headers trailer;
  9444. // A valid trailer that must survive.
  9445. trailer.emplace("X-Safe", "safe");
  9446. // Attacker-controlled value carrying CR/LF (response splitting).
  9447. trailer.emplace("X-Reflected",
  9448. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9449. // Attacker-controlled name carrying CR/LF.
  9450. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9451. sink.done_with_trailer(trailer);
  9452. }
  9453. (*i)++;
  9454. return true;
  9455. },
  9456. [i](bool /*success*/) { delete i; });
  9457. });
  9458. thread t = thread([&] { svr.listen(HOST, PORT); });
  9459. auto se = detail::scope_exit([&] {
  9460. svr.stop();
  9461. t.join();
  9462. ASSERT_FALSE(svr.is_running());
  9463. });
  9464. svr.wait_until_ready();
  9465. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9466. "Host: " + HOST +
  9467. "\r\n"
  9468. "Connection: close\r\n"
  9469. "\r\n";
  9470. std::string res;
  9471. ASSERT_TRUE(send_request(5, req, &res));
  9472. // The injected fields must not appear anywhere in the raw response.
  9473. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9474. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9475. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9476. // Invalid trailers are dropped entirely, matching set_header().
  9477. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9478. // The valid trailer still passes through.
  9479. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9480. }
  9481. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9482. Server svr;
  9483. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9484. // res.headers is a public field an application can populate directly,
  9485. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9486. // A valid header that must survive.
  9487. res.headers.emplace("X-Safe", "safe");
  9488. // Attacker-controlled value carrying CR/LF (response splitting).
  9489. res.headers.emplace("X-Reflected",
  9490. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9491. // Attacker-controlled name carrying CR/LF.
  9492. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9493. res.set_content("body", "text/plain");
  9494. });
  9495. thread t = thread([&] { svr.listen(HOST, PORT); });
  9496. auto se = detail::scope_exit([&] {
  9497. svr.stop();
  9498. t.join();
  9499. ASSERT_FALSE(svr.is_running());
  9500. });
  9501. svr.wait_until_ready();
  9502. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9503. "Host: " + HOST +
  9504. "\r\n"
  9505. "Connection: close\r\n"
  9506. "\r\n";
  9507. std::string res;
  9508. ASSERT_TRUE(send_request(5, req, &res));
  9509. // The injected fields must not appear anywhere in the raw response.
  9510. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9511. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9512. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9513. // Invalid headers are dropped entirely, matching set_header().
  9514. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9515. // The valid header still passes through.
  9516. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9517. }
  9518. // Forward declaration: in split builds split.py strips `inline` and moves the
  9519. // definition into httplib.cc, so detail::write_request_line is not visible from
  9520. // the public httplib.h. Re-declaring it here lets the tests link against the
  9521. // symbol in both header-only and split builds.
  9522. namespace httplib {
  9523. namespace detail {
  9524. ssize_t write_request_line(Stream &strm, const std::string &method,
  9525. const std::string &path);
  9526. } // namespace detail
  9527. } // namespace httplib
  9528. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9529. // A well-formed target is written verbatim.
  9530. {
  9531. detail::BufferStream strm;
  9532. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9533. EXPECT_GT(n, 0);
  9534. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9535. }
  9536. // A target carrying CR/LF, SP or other control octets must be rejected
  9537. // before anything reaches the wire, otherwise it splits the request line and
  9538. // injects a header or a whole request.
  9539. const std::string evil_targets[] = {
  9540. "/a\r\nInjected: pwned",
  9541. "/a\rInjected",
  9542. "/a\nInjected",
  9543. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9544. "/a b",
  9545. "/a\tb",
  9546. "/a\x7f",
  9547. };
  9548. for (const auto &evil : evil_targets) {
  9549. detail::BufferStream strm;
  9550. auto n = detail::write_request_line(strm, "GET", evil);
  9551. EXPECT_LT(n, 0);
  9552. EXPECT_TRUE(strm.get_buffer().empty());
  9553. }
  9554. }
  9555. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9556. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9557. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9558. // target reaches write_request. The client must fail cleanly with
  9559. // Error::Write instead of putting a request-line-less, header-injecting
  9560. // request on the wire.
  9561. Server svr;
  9562. svr.Get("/a", [](const Request &, Response &res) {
  9563. res.set_content("ok", "text/plain");
  9564. });
  9565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9566. auto se = detail::scope_exit([&] {
  9567. svr.stop();
  9568. thread.join();
  9569. ASSERT_FALSE(svr.is_running());
  9570. });
  9571. svr.wait_until_ready();
  9572. {
  9573. Client cli(HOST, PORT);
  9574. cli.set_path_encode(false);
  9575. // The request is rejected before anything is written, so the connection
  9576. // stays silent and the subsequent response read would otherwise block for
  9577. // the full default read timeout. Shorten it -- the assertion is on the
  9578. // error, not the timeout.
  9579. cli.set_read_timeout(1, 0);
  9580. auto res = cli.Get("/a\r\nInjected: pwned");
  9581. EXPECT_FALSE(res);
  9582. EXPECT_EQ(Error::Write, res.error());
  9583. }
  9584. }
  9585. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9586. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9587. // including extension methods.
  9588. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9589. for (const auto &method : good_methods) {
  9590. detail::BufferStream strm;
  9591. auto n = detail::write_request_line(strm, method, "/");
  9592. EXPECT_GT(n, 0);
  9593. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9594. }
  9595. // A method carrying CR/LF would split the request line and smuggle a whole
  9596. // request ahead of the real one. A space or an empty method corrupts the
  9597. // request line. All must be rejected before anything reaches the wire.
  9598. const std::string evil_methods[] = {
  9599. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9600. "GET\r\nInjected: pwned",
  9601. "GET\r",
  9602. "GET\n",
  9603. "GE T",
  9604. "",
  9605. };
  9606. for (const auto &evil : evil_methods) {
  9607. detail::BufferStream strm;
  9608. auto n = detail::write_request_line(strm, evil, "/");
  9609. EXPECT_LT(n, 0);
  9610. EXPECT_TRUE(strm.get_buffer().empty());
  9611. }
  9612. }
  9613. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9614. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9615. // through Client::send must fail with Error::Write and no request, neither
  9616. // the smuggled one nor the real one, may reach the server.
  9617. Server svr;
  9618. std::atomic<int> request_count(0);
  9619. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9620. request_count++;
  9621. res.status = StatusCode::OK_200;
  9622. return Server::HandlerResponse::Handled;
  9623. });
  9624. auto port = svr.bind_to_any_port(HOST);
  9625. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9626. auto se = detail::scope_exit([&] {
  9627. svr.stop();
  9628. thread.join();
  9629. ASSERT_FALSE(svr.is_running());
  9630. });
  9631. svr.wait_until_ready();
  9632. {
  9633. Client cli(HOST, port);
  9634. const std::string evil_methods[] = {
  9635. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9636. "GE T",
  9637. "",
  9638. };
  9639. for (const auto &evil : evil_methods) {
  9640. Request req;
  9641. req.method = evil;
  9642. req.path = "/";
  9643. auto res = cli.send(req);
  9644. EXPECT_FALSE(res);
  9645. EXPECT_EQ(Error::Write, res.error());
  9646. }
  9647. auto handle =
  9648. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9649. EXPECT_FALSE(handle.is_valid());
  9650. EXPECT_EQ(Error::Write, handle.error);
  9651. // A valid request on the same client still goes through.
  9652. auto res = cli.Get("/");
  9653. ASSERT_TRUE(res);
  9654. EXPECT_EQ(StatusCode::OK_200, res->status);
  9655. }
  9656. EXPECT_EQ(1, request_count.load());
  9657. }
  9658. // Sends a raw request and verifies that there isn't a crash or exception.
  9659. static void test_raw_request(const std::string &req,
  9660. std::string *out = nullptr) {
  9661. Server svr;
  9662. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9663. res.set_content("ok", "text/plain");
  9664. });
  9665. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9666. res.set_content("ok", "text/plain");
  9667. });
  9668. svr.Get("/header_field_value_check",
  9669. [&](const Request & /*req*/, Response &res) {
  9670. res.set_content("ok", "text/plain");
  9671. });
  9672. svr.CustomRoute("PROPFIND", "/dav",
  9673. [&](const Request & /*req*/, Response &res) {
  9674. res.status = StatusCode::MultiStatus_207;
  9675. });
  9676. // Server read timeout must be longer than the client read timeout for the
  9677. // bug to reproduce, probably to force the server to process a request
  9678. // without a trailing blank line.
  9679. const time_t client_read_timeout_sec = 1;
  9680. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9681. bool listen_thread_ok = false;
  9682. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9683. auto se = detail::scope_exit([&] {
  9684. svr.stop();
  9685. t.join();
  9686. ASSERT_FALSE(svr.is_running());
  9687. EXPECT_TRUE(listen_thread_ok);
  9688. });
  9689. svr.wait_until_ready();
  9690. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9691. }
  9692. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9693. // A certain header line causes an exception if the header property is parsed
  9694. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9695. test_raw_request(
  9696. "GET /hi HTTP/1.1\r\n"
  9697. " : "
  9698. " "
  9699. " ");
  9700. }
  9701. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9702. // A certain header line causes an exception if the header property *name* is
  9703. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9704. // greedy matcher and requires backtracking when there are a lot of ":"
  9705. // characters.
  9706. // This occurs with libc++ but not libstdc++.
  9707. test_raw_request(
  9708. "GET /hi HTTP/1.1\r\n"
  9709. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9710. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9711. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9712. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9713. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9714. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9715. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9716. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9717. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9718. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9719. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9720. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9721. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9722. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9723. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9724. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9725. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9726. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9727. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9728. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9729. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9730. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9731. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9732. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9733. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9734. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9735. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9736. "&&&%%%");
  9737. }
  9738. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9739. // Make sure this doesn't crash the server.
  9740. // In a previous version of the header line regex, the "\r" rendered the line
  9741. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9742. // a new position where the leading white space ended and the field value
  9743. // began.
  9744. // The crash occurs with libc++ but not libstdc++.
  9745. test_raw_request("GET /hi HTTP/1.1\r\n"
  9746. "a:" +
  9747. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9748. "\r\n"
  9749. "\r\n");
  9750. }
  9751. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9752. const char *rejected[] = {
  9753. // RFC 9112 §3: one SP between the parts, and nothing else
  9754. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9755. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9756. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9757. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9758. // A request-target has no fragment
  9759. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9760. // An HTTP/1.1 request needs a Host
  9761. "GET /hi HTTP/1.1\r\n\r\n",
  9762. };
  9763. for (auto request : rejected) {
  9764. std::string out;
  9765. test_raw_request(request, &out);
  9766. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9767. }
  9768. std::string out;
  9769. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9770. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9771. }
  9772. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9773. // RFC 9112 §6.1
  9774. const char *requests[] = {
  9775. "PUT /put_hi HTTP/1.1\r\n"
  9776. "Host: localhost\r\n"
  9777. "Content-Length: 0\r\n"
  9778. "Transfer-Encoding: chunked\r\n"
  9779. "\r\n"
  9780. "0\r\n\r\n",
  9781. "PUT /put_hi HTTP/1.0\r\n"
  9782. "Connection: keep-alive\r\n"
  9783. "Transfer-Encoding: chunked\r\n"
  9784. "\r\n"
  9785. "0\r\n\r\n",
  9786. };
  9787. for (auto request : requests) {
  9788. std::string out;
  9789. test_raw_request(request, &out);
  9790. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9791. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9792. }
  9793. }
  9794. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9795. std::string out;
  9796. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9797. "Content-Type: text/plain\r\n"
  9798. "Transfer-Encoding: chunked\r\n"
  9799. "\r\n"
  9800. "nothex\r\n",
  9801. &out);
  9802. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9803. }
  9804. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9805. std::string out;
  9806. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9807. "Content-Type: text/plain\r\n"
  9808. "Transfer-Encoding: chunked\r\n"
  9809. "\r\n"
  9810. "3\r\n"
  9811. "xyz\r\n"
  9812. "NaN\r\n",
  9813. &out);
  9814. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9815. }
  9816. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9817. std::string out;
  9818. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9819. "Content-Type: text/plain\r\n"
  9820. "Transfer-Encoding: chunked\r\n"
  9821. "\r\n"
  9822. // Length is too large for 64 bits.
  9823. "1ffffffffffffffff\r\n"
  9824. "xyz\r\n",
  9825. &out);
  9826. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9827. }
  9828. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9829. test_raw_request("GET /hi HTTP/1.1\r\n"
  9830. "Content-Type: text/plain\r\n\r");
  9831. }
  9832. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9833. std::string out;
  9834. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9835. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9836. }
  9837. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9838. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9839. std::string out;
  9840. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9841. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9842. }
  9843. }
  9844. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9845. std::string out;
  9846. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9847. "Host: localhost\r\n"
  9848. "Connection: close\r\n\r\n",
  9849. &out);
  9850. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9851. }
  9852. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9853. Server svr;
  9854. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9855. EXPECT_TRUE(!req.remote_addr.empty());
  9856. });
  9857. thread t = thread([&] { svr.listen(HOST, PORT); });
  9858. auto se = detail::scope_exit([&] {
  9859. svr.stop();
  9860. t.join();
  9861. ASSERT_FALSE(svr.is_running());
  9862. });
  9863. svr.wait_until_ready();
  9864. // Send an invalid request line to trigger Bad Request
  9865. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9866. std::string out;
  9867. ASSERT_TRUE(send_request(5, bad_req, &out));
  9868. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9869. }
  9870. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9871. // answered right away rather than blocking on a read that waits for EOF.
  9872. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9873. std::string out;
  9874. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9875. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9876. }
  9877. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9878. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9879. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9880. for (const auto *method : methods) {
  9881. Server svr;
  9882. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9883. EXPECT_FALSE(svr.is_valid()) << method;
  9884. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9885. }
  9886. }
  9887. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9888. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9889. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9890. for (const auto *method : methods) {
  9891. Server svr;
  9892. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9893. EXPECT_FALSE(svr.is_valid()) << method;
  9894. }
  9895. }
  9896. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9897. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9898. "COPY", "MOVE", "LOCK",
  9899. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9900. Server svr;
  9901. for (const auto *method : methods) {
  9902. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9903. }
  9904. EXPECT_TRUE(svr.is_valid());
  9905. }
  9906. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9907. Server svr;
  9908. svr.CustomRoute("POST", "/x",
  9909. [](const Request &, Response &, const ContentReader &) {});
  9910. EXPECT_FALSE(svr.is_valid());
  9911. }
  9912. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9913. Server svr;
  9914. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9915. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9916. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9917. EXPECT_FALSE(svr.is_valid());
  9918. }
  9919. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9920. Server svr;
  9921. auto captured = Error::Success;
  9922. svr.set_error_logger(
  9923. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9924. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9925. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9926. }
  9927. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9928. std::string out;
  9929. std::string request(
  9930. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9931. test_raw_request(request, &out);
  9932. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9933. }
  9934. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9935. std::string out;
  9936. std::string request(
  9937. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9938. test_raw_request(request, &out);
  9939. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9940. }
  9941. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9942. std::string out;
  9943. std::string request(
  9944. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9945. test_raw_request(request, &out);
  9946. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9947. }
  9948. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9949. std::string out;
  9950. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9951. "Host: localhost\r\n"
  9952. "Test: \r\n\r\n",
  9953. &out);
  9954. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9955. }
  9956. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9957. Server svr;
  9958. std::string x_custom;
  9959. std::string cookie;
  9960. std::string xff;
  9961. std::string x_unicode;
  9962. std::string x_iis;
  9963. svr.Get("/check", [&](const Request &req, Response &res) {
  9964. x_custom = req.get_header_value("X-Custom");
  9965. cookie = req.get_header_value("Cookie");
  9966. xff = req.get_header_value("X-Forwarded-For");
  9967. x_unicode = req.get_header_value("X-Unicode");
  9968. x_iis = req.get_header_value("X-IIS");
  9969. res.set_content("ok", "text/plain");
  9970. });
  9971. thread t = thread([&] { svr.listen(HOST, PORT); });
  9972. auto se = detail::scope_exit([&] {
  9973. svr.stop();
  9974. t.join();
  9975. ASSERT_FALSE(svr.is_running());
  9976. });
  9977. svr.wait_until_ready();
  9978. const std::string req = "GET /check HTTP/1.1\r\n"
  9979. "Host: localhost\r\n"
  9980. "X-Custom: a%0D%0AInjected: b\r\n"
  9981. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9982. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9983. "X-Unicode: %E3%81%82\r\n"
  9984. "X-IIS: %u00E9\r\n"
  9985. "Connection: close\r\n"
  9986. "\r\n";
  9987. std::string res;
  9988. ASSERT_TRUE(send_request(5, req, &res));
  9989. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9990. // Every value must be returned verbatim (wire form), with no decoding.
  9991. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9992. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9993. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9994. EXPECT_EQ("%E3%81%82", x_unicode);
  9995. EXPECT_EQ("%u00E9", x_iis);
  9996. }
  9997. // Applications that previously relied on automatic percent-decoding can
  9998. // reproduce the old behavior by explicitly calling decode_path_component()
  9999. // or, for RFC 3986 conformance, decode_uri_component().
  10000. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10001. Server svr;
  10002. std::string decoded;
  10003. svr.Get("/check", [&](const Request &req, Response &res) {
  10004. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10005. res.set_content("ok", "text/plain");
  10006. });
  10007. thread t = thread([&] { svr.listen(HOST, PORT); });
  10008. auto se = detail::scope_exit([&] {
  10009. svr.stop();
  10010. t.join();
  10011. ASSERT_FALSE(svr.is_running());
  10012. });
  10013. svr.wait_until_ready();
  10014. const std::string req = "GET /check HTTP/1.1\r\n"
  10015. "Host: localhost\r\n"
  10016. "X-Custom: hello%20world\r\n"
  10017. "Connection: close\r\n"
  10018. "\r\n";
  10019. std::string res;
  10020. ASSERT_TRUE(send_request(5, req, &res));
  10021. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10022. EXPECT_EQ("hello world", decoded);
  10023. }
  10024. // Regression test for #2033. Browsers send Referer values that include
  10025. // percent-encoded characters such as %0A inside the URL. Decoding the
  10026. // header value would either trip the post-decode CR/LF/NUL guard (the
  10027. // original bug, returning 400) or, after that guard was relaxed, silently
  10028. // store a literal LF — both unacceptable. The wire form must round-trip.
  10029. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10030. Server svr;
  10031. std::string referer;
  10032. svr.Get("/check", [&](const Request &req, Response &res) {
  10033. referer = req.get_header_value("Referer");
  10034. res.set_content("ok", "text/plain");
  10035. });
  10036. thread t = thread([&] { svr.listen(HOST, PORT); });
  10037. auto se = detail::scope_exit([&] {
  10038. svr.stop();
  10039. t.join();
  10040. ASSERT_FALSE(svr.is_running());
  10041. });
  10042. svr.wait_until_ready();
  10043. const std::string req = "GET /check HTTP/1.1\r\n"
  10044. "Host: localhost\r\n"
  10045. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10046. "Connection: close\r\n"
  10047. "\r\n";
  10048. std::string res;
  10049. ASSERT_TRUE(send_request(5, req, &res));
  10050. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10051. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10052. }
  10053. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10054. Server svr;
  10055. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10056. res.set_header("Cache-Control", "no-cache");
  10057. res.set_chunked_content_provider(
  10058. "text/event-stream", [](size_t offset, DataSink &sink) {
  10059. std::string s = "data:";
  10060. s += std::to_string(offset);
  10061. s += "\n\n";
  10062. auto ret = sink.write(s.data(), s.size());
  10063. EXPECT_TRUE(ret);
  10064. std::this_thread::sleep_for(std::chrono::seconds(1));
  10065. return true;
  10066. });
  10067. });
  10068. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10069. svr.wait_until_ready();
  10070. Client client(HOST, PORT);
  10071. const Headers headers = {{"Accept", "text/event-stream"}};
  10072. auto get_thread = std::thread([&client, &headers]() {
  10073. auto res = client.Get(
  10074. "/events", headers,
  10075. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10076. });
  10077. auto se = detail::scope_exit([&] {
  10078. svr.stop();
  10079. get_thread.join();
  10080. listen_thread.join();
  10081. ASSERT_FALSE(svr.is_running());
  10082. });
  10083. // Give GET time to get a few messages.
  10084. std::this_thread::sleep_for(std::chrono::seconds(2));
  10085. }
  10086. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10087. httplib::Server svr;
  10088. svr.Post("/hi",
  10089. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10090. res.status = StatusCode::OK_200;
  10091. });
  10092. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10093. svr.wait_until_ready();
  10094. Client cli(HOST, PORT);
  10095. auto res = cli.Post("/hi", "data", "text/plain");
  10096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10097. EXPECT_EQ(StatusCode::OK_200, res->status);
  10098. svr.stop();
  10099. thread.join();
  10100. ASSERT_FALSE(svr.is_running());
  10101. res = cli.Post("/hi", "data", "text/plain");
  10102. ASSERT_FALSE(res);
  10103. }
  10104. TEST(ServerStopTest, ListenFailure) {
  10105. Server svr;
  10106. auto t = thread([&]() {
  10107. auto ret = svr.listen("????", PORT);
  10108. EXPECT_FALSE(ret);
  10109. });
  10110. svr.wait_until_ready();
  10111. svr.stop();
  10112. t.join();
  10113. }
  10114. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10115. TEST(ServerStopTest, Decommision) {
  10116. Server svr;
  10117. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10118. for (int i = 0; i < 4; i++) {
  10119. auto is_even = !(i % 2);
  10120. std::thread t{[&] {
  10121. try {
  10122. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10123. if (is_even) {
  10124. throw std::runtime_error("Some thing that happens to go wrong.");
  10125. }
  10126. svr.listen(HOST, PORT);
  10127. } catch (...) { svr.decommission(); }
  10128. }};
  10129. svr.wait_until_ready();
  10130. // Server is up
  10131. {
  10132. Client cli(HOST, PORT);
  10133. auto res = cli.Get("/hi");
  10134. if (is_even) {
  10135. EXPECT_FALSE(res);
  10136. } else {
  10137. EXPECT_TRUE(res);
  10138. EXPECT_EQ("hi...", res->body);
  10139. }
  10140. }
  10141. svr.stop();
  10142. t.join();
  10143. // Server is down...
  10144. {
  10145. Client cli(HOST, PORT);
  10146. auto res = cli.Get("/hi");
  10147. EXPECT_FALSE(res);
  10148. }
  10149. }
  10150. }
  10151. #endif
  10152. // Helper function for string body upload progress tests
  10153. template <typename SetupHandler, typename ClientCall>
  10154. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10155. ClientCall &&client_call,
  10156. const string &body) {
  10157. Server svr;
  10158. setup_handler(svr);
  10159. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10160. auto se = detail::scope_exit([&] {
  10161. svr.stop();
  10162. t.join();
  10163. });
  10164. svr.wait_until_ready();
  10165. Client cli(HOST, PORT);
  10166. vector<uint64_t> progress_values;
  10167. bool progress_called = false;
  10168. auto res =
  10169. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10170. progress_values.push_back(current);
  10171. progress_called = true;
  10172. return true;
  10173. });
  10174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10175. EXPECT_EQ(200, res->status);
  10176. EXPECT_TRUE(progress_called);
  10177. }
  10178. TEST(UploadProgressTest, PostStringBodyBasic) {
  10179. TestStringBodyUploadProgress(
  10180. [](Server &svr) {
  10181. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10182. res.set_content("received", "text/plain");
  10183. });
  10184. },
  10185. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10186. return cli.Post("/test", body, "text/plain", progress_callback);
  10187. },
  10188. "test data for upload progress");
  10189. }
  10190. TEST(UploadProgressTest, PutStringBodyBasic) {
  10191. TestStringBodyUploadProgress(
  10192. [](Server &svr) {
  10193. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10194. res.set_content("put received", "text/plain");
  10195. });
  10196. },
  10197. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10198. return cli.Put("/test", body, "text/plain", progress_callback);
  10199. },
  10200. "put test data for upload progress");
  10201. }
  10202. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10203. TestStringBodyUploadProgress(
  10204. [](Server &svr) {
  10205. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10206. res.set_content("patch received", "text/plain");
  10207. });
  10208. },
  10209. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10210. return cli.Patch("/test", body, "text/plain", progress_callback);
  10211. },
  10212. "patch test data for upload progress");
  10213. }
  10214. // Helper function for content provider upload progress tests
  10215. template <typename SetupHandler, typename ClientCall>
  10216. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10217. ClientCall &&client_call) {
  10218. Server svr;
  10219. setup_handler(svr);
  10220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10221. auto se = detail::scope_exit([&] {
  10222. svr.stop();
  10223. t.join();
  10224. });
  10225. svr.wait_until_ready();
  10226. Client cli(HOST, PORT);
  10227. vector<uint64_t> progress_values;
  10228. auto res =
  10229. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10230. progress_values.push_back(current);
  10231. return true;
  10232. });
  10233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10234. EXPECT_EQ(200, res->status);
  10235. EXPECT_FALSE(progress_values.empty());
  10236. }
  10237. TEST(UploadProgressTest, PostContentProviderProgress) {
  10238. TestContentProviderUploadProgress(
  10239. [](Server &svr) {
  10240. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10241. res.set_content("provider received", "text/plain");
  10242. });
  10243. },
  10244. [](Client &cli, UploadProgress progress_callback) {
  10245. return cli.Post(
  10246. "/test", 9,
  10247. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10248. sink.os << "test data";
  10249. return true;
  10250. },
  10251. "text/plain", progress_callback);
  10252. });
  10253. }
  10254. // Helper function for multipart upload progress tests
  10255. template <typename SetupHandler, typename ClientCall>
  10256. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10257. ClientCall &&client_call,
  10258. const string &endpoint) {
  10259. Server svr;
  10260. setup_handler(svr);
  10261. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10262. auto se = detail::scope_exit([&] {
  10263. svr.stop();
  10264. t.join();
  10265. });
  10266. svr.wait_until_ready();
  10267. Client cli(HOST, PORT);
  10268. vector<uint64_t> progress_values;
  10269. UploadFormDataItems items = {
  10270. {"field1", "value1", "", ""},
  10271. {"field2", "longer value for progress tracking test", "", ""},
  10272. {"file1", "file content data for upload progress", "test.txt",
  10273. "text/plain"}};
  10274. auto res = client_call(cli, endpoint, items,
  10275. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10276. progress_values.push_back(current);
  10277. return true;
  10278. });
  10279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10280. EXPECT_EQ(200, res->status);
  10281. EXPECT_FALSE(progress_values.empty());
  10282. }
  10283. TEST(UploadProgressTest, PostMultipartProgress) {
  10284. TestMultipartUploadProgress(
  10285. [](Server &svr) {
  10286. svr.Post("/multipart", [](const Request &req, Response &res) {
  10287. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10288. res.set_content("multipart received", "text/plain");
  10289. });
  10290. },
  10291. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10292. UploadProgress progress_callback) {
  10293. return cli.Post(endpoint, items, progress_callback);
  10294. },
  10295. "/multipart");
  10296. }
  10297. // Helper function for basic download progress tests
  10298. template <typename SetupHandler, typename ClientCall>
  10299. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10300. ClientCall &&client_call, const string &endpoint,
  10301. size_t expected_content_size) {
  10302. Server svr;
  10303. setup_handler(svr);
  10304. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10305. auto se = detail::scope_exit([&] {
  10306. svr.stop();
  10307. t.join();
  10308. });
  10309. svr.wait_until_ready();
  10310. Client cli(HOST, PORT);
  10311. vector<uint64_t> progress_values;
  10312. auto res = client_call(cli, endpoint,
  10313. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10314. progress_values.push_back(current);
  10315. return true;
  10316. });
  10317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10318. EXPECT_EQ(200, res->status);
  10319. EXPECT_FALSE(progress_values.empty());
  10320. EXPECT_EQ(expected_content_size, res->body.size());
  10321. }
  10322. TEST(DownloadProgressTest, GetBasic) {
  10323. TestBasicDownloadProgress(
  10324. [](Server &svr) {
  10325. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10326. string content(1000, 'D');
  10327. res.set_content(content, "text/plain");
  10328. });
  10329. },
  10330. [](Client &cli, const string &endpoint,
  10331. DownloadProgress progress_callback) {
  10332. return cli.Get(endpoint, progress_callback);
  10333. },
  10334. "/download", 1000u);
  10335. }
  10336. // Helper function for content receiver download progress tests
  10337. template <typename SetupHandler, typename ClientCall>
  10338. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10339. ClientCall &&client_call,
  10340. const string &endpoint,
  10341. size_t expected_content_size) {
  10342. Server svr;
  10343. setup_handler(svr);
  10344. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10345. auto se = detail::scope_exit([&] {
  10346. svr.stop();
  10347. t.join();
  10348. });
  10349. svr.wait_until_ready();
  10350. Client cli(HOST, PORT);
  10351. vector<uint64_t> progress_values;
  10352. string received_body;
  10353. auto res = client_call(
  10354. cli, endpoint,
  10355. [&](const char *data, size_t data_length) -> bool {
  10356. received_body.append(data, data_length);
  10357. return true;
  10358. },
  10359. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10360. progress_values.push_back(current);
  10361. return true;
  10362. });
  10363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10364. EXPECT_EQ(200, res->status);
  10365. EXPECT_FALSE(progress_values.empty());
  10366. EXPECT_EQ(expected_content_size, received_body.size());
  10367. EXPECT_TRUE(res->body.empty());
  10368. }
  10369. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10370. TestContentReceiverDownloadProgress(
  10371. [](Server &svr) {
  10372. svr.Get("/download-receiver",
  10373. [](const Request & /*req*/, Response &res) {
  10374. string content(2000, 'R');
  10375. res.set_content(content, "text/plain");
  10376. });
  10377. },
  10378. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10379. DownloadProgress progress_callback) {
  10380. return cli.Get(endpoint, content_receiver, progress_callback);
  10381. },
  10382. "/download-receiver", 2000u);
  10383. }
  10384. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10385. // A provider reaching a pass with nothing to hand over - an empty buffer
  10386. // popped off a queue, say - must not be taken to mean the body is finished.
  10387. // It used to end the loop with the terminating chunk unwritten while the
  10388. // server still considered the response complete, so the peer waited for an
  10389. // end that never arrived.
  10390. Server svr;
  10391. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10392. auto step = std::make_shared<int>(0);
  10393. res.set_chunked_content_provider("text/plain",
  10394. [step](size_t /*offset*/, DataSink &sink) {
  10395. switch ((*step)++) {
  10396. case 0: sink.write("", 0); break;
  10397. case 1: sink.write("hello", 5); break;
  10398. default: sink.done(); break;
  10399. }
  10400. return true;
  10401. });
  10402. });
  10403. auto port = svr.bind_to_any_port(HOST);
  10404. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10405. auto listen_se = detail::scope_exit([&] {
  10406. svr.stop();
  10407. listen_thread.join();
  10408. ASSERT_FALSE(svr.is_running());
  10409. });
  10410. svr.wait_until_ready();
  10411. Client cli(HOST, port);
  10412. // Without the fix the body is never terminated, so bound the wait rather
  10413. // than letting the test hang on the default read timeout.
  10414. cli.set_read_timeout(5, 0);
  10415. auto res = cli.Get("/stream");
  10416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10417. EXPECT_EQ(StatusCode::OK_200, res->status);
  10418. EXPECT_EQ("hello", res->body);
  10419. }
  10420. TEST(StreamingTest, NoContentLengthStreaming) {
  10421. Server svr;
  10422. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10423. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10424. if (offset < 6) {
  10425. sink.os << (offset < 3 ? "a" : "b");
  10426. } else {
  10427. sink.done();
  10428. }
  10429. return true;
  10430. });
  10431. });
  10432. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10433. auto listen_se = detail::scope_exit([&] {
  10434. svr.stop();
  10435. listen_thread.join();
  10436. ASSERT_FALSE(svr.is_running());
  10437. });
  10438. svr.wait_until_ready();
  10439. Client client(HOST, PORT);
  10440. auto get_thread = std::thread([&client]() {
  10441. std::string s;
  10442. auto res =
  10443. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10444. s += std::string(data, len);
  10445. return true;
  10446. });
  10447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10448. EXPECT_EQ(StatusCode::OK_200, res->status);
  10449. EXPECT_EQ("aaabbb", s);
  10450. });
  10451. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10452. // Give GET time to get a few messages.
  10453. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10454. }
  10455. TEST(MountTest, Unmount) {
  10456. Server svr;
  10457. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10458. auto se = detail::scope_exit([&] {
  10459. svr.stop();
  10460. listen_thread.join();
  10461. ASSERT_FALSE(svr.is_running());
  10462. });
  10463. svr.wait_until_ready();
  10464. Client cli("localhost", PORT);
  10465. svr.set_mount_point("/mount2", "./www2");
  10466. auto res = cli.Get("/");
  10467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10469. res = cli.Get("/mount2/dir/test.html");
  10470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10471. EXPECT_EQ(StatusCode::OK_200, res->status);
  10472. svr.set_mount_point("/", "./www");
  10473. res = cli.Get("/dir/");
  10474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10475. EXPECT_EQ(StatusCode::OK_200, res->status);
  10476. svr.remove_mount_point("/");
  10477. res = cli.Get("/dir/");
  10478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10480. svr.remove_mount_point("/mount2");
  10481. res = cli.Get("/mount2/dir/test.html");
  10482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10483. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10484. }
  10485. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10486. Server svr;
  10487. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10488. svr.Get("/api/hello", [](const Request &, Response &res) {
  10489. res.set_content("api", "text/plain");
  10490. });
  10491. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10492. auto se = detail::scope_exit([&] {
  10493. svr.stop();
  10494. listen_thread.join();
  10495. ASSERT_FALSE(svr.is_running());
  10496. });
  10497. svr.wait_until_ready();
  10498. Client cli(HOST, PORT);
  10499. auto res = cli.Get("/dir/test.html");
  10500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10501. EXPECT_EQ(StatusCode::OK_200, res->status);
  10502. res = cli.Get("/api/hello");
  10503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10504. EXPECT_EQ(StatusCode::OK_200, res->status);
  10505. EXPECT_EQ("api", res->body);
  10506. }
  10507. TEST(MountTest, PathSegmentBoundary) {
  10508. Server svr;
  10509. svr.set_mount_point("/mount2", "./www2");
  10510. svr.set_mount_point("/", "./www");
  10511. auto port = svr.bind_to_any_port(HOST);
  10512. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10513. auto se = detail::scope_exit([&] {
  10514. svr.stop();
  10515. listen_thread.join();
  10516. ASSERT_FALSE(svr.is_running());
  10517. });
  10518. svr.wait_until_ready();
  10519. Client cli(HOST, port);
  10520. auto res = cli.Get("/mount2/dir/test.html");
  10521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10522. EXPECT_EQ(StatusCode::OK_200, res->status);
  10523. // "/mount2" must not match part-way through a path segment.
  10524. res = cli.Get("/mount2dir/test.html");
  10525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10527. // A mount point ending in '/' keeps matching every path below it.
  10528. res = cli.Get("/dir/test.html");
  10529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10530. EXPECT_EQ(StatusCode::OK_200, res->status);
  10531. }
  10532. TEST(MountTest, Redicect) {
  10533. Server svr;
  10534. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10535. auto se = detail::scope_exit([&] {
  10536. svr.stop();
  10537. listen_thread.join();
  10538. ASSERT_FALSE(svr.is_running());
  10539. });
  10540. svr.set_mount_point("/", "./www");
  10541. svr.wait_until_ready();
  10542. Client cli("localhost", PORT);
  10543. auto res = cli.Get("/dir/");
  10544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10545. EXPECT_EQ(StatusCode::OK_200, res->status);
  10546. res = cli.Get("/dir");
  10547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10548. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10549. res = cli.Get("/file");
  10550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10551. EXPECT_EQ(StatusCode::OK_200, res->status);
  10552. res = cli.Get("/file/");
  10553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10554. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10555. cli.set_follow_location(true);
  10556. res = cli.Get("/dir");
  10557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10558. EXPECT_EQ(StatusCode::OK_200, res->status);
  10559. }
  10560. TEST(MountTest, MultibytesPathName) {
  10561. Server svr;
  10562. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10563. auto se = detail::scope_exit([&] {
  10564. svr.stop();
  10565. listen_thread.join();
  10566. ASSERT_FALSE(svr.is_running());
  10567. });
  10568. svr.set_mount_point("/", "./www");
  10569. svr.wait_until_ready();
  10570. Client cli("localhost", PORT);
  10571. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10573. EXPECT_EQ(StatusCode::OK_200, res->status);
  10574. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10575. }
  10576. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10577. // in the pre-routing handler sees the path of every file that is served
  10578. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10579. Server svr;
  10580. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10581. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10582. if (req.path == "/dir/test.html") {
  10583. res.status = StatusCode::Unauthorized_401;
  10584. return Server::HandlerResponse::Handled;
  10585. }
  10586. return Server::HandlerResponse::Unhandled;
  10587. });
  10588. auto port = svr.bind_to_any_port(HOST);
  10589. ASSERT_LT(0, port);
  10590. thread t = thread([&] { svr.listen_after_bind(); });
  10591. auto se = detail::scope_exit([&] {
  10592. svr.stop();
  10593. t.join();
  10594. ASSERT_FALSE(svr.is_running());
  10595. });
  10596. svr.wait_until_ready();
  10597. Client cli(HOST, port);
  10598. for (auto path :
  10599. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10600. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10601. SCOPED_TRACE(path);
  10602. auto res = cli.Get(path);
  10603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10604. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10605. }
  10606. }
  10607. #ifdef _WIN32
  10608. // Issue #2435: mmap::open() must succeed even when another handle holds
  10609. // the file open for writing (e.g. an active log file).
  10610. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10611. const char *path = "mmap_concurrent_writer_test.txt";
  10612. const char *content = "hello";
  10613. {
  10614. std::ofstream f(path, std::ios::binary);
  10615. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10616. }
  10617. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10618. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10619. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10620. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10621. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10622. detail::mmap m(path);
  10623. ASSERT_TRUE(m.is_open());
  10624. EXPECT_EQ(strlen(content), m.size());
  10625. char buf[8];
  10626. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10627. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10628. }
  10629. #endif
  10630. #ifndef _WIN32
  10631. // A directory or a device has no size to serve.
  10632. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10633. const char *path = "./mmap_not_regular_test_dir";
  10634. ASSERT_EQ(0, ::mkdir(path, 0755));
  10635. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10636. for (auto p : {path, "/dev/null"}) {
  10637. detail::mmap m(p);
  10638. EXPECT_FALSE(m.is_open()) << p;
  10639. EXPECT_EQ(0U, m.size()) << p;
  10640. }
  10641. Server svr;
  10642. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10643. res.set_file_content("/dev/null");
  10644. });
  10645. auto port = svr.bind_to_any_port(HOST);
  10646. thread t = thread([&] { svr.listen_after_bind(); });
  10647. auto se = detail::scope_exit([&] {
  10648. svr.stop();
  10649. t.join();
  10650. });
  10651. svr.wait_until_ready();
  10652. auto res = Client(HOST, port).Get("/null");
  10653. ASSERT_TRUE(res);
  10654. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10655. }
  10656. #endif
  10657. #ifdef __linux__
  10658. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10659. TEST(MmapTest, FileIsNotMapped) {
  10660. const char *path = "mmap_not_mapped_test.txt";
  10661. {
  10662. std::ofstream f(path, std::ios::binary);
  10663. f << "hello";
  10664. }
  10665. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10666. detail::mmap m(path);
  10667. ASSERT_TRUE(m.is_open());
  10668. std::ifstream maps("/proc/self/maps");
  10669. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10670. std::istreambuf_iterator<char>());
  10671. EXPECT_EQ(std::string::npos, mappings.find(path));
  10672. }
  10673. #endif
  10674. TEST(KeepAliveTest, ReadTimeout) {
  10675. Server svr;
  10676. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10677. std::this_thread::sleep_for(std::chrono::seconds(2));
  10678. res.set_content("a", "text/plain");
  10679. });
  10680. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10681. res.set_content("b", "text/plain");
  10682. });
  10683. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10684. auto se = detail::scope_exit([&] {
  10685. svr.stop();
  10686. listen_thread.join();
  10687. ASSERT_FALSE(svr.is_running());
  10688. });
  10689. svr.wait_until_ready();
  10690. Client cli("localhost", PORT);
  10691. cli.set_keep_alive(true);
  10692. cli.set_read_timeout(std::chrono::seconds(1));
  10693. auto resa = cli.Get("/a");
  10694. ASSERT_FALSE(resa);
  10695. EXPECT_EQ(Error::Read, resa.error());
  10696. auto resb = cli.Get("/b");
  10697. ASSERT_TRUE(resb);
  10698. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10699. EXPECT_EQ("b", resb->body);
  10700. }
  10701. TEST(KeepAliveTest, MaxCount) {
  10702. size_t keep_alive_max_count = 3;
  10703. Server svr;
  10704. svr.set_keep_alive_max_count(keep_alive_max_count);
  10705. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10706. res.set_content("Hello World!", "text/plain");
  10707. });
  10708. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10709. auto se = detail::scope_exit([&] {
  10710. svr.stop();
  10711. listen_thread.join();
  10712. ASSERT_FALSE(svr.is_running());
  10713. });
  10714. svr.wait_until_ready();
  10715. Client cli(HOST, PORT);
  10716. cli.set_keep_alive(true);
  10717. for (size_t i = 0; i < 5; i++) {
  10718. auto result = cli.Get("/hi");
  10719. ASSERT_TRUE(result);
  10720. EXPECT_EQ(StatusCode::OK_200, result->status);
  10721. if (i == keep_alive_max_count - 1) {
  10722. EXPECT_EQ("close", result->get_header_value("Connection"));
  10723. } else {
  10724. EXPECT_FALSE(result->has_header("Connection"));
  10725. }
  10726. }
  10727. }
  10728. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10729. // can pull the next one into the server's buffer. The server must serve it
  10730. // without waiting for the socket to become readable again. The keep-alive
  10731. // timeout outlasts the client's read timeout, so a request left waiting for it
  10732. // shows up as a missing response.
  10733. static void serve_pipelining_routes(Server &svr,
  10734. const std::function<void(int)> &client) {
  10735. svr.set_keep_alive_timeout(5);
  10736. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10737. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10738. });
  10739. svr.Post("/echo", [](const Request &req, Response &res) {
  10740. res.set_content("echo " + req.body, "text/plain");
  10741. });
  10742. auto port = svr.bind_to_any_port(HOST);
  10743. thread t = thread([&] { svr.listen_after_bind(); });
  10744. auto se = detail::scope_exit([&] {
  10745. svr.stop();
  10746. t.join();
  10747. });
  10748. svr.wait_until_ready();
  10749. client(port);
  10750. }
  10751. static std::string
  10752. send_pipelined_requests(const std::vector<std::string> &parts) {
  10753. Server svr;
  10754. std::string res;
  10755. serve_pipelining_routes(svr, [&](int port) {
  10756. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10757. });
  10758. return res;
  10759. }
  10760. static void expect_in_order(const std::string &res,
  10761. const std::vector<std::string> &bodies) {
  10762. size_t pos = 0;
  10763. for (const auto &body : bodies) {
  10764. pos = res.find(body, pos);
  10765. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10766. pos += body.size();
  10767. }
  10768. }
  10769. TEST(KeepAliveTest, PipelinedRequests) {
  10770. auto res = send_pipelined_requests(
  10771. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10772. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10773. "Content-Length: 4\r\n\r\nbody"
  10774. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10775. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10776. }
  10777. // The second request starts in the server's buffer and ends on the socket.
  10778. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10779. auto res =
  10780. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10781. "GET /hi/2 HTTP/1.1\r\nHo",
  10782. "st: localhost\r\nConnection: close\r\n\r\n"});
  10783. expect_in_order(res, {"hi 1", "hi 2"});
  10784. }
  10785. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10786. // CRLF after a body does not turn into a 400 for the next request.
  10787. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10788. auto res = send_pipelined_requests(
  10789. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10790. "Content-Length: 4\r\n\r\nbody\r\n"
  10791. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10792. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10793. expect_in_order(res, {"echo body", "hi 2"});
  10794. }
  10795. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10796. // must not be served as the next request.
  10797. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10798. auto res = send_pipelined_requests(
  10799. {"INVALID REQUEST LINE\r\n\r\n"
  10800. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10801. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10802. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10803. }
  10804. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10805. // Over TLS, the next request is held by the TLS library as already decrypted
  10806. // data rather than on the socket.
  10807. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10808. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10809. std::string res;
  10810. serve_pipelining_routes(svr, [&](int port) {
  10811. // One part, so all three requests arrive in one TLS record
  10812. EXPECT_TRUE(send_ssl_request_in_parts(
  10813. 2,
  10814. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10815. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10816. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10817. &res, port));
  10818. });
  10819. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10820. }
  10821. #endif
  10822. TEST(KeepAliveTest, Issue1041) {
  10823. Server svr;
  10824. svr.set_keep_alive_timeout(3);
  10825. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10826. res.set_content("Hello World!", "text/plain");
  10827. });
  10828. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10829. auto se = detail::scope_exit([&] {
  10830. svr.stop();
  10831. listen_thread.join();
  10832. ASSERT_FALSE(svr.is_running());
  10833. });
  10834. svr.wait_until_ready();
  10835. Client cli(HOST, PORT);
  10836. cli.set_keep_alive(true);
  10837. auto result = cli.Get("/hi");
  10838. ASSERT_TRUE(result);
  10839. EXPECT_EQ(StatusCode::OK_200, result->status);
  10840. std::this_thread::sleep_for(std::chrono::seconds(5));
  10841. result = cli.Get("/hi");
  10842. ASSERT_TRUE(result);
  10843. EXPECT_EQ(StatusCode::OK_200, result->status);
  10844. }
  10845. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10846. Server svr;
  10847. svr.set_keep_alive_max_count(0);
  10848. std::set<int> remote_ports;
  10849. svr.Get("/hi", [&](const Request &req, Response &res) {
  10850. remote_ports.insert(req.remote_port);
  10851. res.set_content("hi", "text/plain");
  10852. });
  10853. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10854. auto se = detail::scope_exit([&] {
  10855. svr.stop();
  10856. listen_thread.join();
  10857. ASSERT_FALSE(svr.is_running());
  10858. });
  10859. svr.wait_until_ready();
  10860. Client cli(HOST, PORT);
  10861. cli.set_keep_alive(true);
  10862. for (int i = 0; i < 3; i++) {
  10863. auto res = cli.Get("/hi");
  10864. ASSERT_TRUE(res);
  10865. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10866. }
  10867. // All three over one connection
  10868. EXPECT_EQ(1u, remote_ports.size());
  10869. }
  10870. TEST(KeepAliveTest, Issue1959) {
  10871. Server svr;
  10872. svr.set_keep_alive_timeout(5);
  10873. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10874. res.set_content("a", "text/plain");
  10875. });
  10876. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10877. auto se = detail::scope_exit([&] {
  10878. if (!svr.is_running()) return;
  10879. svr.stop();
  10880. listen_thread.join();
  10881. ASSERT_FALSE(svr.is_running());
  10882. });
  10883. svr.wait_until_ready();
  10884. Client cli("localhost", PORT);
  10885. cli.set_keep_alive(true);
  10886. using namespace std::chrono;
  10887. auto start = steady_clock::now();
  10888. cli.Get("/a");
  10889. svr.stop();
  10890. listen_thread.join();
  10891. auto end = steady_clock::now();
  10892. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10893. EXPECT_LT(elapsed, 5000);
  10894. }
  10895. #ifdef CPPHTTPLIB_SSL_ENABLED
  10896. TEST(KeepAliveTest, SSLClientReconnection) {
  10897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10898. ASSERT_TRUE(svr.is_valid());
  10899. svr.set_keep_alive_timeout(1);
  10900. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10901. res.set_content("Hello World!", "text/plain");
  10902. });
  10903. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10904. auto se = detail::scope_exit([&] {
  10905. svr.stop();
  10906. listen_thread.join();
  10907. ASSERT_FALSE(svr.is_running());
  10908. });
  10909. svr.wait_until_ready();
  10910. SSLClient cli(HOST, PORT);
  10911. cli.enable_server_certificate_verification(false);
  10912. cli.set_keep_alive(true);
  10913. auto result = cli.Get("/hi");
  10914. ASSERT_TRUE(result);
  10915. EXPECT_EQ(StatusCode::OK_200, result->status);
  10916. result = cli.Get("/hi");
  10917. ASSERT_TRUE(result);
  10918. EXPECT_EQ(StatusCode::OK_200, result->status);
  10919. std::this_thread::sleep_for(std::chrono::seconds(2));
  10920. // Recoonect
  10921. result = cli.Get("/hi");
  10922. ASSERT_TRUE(result);
  10923. EXPECT_EQ(StatusCode::OK_200, result->status);
  10924. result = cli.Get("/hi");
  10925. ASSERT_TRUE(result);
  10926. EXPECT_EQ(StatusCode::OK_200, result->status);
  10927. }
  10928. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10930. ASSERT_TRUE(svr.is_valid());
  10931. svr.set_keep_alive_timeout(1);
  10932. std::string content = "reconnect";
  10933. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10934. res.set_content("Hello World!", "text/plain");
  10935. });
  10936. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10937. auto se = detail::scope_exit([&] {
  10938. svr.stop();
  10939. listen_thread.join();
  10940. ASSERT_FALSE(svr.is_running());
  10941. });
  10942. svr.wait_until_ready();
  10943. SSLClient cli(HOST, PORT);
  10944. cli.enable_server_certificate_verification(false);
  10945. cli.set_keep_alive(true);
  10946. auto result = cli.Post(
  10947. "/hi", content.size(),
  10948. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10949. sink.write(content.c_str(), content.size());
  10950. return true;
  10951. },
  10952. "text/plain");
  10953. ASSERT_TRUE(result);
  10954. EXPECT_EQ(200, result->status);
  10955. std::this_thread::sleep_for(std::chrono::seconds(2));
  10956. // Recoonect
  10957. result = cli.Post(
  10958. "/hi", content.size(),
  10959. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10960. sink.write(content.c_str(), content.size());
  10961. return true;
  10962. },
  10963. "text/plain");
  10964. ASSERT_TRUE(result);
  10965. EXPECT_EQ(200, result->status);
  10966. result = cli.Post(
  10967. "/hi", content.size(),
  10968. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10969. sink.write(content.c_str(), content.size());
  10970. return true;
  10971. },
  10972. "text/plain");
  10973. ASSERT_TRUE(result);
  10974. EXPECT_EQ(200, result->status);
  10975. }
  10976. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10977. using namespace httplib::tls;
  10978. {
  10979. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10980. ASSERT_TRUE(svr.is_valid());
  10981. svr.Get("/sni", [&](const Request &req, Response &res) {
  10982. std::string expected = req.sni();
  10983. EXPECT_EQ(expected, req.get_param_value("expected"));
  10984. res.set_content("ok", "text/plain");
  10985. });
  10986. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10987. auto se = detail::scope_exit([&] {
  10988. svr.stop();
  10989. listen_thread.join();
  10990. ASSERT_FALSE(svr.is_running());
  10991. });
  10992. svr.wait_until_ready();
  10993. {
  10994. SSLClient cli("localhost", PORT);
  10995. cli.enable_server_certificate_verification(false);
  10996. auto res = cli.Get("/sni?expected=localhost");
  10997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10998. }
  10999. {
  11000. SSLClient cli("::1", PORT);
  11001. cli.enable_server_certificate_verification(false);
  11002. auto res = cli.Get("/sni?expected=");
  11003. // NOTE: This may fail if the server is listening on IPv4 only
  11004. // (e.g., when localhost resolves to 127.0.0.1 only)
  11005. if (res) {
  11006. EXPECT_EQ(StatusCode::OK_200, res->status);
  11007. } else {
  11008. EXPECT_EQ(Error::Connection, res.error());
  11009. }
  11010. }
  11011. }
  11012. }
  11013. // The SNI of a failed handshake does not reach the next connection that the
  11014. // same worker thread serves
  11015. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11016. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11017. ASSERT_TRUE(svr.is_valid());
  11018. svr.new_task_queue = [] { return new ThreadPool(1); };
  11019. svr.Get("/sni", [](const Request &req, Response &res) {
  11020. res.set_content(req.sni(), "text/plain");
  11021. });
  11022. auto port = svr.bind_to_any_port("127.0.0.1");
  11023. ASSERT_LT(0, port);
  11024. thread t = thread([&] { svr.listen_after_bind(); });
  11025. auto se = detail::scope_exit([&] {
  11026. svr.stop();
  11027. t.join();
  11028. ASSERT_FALSE(svr.is_running());
  11029. });
  11030. svr.wait_until_ready();
  11031. {
  11032. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11033. SSLClient cli("localhost", port);
  11034. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11035. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11036. auto res = cli.Get("/sni");
  11037. ASSERT_FALSE(res);
  11038. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11039. }
  11040. // An IP host sends no SNI (RFC 6066)
  11041. SSLClient cli("127.0.0.1", port);
  11042. cli.enable_server_certificate_verification(false);
  11043. auto res = cli.Get("/sni");
  11044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11045. EXPECT_EQ("", res->body);
  11046. }
  11047. #endif
  11048. TEST(ClientProblemDetectionTest, ContentProvider) {
  11049. Server svr;
  11050. size_t content_length = 1024 * 1024;
  11051. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11052. res.set_content_provider(
  11053. content_length, "text/plain",
  11054. [&](size_t offset, size_t length, DataSink &sink) {
  11055. auto out_len = std::min(length, static_cast<size_t>(1024));
  11056. std::string out(out_len, '@');
  11057. sink.write(out.data(), out_len);
  11058. return offset < 4096;
  11059. },
  11060. [](bool success) { ASSERT_FALSE(success); });
  11061. });
  11062. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11063. res.set_content_provider(
  11064. 0, "text/plain",
  11065. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11066. EXPECT_TRUE(false);
  11067. return true;
  11068. },
  11069. [](bool success) { ASSERT_FALSE(success); });
  11070. });
  11071. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11072. auto se = detail::scope_exit([&] {
  11073. svr.stop();
  11074. listen_thread.join();
  11075. ASSERT_FALSE(svr.is_running());
  11076. });
  11077. svr.wait_until_ready();
  11078. Client cli("localhost", PORT);
  11079. {
  11080. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11081. size_t /*data_length*/) { return false; });
  11082. ASSERT_FALSE(res);
  11083. }
  11084. {
  11085. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11086. size_t /*data_length*/) { return false; });
  11087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11088. }
  11089. }
  11090. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11091. // A provider that reports success without writing anything and without
  11092. // calling done() used to be handed the same offset and length again on every
  11093. // pass, so it spun for as long as the peer stayed connected.
  11094. Server svr;
  11095. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11096. res.set_content("ok", "text/plain");
  11097. });
  11098. auto port = svr.bind_to_any_port(HOST);
  11099. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11100. auto se = detail::scope_exit([&] {
  11101. svr.stop();
  11102. listen_thread.join();
  11103. ASSERT_FALSE(svr.is_running());
  11104. });
  11105. svr.wait_until_ready();
  11106. std::atomic<int> call_count{0};
  11107. Client cli(HOST, port);
  11108. auto res = cli.Post(
  11109. "/", 1024,
  11110. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11111. // Give up after enough passes to show the spin, so that losing the
  11112. // check below fails this test instead of hanging it.
  11113. return ++call_count < 100;
  11114. },
  11115. "text/plain");
  11116. ASSERT_FALSE(res);
  11117. EXPECT_EQ(Error::Write, res.error());
  11118. EXPECT_EQ(1, call_count.load());
  11119. }
  11120. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11121. // A writer only has to assign `write`. The other three used to be left as
  11122. // empty std::functions, so a provider calling one threw
  11123. // std::bad_function_call out of the thread running it and took the whole
  11124. // process down.
  11125. DataSink sink;
  11126. std::string written;
  11127. sink.write = [&](const char *data, size_t data_len) {
  11128. written.append(data, data_len);
  11129. return true;
  11130. };
  11131. EXPECT_TRUE(sink.is_writable());
  11132. sink.done();
  11133. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11134. EXPECT_TRUE(written.empty());
  11135. }
  11136. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11137. // A sink that cannot carry trailers still has to finish.
  11138. DataSink sink;
  11139. auto done_count = 0;
  11140. sink.done = [&]() { done_count++; };
  11141. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11142. EXPECT_EQ(1, done_count);
  11143. }
  11144. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11145. Server svr;
  11146. const std::string body(4096, 'x');
  11147. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11148. res.set_content_provider(body.size(), "text/plain",
  11149. [&](size_t offset, size_t length, DataSink &sink) {
  11150. sink.write(body.data() + offset, length);
  11151. sink.done();
  11152. return true;
  11153. });
  11154. });
  11155. auto port = svr.bind_to_any_port(HOST);
  11156. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11157. auto se = detail::scope_exit([&] {
  11158. svr.stop();
  11159. listen_thread.join();
  11160. ASSERT_FALSE(svr.is_running());
  11161. });
  11162. svr.wait_until_ready();
  11163. Client cli(HOST, port);
  11164. auto res = cli.Get("/");
  11165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11166. EXPECT_EQ(StatusCode::OK_200, res->status);
  11167. EXPECT_EQ(body, res->body);
  11168. }
  11169. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11170. Server svr;
  11171. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11172. res.set_content_provider(
  11173. 1024, "text/plain",
  11174. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11175. sink.write("hello", 5);
  11176. sink.done(); // short of the 1024 bytes the response promised
  11177. return true;
  11178. });
  11179. });
  11180. auto port = svr.bind_to_any_port(HOST);
  11181. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11182. auto se = detail::scope_exit([&] {
  11183. svr.stop();
  11184. listen_thread.join();
  11185. ASSERT_FALSE(svr.is_running());
  11186. });
  11187. svr.wait_until_ready();
  11188. Client cli(HOST, port);
  11189. cli.set_read_timeout(5, 0);
  11190. // The response is short of its Content-Length, so the client cannot read a
  11191. // complete body. What matters is that this returns at all: a no-op done()
  11192. // would leave the writer looping over a provider that never makes progress.
  11193. auto res = cli.Get("/");
  11194. EXPECT_FALSE(res);
  11195. }
  11196. // Read as the next response by a peer that sees it after a framed body.
  11197. static const std::string smuggled_response =
  11198. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11199. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11200. Server svr;
  11201. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11202. res.set_content_provider(
  11203. 5, "text/plain",
  11204. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11205. auto data = "AAAAA" + smuggled_response;
  11206. sink.write(data.data(), data.size());
  11207. return true;
  11208. });
  11209. });
  11210. thread t = thread([&] { svr.listen(HOST, PORT); });
  11211. auto se = detail::scope_exit([&] {
  11212. svr.stop();
  11213. t.join();
  11214. ASSERT_FALSE(svr.is_running());
  11215. });
  11216. svr.wait_until_ready();
  11217. std::string resp;
  11218. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11219. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11220. resp.clear();
  11221. ASSERT_TRUE(send_request(
  11222. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11223. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11224. }
  11225. TEST(NoContentTest, BodyIsNotSent) {
  11226. Server svr;
  11227. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11228. res.status = StatusCode::NoContent_204;
  11229. res.set_content(smuggled_response, "text/plain");
  11230. });
  11231. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11232. res.status = StatusCode::NotModified_304;
  11233. res.set_chunked_content_provider(
  11234. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11235. sink.write(smuggled_response.data(), smuggled_response.size());
  11236. sink.done();
  11237. return true;
  11238. });
  11239. });
  11240. thread t = thread([&] { svr.listen(HOST, PORT); });
  11241. auto se = detail::scope_exit([&] {
  11242. svr.stop();
  11243. t.join();
  11244. ASSERT_FALSE(svr.is_running());
  11245. });
  11246. svr.wait_until_ready();
  11247. for (auto path : {"/204", "/304"}) {
  11248. std::string resp;
  11249. ASSERT_TRUE(send_request(
  11250. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11251. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11252. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11253. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11254. }
  11255. }
  11256. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11257. Server svr;
  11258. std::atomic<bool> smuggled(false);
  11259. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11260. res.set_content("ok", "text/plain");
  11261. });
  11262. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11263. smuggled = true;
  11264. });
  11265. auto port = svr.bind_to_any_port(HOST);
  11266. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11267. auto se = detail::scope_exit([&] {
  11268. svr.stop();
  11269. listen_thread.join();
  11270. ASSERT_FALSE(svr.is_running());
  11271. });
  11272. svr.wait_until_ready();
  11273. // What follows the body would be read as the next request.
  11274. Client cli(HOST, port);
  11275. auto res = cli.Post(
  11276. "/", 5,
  11277. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11278. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11279. sink.write(data.data(), data.size());
  11280. return true;
  11281. },
  11282. "text/plain");
  11283. ASSERT_FALSE(res);
  11284. EXPECT_EQ(Error::Write, res.error());
  11285. EXPECT_FALSE(smuggled);
  11286. }
  11287. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11288. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11289. // The compressed path builds the whole body before connecting, so this
  11290. // fails client-side and never reaches a server.
  11291. Client cli(HOST, PORT);
  11292. cli.set_compress(true);
  11293. auto res = cli.Post(
  11294. "/", 1024,
  11295. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11296. sink.write("hello", 5);
  11297. sink.done(); // short of the 1024 bytes the request announced
  11298. return true;
  11299. },
  11300. "text/plain");
  11301. ASSERT_FALSE(res);
  11302. EXPECT_EQ(Error::Write, res.error());
  11303. }
  11304. #endif
  11305. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11306. Server svr;
  11307. svr.set_error_handler([](Request const &, Response &res) -> void {
  11308. res.set_chunked_content_provider(
  11309. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11310. sink.os << "hello";
  11311. sink.os << "world";
  11312. sink.done();
  11313. return true;
  11314. });
  11315. });
  11316. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11317. auto se = detail::scope_exit([&] {
  11318. svr.stop();
  11319. listen_thread.join();
  11320. ASSERT_FALSE(svr.is_running());
  11321. });
  11322. svr.wait_until_ready();
  11323. Client cli("localhost", PORT);
  11324. auto res = cli.Get("/");
  11325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11326. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11327. EXPECT_EQ("helloworld", res->body);
  11328. }
  11329. // A body set after a content provider must replace it, not be sent through it.
  11330. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11331. Server svr;
  11332. svr.set_mount_point("/", "./www");
  11333. svr.set_file_request_handler([](const Request &req, Response &res) {
  11334. if (req.path == "/dir/test.html") {
  11335. res.status = StatusCode::Forbidden_403;
  11336. res.set_content(std::string(5000, 'D'), "text/plain");
  11337. } else if (req.path == "/file") {
  11338. res.status = StatusCode::Forbidden_403;
  11339. res.body = "Denied";
  11340. }
  11341. });
  11342. auto port = svr.bind_to_any_port(HOST);
  11343. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11344. auto se = detail::scope_exit([&] {
  11345. svr.stop();
  11346. t.join();
  11347. ASSERT_FALSE(svr.is_running());
  11348. });
  11349. svr.wait_until_ready();
  11350. Client cli(HOST, port);
  11351. {
  11352. auto res = cli.Get("/dir/test.html");
  11353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11354. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11355. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11356. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11357. }
  11358. {
  11359. auto res = cli.Get("/file");
  11360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11361. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11362. EXPECT_EQ("Denied", res->body);
  11363. }
  11364. {
  11365. auto res = cli.Get("/dir/index.html");
  11366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11367. EXPECT_EQ(StatusCode::OK_200, res->status);
  11368. EXPECT_EQ(0U, res->body.find("<html>"));
  11369. }
  11370. }
  11371. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11372. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11373. Server svr;
  11374. std::vector<bool> released;
  11375. std::mutex released_mutex;
  11376. auto releaser = [&](bool success) {
  11377. std::lock_guard<std::mutex> guard(released_mutex);
  11378. released.push_back(success);
  11379. };
  11380. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11381. return sink.write(&"hello"[offset], length);
  11382. };
  11383. svr.Get("/sized", [&](const Request &, Response &res) {
  11384. res.status = StatusCode::NotFound_404;
  11385. res.set_content_provider(5, "text/plain", provider, releaser);
  11386. });
  11387. svr.Get("/chunked", [&](const Request &, Response &res) {
  11388. res.status = StatusCode::ServiceUnavailable_503;
  11389. res.set_chunked_content_provider(
  11390. "text/plain",
  11391. [](size_t, DataSink &sink) {
  11392. sink.os << "chunk";
  11393. sink.done();
  11394. return true;
  11395. },
  11396. releaser);
  11397. });
  11398. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11399. res.set_content_provider(5, "text/plain", provider, releaser);
  11400. throw std::runtime_error("after the provider");
  11401. });
  11402. svr.set_error_handler([](const Request &req, Response &res) {
  11403. // Leave the exception handler's content to it.
  11404. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11405. res.set_content(std::string(1000, 'E'), "text/html");
  11406. return Server::HandlerResponse::Handled;
  11407. });
  11408. svr.set_exception_handler(
  11409. [](const Request &, Response &res, std::exception_ptr) {
  11410. res.status = StatusCode::InternalServerError_500;
  11411. res.set_content(std::string(1000, 'X'), "text/html");
  11412. });
  11413. auto port = svr.bind_to_any_port(HOST);
  11414. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11415. auto se = detail::scope_exit([&] {
  11416. svr.stop();
  11417. t.join();
  11418. ASSERT_FALSE(svr.is_running());
  11419. });
  11420. svr.wait_until_ready();
  11421. Client cli(HOST, port);
  11422. {
  11423. auto res = cli.Get("/sized");
  11424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11425. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11426. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11427. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11428. }
  11429. {
  11430. auto res = cli.Get("/chunked");
  11431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11432. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11433. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11434. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11435. }
  11436. {
  11437. auto res = cli.Get("/throw");
  11438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11439. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11440. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11441. }
  11442. std::lock_guard<std::mutex> guard(released_mutex);
  11443. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11444. }
  11445. #endif
  11446. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11447. Server svr;
  11448. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11449. return sink.write(&"abc"[offset], length);
  11450. };
  11451. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11452. res.set_file_content("./www/dir/test.html");
  11453. res.set_content("body", "text/plain");
  11454. });
  11455. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11456. res.set_content(std::string(100, 'B'), "text/plain");
  11457. res.set_file_content("./www/dir/test.html");
  11458. });
  11459. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11460. res.set_content(std::string(100, 'B'), "text/plain");
  11461. res.set_content_provider(3, "text/x-provider", abc);
  11462. });
  11463. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11464. res.set_content_provider(3, "text/x-provider", abc);
  11465. res.set_content(std::string(100, 'B'), "text/plain");
  11466. });
  11467. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11468. res.set_content_provider(3, "text/x-provider", abc);
  11469. res.set_file_content("./www/dir/test.html", "text/x-file");
  11470. });
  11471. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11472. res.set_file_content("./www/dir/test.html");
  11473. res.set_header("Content-Type", "text/x-handler");
  11474. });
  11475. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11476. res.set_content_provider(3, "text/plain", abc);
  11477. res.body = "direct";
  11478. });
  11479. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11480. res.set_file_content("./www/dir/test.html");
  11481. res.body = "direct";
  11482. });
  11483. auto port = svr.bind_to_any_port(HOST);
  11484. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11485. auto se = detail::scope_exit([&] {
  11486. svr.stop();
  11487. t.join();
  11488. ASSERT_FALSE(svr.is_running());
  11489. });
  11490. svr.wait_until_ready();
  11491. Client cli(HOST, port);
  11492. auto expect_body = [&](const char *path, const std::string &body,
  11493. const std::string &type) {
  11494. // Uncompressed, so Content-Length can be compared with the body.
  11495. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11496. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11497. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11498. EXPECT_EQ(body, res->body) << path;
  11499. EXPECT_EQ(std::to_string(body.size()),
  11500. res->get_header_value("Content-Length"))
  11501. << path;
  11502. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11503. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11504. };
  11505. expect_body("/file-then-body", "body", "text/plain");
  11506. expect_body("/body-then-file", "test.html", "text/html");
  11507. expect_body("/body-then-provider", "abc", "text/x-provider");
  11508. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11509. expect_body("/provider-then-file", "test.html", "text/x-file");
  11510. expect_body("/file-then-header", "test.html", "text/x-handler");
  11511. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11512. expect_body("/file-then-direct-body", "direct", "text/plain");
  11513. // Ranges are checked against the body, not the dropped provider.
  11514. {
  11515. auto res = cli.Get("/provider-then-direct-body",
  11516. Headers{{make_range_header({{1, 2}})}});
  11517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11519. EXPECT_EQ("ir", res->body);
  11520. }
  11521. {
  11522. auto res = cli.Get("/file-then-direct-body",
  11523. Headers{{make_range_header({{7, 8}})}});
  11524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11525. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11526. }
  11527. }
  11528. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11529. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11530. const char *path = "./truncated_while_served.txt";
  11531. const size_t size = 32 * 1024 * 1024;
  11532. {
  11533. std::ofstream f(path, std::ios::binary);
  11534. f << std::string(size, 'x');
  11535. }
  11536. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11537. // Over TLS, where the bytes are encrypted in this process rather than
  11538. // copied by send().
  11539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11540. svr.Get("/file", [&](const Request &, Response &res) {
  11541. res.set_file_content(path, "text/plain");
  11542. });
  11543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11544. auto se = detail::scope_exit([&] {
  11545. svr.stop();
  11546. thread.join();
  11547. ASSERT_FALSE(svr.is_running());
  11548. });
  11549. svr.wait_until_ready();
  11550. // The file shrinks once the first bytes are in, as a rewrite in place
  11551. // would, and reading the mapping past its new end used to raise SIGBUS.
  11552. SSLClient cli(HOST, PORT);
  11553. cli.enable_server_certificate_verification(false);
  11554. size_t received = 0;
  11555. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11556. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11557. received += len;
  11558. return true;
  11559. });
  11560. EXPECT_FALSE(res);
  11561. EXPECT_LT(received, size);
  11562. }
  11563. #endif
  11564. // Forward declaration (see the base64_encode note).
  11565. namespace httplib {
  11566. namespace detail {
  11567. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11568. const std::string &content_type,
  11569. EncodingType encoding);
  11570. } // namespace detail
  11571. } // namespace httplib
  11572. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11573. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11574. ASSERT_TRUE(mm->is_open());
  11575. Response res;
  11576. detail::set_file_content_provider(res, mm, "text/html",
  11577. detail::EncodingType::None);
  11578. std::string out;
  11579. DataSink sink;
  11580. sink.write = [&](const char *d, size_t l) {
  11581. out.append(d, l);
  11582. return true;
  11583. };
  11584. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11585. EXPECT_EQ("test.html", out);
  11586. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11587. EXPECT_EQ("test.html", out);
  11588. }
  11589. TEST(LongPollingTest, ClientCloseDetection) {
  11590. Server svr;
  11591. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11592. res.set_chunked_content_provider(
  11593. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11594. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11595. sink.os << "hello";
  11596. auto count = 10;
  11597. while (count > 0 && sink.is_writable()) {
  11598. this_thread::sleep_for(chrono::milliseconds(10));
  11599. count--;
  11600. }
  11601. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11602. return true;
  11603. });
  11604. });
  11605. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11606. auto se = detail::scope_exit([&] {
  11607. svr.stop();
  11608. listen_thread.join();
  11609. ASSERT_FALSE(svr.is_running());
  11610. });
  11611. svr.wait_until_ready();
  11612. Client cli("localhost", PORT);
  11613. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11614. EXPECT_EQ("hello", string(data, data_length));
  11615. return false; // close the socket immediately.
  11616. });
  11617. ASSERT_FALSE(res);
  11618. }
  11619. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11620. Server svr;
  11621. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11622. res.set_chunked_content_provider(
  11623. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11624. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11625. sink.os << "hello";
  11626. EXPECT_TRUE(sink.os.good());
  11627. // Wait for the client to close the connection
  11628. auto count = 10;
  11629. while (count > 0 && sink.is_writable()) {
  11630. this_thread::sleep_for(chrono::milliseconds(10));
  11631. count--;
  11632. }
  11633. // After client disconnect, write repeatedly until the socket
  11634. // write actually fails (small writes may be absorbed by the
  11635. // kernel buffer)
  11636. std::string chunk(1024, 'x');
  11637. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11638. sink.os << chunk;
  11639. }
  11640. EXPECT_TRUE(sink.os.fail());
  11641. return true;
  11642. });
  11643. });
  11644. auto port = svr.bind_to_any_port("localhost");
  11645. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11646. auto se = detail::scope_exit([&] {
  11647. svr.stop();
  11648. listen_thread.join();
  11649. ASSERT_FALSE(svr.is_running());
  11650. });
  11651. svr.wait_until_ready();
  11652. Client cli("localhost", port);
  11653. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11654. EXPECT_EQ("hello", string(data, data_length));
  11655. return false; // close the socket immediately.
  11656. });
  11657. ASSERT_FALSE(res);
  11658. }
  11659. TEST(GetWithParametersTest, GetWithParameters) {
  11660. Server svr;
  11661. svr.Get("/", [&](const Request &req, Response &) {
  11662. EXPECT_EQ("world", req.get_param_value("hello"));
  11663. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11664. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11665. });
  11666. svr.Get("/params", [&](const Request &req, Response &) {
  11667. EXPECT_EQ("world", req.get_param_value("hello"));
  11668. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11669. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11670. });
  11671. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11672. EXPECT_EQ("resource-id", req.matches[1]);
  11673. EXPECT_EQ("foo", req.get_param_value("param1"));
  11674. EXPECT_EQ("bar", req.get_param_value("param2"));
  11675. });
  11676. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11677. EXPECT_EQ("user-id", req.path_params.at("id"));
  11678. EXPECT_EQ("foo", req.get_param_value("param1"));
  11679. EXPECT_EQ("bar", req.get_param_value("param2"));
  11680. });
  11681. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11682. auto se = detail::scope_exit([&] {
  11683. svr.stop();
  11684. listen_thread.join();
  11685. ASSERT_FALSE(svr.is_running());
  11686. });
  11687. svr.wait_until_ready();
  11688. {
  11689. Client cli(HOST, PORT);
  11690. Params params;
  11691. params.emplace("hello", "world");
  11692. params.emplace("hello2", "world2");
  11693. params.emplace("hello3", "world3");
  11694. auto res = cli.Get("/", params, Headers{});
  11695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11696. EXPECT_EQ(StatusCode::OK_200, res->status);
  11697. }
  11698. {
  11699. Client cli(HOST, PORT);
  11700. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11702. EXPECT_EQ(StatusCode::OK_200, res->status);
  11703. }
  11704. {
  11705. Client cli(HOST, PORT);
  11706. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11708. EXPECT_EQ(StatusCode::OK_200, res->status);
  11709. }
  11710. {
  11711. Client cli(HOST, PORT);
  11712. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11714. EXPECT_EQ(StatusCode::OK_200, res->status);
  11715. }
  11716. }
  11717. TEST(GetWithParametersTest, GetWithParameters2) {
  11718. Server svr;
  11719. svr.Get("/", [&](const Request &req, Response &res) {
  11720. auto text = req.get_param_value("hello");
  11721. res.set_content(text, "text/plain");
  11722. });
  11723. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11724. auto se = detail::scope_exit([&] {
  11725. svr.stop();
  11726. listen_thread.join();
  11727. ASSERT_FALSE(svr.is_running());
  11728. });
  11729. svr.wait_until_ready();
  11730. Client cli("localhost", PORT);
  11731. Params params;
  11732. params.emplace("hello", "world");
  11733. std::string body;
  11734. auto res = cli.Get("/", params, Headers{},
  11735. [&](const char *data, size_t data_length) {
  11736. body.append(data, data_length);
  11737. return true;
  11738. });
  11739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11740. EXPECT_EQ(StatusCode::OK_200, res->status);
  11741. EXPECT_EQ("world", body);
  11742. }
  11743. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11744. Server svr;
  11745. svr.Get("/search", [&](const Request &req, Response &res) {
  11746. auto q = req.get_param_value("q");
  11747. res.set_content(q, "text/plain");
  11748. });
  11749. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11750. auto se = detail::scope_exit([&] {
  11751. svr.stop();
  11752. listen_thread.join();
  11753. ASSERT_FALSE(svr.is_running());
  11754. });
  11755. svr.wait_until_ready();
  11756. Client cli("localhost", PORT);
  11757. // Verify that Get(path, params) works without requiring Headers argument
  11758. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11760. EXPECT_EQ(StatusCode::OK_200, res->status);
  11761. EXPECT_EQ("cpp-httplib", res->body);
  11762. }
  11763. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11764. auto host = "httpbingo.org";
  11765. auto path = std::string{"/range/32"};
  11766. #ifdef CPPHTTPLIB_SSL_ENABLED
  11767. SSLClient cli(host);
  11768. #else
  11769. Client cli(host);
  11770. #endif
  11771. cli.set_default_headers({make_range_header({{1, 10}})});
  11772. cli.set_connection_timeout(5);
  11773. {
  11774. auto res = cli.Get(path);
  11775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11776. EXPECT_EQ("bcdefghijk", res->body);
  11777. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11778. }
  11779. {
  11780. auto res = cli.Get(path);
  11781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11782. EXPECT_EQ("bcdefghijk", res->body);
  11783. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11784. }
  11785. }
  11786. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11787. Server svr;
  11788. svr.set_default_headers({{"Hello", "World"}});
  11789. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11790. res.set_content("ok", "text/plain");
  11791. });
  11792. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11793. auto se = detail::scope_exit([&] {
  11794. svr.stop();
  11795. listen_thread.join();
  11796. ASSERT_FALSE(svr.is_running());
  11797. });
  11798. svr.wait_until_ready();
  11799. Client cli("localhost", PORT);
  11800. auto res = cli.Get("/");
  11801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11802. EXPECT_EQ(StatusCode::OK_200, res->status);
  11803. EXPECT_EQ("ok", res->body);
  11804. EXPECT_EQ("World", res->get_header_value("Hello"));
  11805. }
  11806. #ifdef CPPHTTPLIB_SSL_ENABLED
  11807. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11808. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11809. ASSERT_TRUE(svr.is_valid());
  11810. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11811. std::this_thread::sleep_for(std::chrono::seconds(2));
  11812. res.set_content("a", "text/plain");
  11813. });
  11814. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11815. res.set_content("b", "text/plain");
  11816. });
  11817. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11818. auto se = detail::scope_exit([&] {
  11819. svr.stop();
  11820. listen_thread.join();
  11821. ASSERT_FALSE(svr.is_running());
  11822. });
  11823. svr.wait_until_ready();
  11824. SSLClient cli("localhost", PORT);
  11825. cli.enable_server_certificate_verification(false);
  11826. cli.set_keep_alive(true);
  11827. cli.set_read_timeout(std::chrono::seconds(1));
  11828. auto resa = cli.Get("/a");
  11829. ASSERT_TRUE(!resa);
  11830. EXPECT_EQ(Error::Read, resa.error());
  11831. auto resb = cli.Get("/b");
  11832. ASSERT_TRUE(resb);
  11833. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11834. EXPECT_EQ("b", resb->body);
  11835. }
  11836. // Closing an idle keep-alive connection sends close_notify and returns. The
  11837. // server must not wait for the client's close_notify: an idle client never
  11838. // sends one, so the worker would be held until the read timeout expires, and
  11839. // stop() would wait for it.
  11840. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11841. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11842. ASSERT_TRUE(svr.is_valid());
  11843. svr.set_keep_alive_timeout(1);
  11844. svr.set_read_timeout(10, 0);
  11845. svr.Get("/", [](const Request &, Response &res) {
  11846. res.set_content("ok", "text/plain");
  11847. });
  11848. auto port = svr.bind_to_any_port(HOST);
  11849. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11850. auto se = detail::scope_exit([&] {
  11851. if (listen_thread.joinable()) {
  11852. svr.stop();
  11853. listen_thread.join();
  11854. }
  11855. });
  11856. svr.wait_until_ready();
  11857. SSLClient cli(HOST, port);
  11858. cli.enable_server_certificate_verification(false);
  11859. cli.set_keep_alive(true);
  11860. auto res = cli.Get("/");
  11861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11862. EXPECT_EQ(StatusCode::OK_200, res->status);
  11863. // Stay idle past the keep-alive timeout so the server closes the connection.
  11864. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11865. auto start = std::chrono::steady_clock::now();
  11866. svr.stop();
  11867. listen_thread.join();
  11868. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11869. std::chrono::steady_clock::now() - start)
  11870. .count();
  11871. EXPECT_LT(elapsed, 3000);
  11872. }
  11873. #endif
  11874. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11875. protected:
  11876. ServerTestWithAI_PASSIVE()
  11877. : cli_(HOST, PORT)
  11878. #ifdef CPPHTTPLIB_SSL_ENABLED
  11879. ,
  11880. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11881. #endif
  11882. {
  11883. #ifdef CPPHTTPLIB_SSL_ENABLED
  11884. cli_.enable_server_certificate_verification(false);
  11885. #endif
  11886. }
  11887. virtual void SetUp() {
  11888. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11889. res.set_content("Hello World!", "text/plain");
  11890. });
  11891. t_ = thread(
  11892. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11893. svr_.wait_until_ready();
  11894. }
  11895. virtual void TearDown() {
  11896. svr_.stop();
  11897. t_.join();
  11898. }
  11899. #ifdef CPPHTTPLIB_SSL_ENABLED
  11900. SSLClient cli_;
  11901. SSLServer svr_;
  11902. #else
  11903. Client cli_;
  11904. Server svr_;
  11905. #endif
  11906. thread t_;
  11907. };
  11908. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11909. auto res = cli_.Get("/hi");
  11910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11911. EXPECT_EQ(StatusCode::OK_200, res->status);
  11912. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11913. EXPECT_EQ("Hello World!", res->body);
  11914. }
  11915. class ServerUpDownTest : public ::testing::Test {
  11916. protected:
  11917. ServerUpDownTest() : cli_(HOST, PORT) {}
  11918. virtual void SetUp() {
  11919. t_ = thread([&]() {
  11920. svr_.bind_to_any_port(HOST);
  11921. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11922. ASSERT_TRUE(svr_.listen_after_bind());
  11923. });
  11924. svr_.wait_until_ready();
  11925. }
  11926. virtual void TearDown() {
  11927. svr_.stop();
  11928. t_.join();
  11929. }
  11930. Client cli_;
  11931. Server svr_;
  11932. thread t_;
  11933. };
  11934. TEST_F(ServerUpDownTest, QuickStartStop) {
  11935. // Should not crash, especially when run with
  11936. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11937. }
  11938. class PayloadMaxLengthTest : public ::testing::Test {
  11939. protected:
  11940. PayloadMaxLengthTest()
  11941. : cli_(HOST, PORT)
  11942. #ifdef CPPHTTPLIB_SSL_ENABLED
  11943. ,
  11944. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11945. #endif
  11946. {
  11947. #ifdef CPPHTTPLIB_SSL_ENABLED
  11948. cli_.enable_server_certificate_verification(false);
  11949. #endif
  11950. }
  11951. virtual void SetUp() {
  11952. svr_.set_payload_max_length(8);
  11953. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11954. res.set_content("test", "text/plain");
  11955. });
  11956. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11957. svr_.wait_until_ready();
  11958. }
  11959. virtual void TearDown() {
  11960. svr_.stop();
  11961. t_.join();
  11962. }
  11963. #ifdef CPPHTTPLIB_SSL_ENABLED
  11964. SSLClient cli_;
  11965. SSLServer svr_;
  11966. #else
  11967. Client cli_;
  11968. Server svr_;
  11969. #endif
  11970. thread t_;
  11971. };
  11972. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11973. auto res = cli_.Post("/test", "123456789", "text/plain");
  11974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11975. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11976. res = cli_.Post("/test", "12345678", "text/plain");
  11977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11978. EXPECT_EQ(StatusCode::OK_200, res->status);
  11979. }
  11980. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11981. // Test chunked encoding with payload exceeding the 8-byte limit
  11982. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11983. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11985. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11986. }
  11987. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11988. // Test chunked encoding with payload within the 8-byte limit
  11989. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11990. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11992. EXPECT_EQ(StatusCode::OK_200, res->status);
  11993. }
  11994. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11995. // Test using send_request to send chunked data exceeding payload limit
  11996. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11997. "Host: " +
  11998. std::string(HOST) + ":" + std::to_string(PORT) +
  11999. "\r\n"
  12000. "Transfer-Encoding: chunked\r\n"
  12001. "Connection: close\r\n"
  12002. "\r\n"
  12003. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12004. "0123456789\r\n"
  12005. "0\r\n" // End chunk
  12006. "\r\n";
  12007. std::string response;
  12008. bool result = send_request(1, chunked_request, &response);
  12009. if (!result) {
  12010. // If send_request fails, it might be because the server closed the
  12011. // connection due to payload limit enforcement, which is acceptable
  12012. SUCCEED()
  12013. << "Server rejected oversized chunked request (connection closed)";
  12014. } else {
  12015. // If we got a response, check if it's an error response or connection was
  12016. // closed early Short response length indicates connection was closed due to
  12017. // payload limit
  12018. if (response.length() <= 10) {
  12019. SUCCEED() << "Server closed connection for oversized chunked request";
  12020. } else {
  12021. // Check for error status codes
  12022. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12023. response.find("Payload Too Large") != std::string::npos ||
  12024. response.find("400") != std::string::npos);
  12025. }
  12026. }
  12027. }
  12028. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  12029. // Test request without Content-Length header exceeding payload limit
  12030. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12031. "Host: " +
  12032. std::string(HOST) + ":" +
  12033. std::to_string(PORT) +
  12034. "\r\n"
  12035. "Connection: close\r\n"
  12036. "\r\n";
  12037. // Add payload exceeding the 8-byte limit
  12038. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  12039. request_without_content_length += large_payload;
  12040. std::string response;
  12041. bool result = send_request(1, request_without_content_length, &response);
  12042. if (!result) {
  12043. // If send_request fails, server likely closed connection due to payload
  12044. // limit
  12045. SUCCEED() << "Server rejected oversized request without Content-Length "
  12046. "(connection closed)";
  12047. } else {
  12048. // Check if server responded with error or closed connection early
  12049. if (response.length() <= 10) {
  12050. SUCCEED() << "Server closed connection for oversized request without "
  12051. "Content-Length";
  12052. } else {
  12053. // Check for error status codes
  12054. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12055. response.find("Payload Too Large") != std::string::npos ||
  12056. response.find("400") != std::string::npos);
  12057. }
  12058. }
  12059. }
  12060. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12061. // Test request without Content-Length header within payload limit
  12062. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12063. "Host: " +
  12064. std::string(HOST) + ":" +
  12065. std::to_string(PORT) +
  12066. "\r\n"
  12067. "Connection: close\r\n"
  12068. "\r\n";
  12069. // Add payload within the 8-byte limit
  12070. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12071. request_without_content_length += small_payload;
  12072. std::string response;
  12073. bool result = send_request(1, request_without_content_length, &response);
  12074. // For requests without Content-Length, the server may have different behavior
  12075. // The key is that it should not reject due to payload limit for small
  12076. // payloads
  12077. if (result) {
  12078. // Check for any HTTP response (success or error, but not connection closed)
  12079. if (response.length() > 10) {
  12080. SUCCEED()
  12081. << "Server processed request without Content-Length within limit";
  12082. } else {
  12083. // Short response might indicate connection closed, which is acceptable
  12084. SUCCEED() << "Server closed connection for request without "
  12085. "Content-Length (acceptable behavior)";
  12086. }
  12087. } else {
  12088. // Connection failure might be due to protocol requirements
  12089. SUCCEED() << "Connection issue with request without Content-Length "
  12090. "(environment-specific)";
  12091. }
  12092. }
  12093. class LargePayloadMaxLengthTest : public ::testing::Test {
  12094. protected:
  12095. LargePayloadMaxLengthTest()
  12096. : cli_(HOST, PORT)
  12097. #ifdef CPPHTTPLIB_SSL_ENABLED
  12098. ,
  12099. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12100. #endif
  12101. {
  12102. #ifdef CPPHTTPLIB_SSL_ENABLED
  12103. cli_.enable_server_certificate_verification(false);
  12104. #endif
  12105. }
  12106. virtual void SetUp() {
  12107. // Set 10MB payload limit
  12108. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12109. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12110. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12111. res.set_content("Large payload test", "text/plain");
  12112. });
  12113. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12114. svr_.wait_until_ready();
  12115. }
  12116. virtual void TearDown() {
  12117. svr_.stop();
  12118. t_.join();
  12119. }
  12120. #ifdef CPPHTTPLIB_SSL_ENABLED
  12121. SSLClient cli_;
  12122. SSLServer svr_;
  12123. #else
  12124. Client cli_;
  12125. Server svr_;
  12126. #endif
  12127. thread t_;
  12128. };
  12129. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12130. // Test chunked encoding with payload within 10MB limit
  12131. std::string medium_payload(5 * 1024 * 1024,
  12132. 'A'); // 5MB payload, within 10MB limit
  12133. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12135. EXPECT_EQ(StatusCode::OK_200, res->status);
  12136. }
  12137. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12138. // Test chunked encoding with payload exceeding 10MB limit
  12139. std::string large_payload(12 * 1024 * 1024,
  12140. 'B'); // 12MB payload, exceeds 10MB limit
  12141. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12142. // Server may either return 413 or close the connection
  12143. if (res) {
  12144. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12145. } else {
  12146. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12147. }
  12148. }
  12149. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12150. // Test request without Content-Length header within 10MB limit
  12151. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12152. "Host: " +
  12153. std::string(HOST) + ":" +
  12154. std::to_string(PORT) +
  12155. "\r\n"
  12156. "Connection: close\r\n"
  12157. "\r\n";
  12158. // Add 1MB payload (within 10MB limit)
  12159. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12160. request_without_content_length += medium_payload;
  12161. std::string response;
  12162. bool result = send_request(5, request_without_content_length, &response);
  12163. if (result) {
  12164. // Should get a proper HTTP response for payloads within limit
  12165. if (response.length() > 10) {
  12166. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12167. "10MB limit";
  12168. } else {
  12169. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12170. "Content-Length)";
  12171. }
  12172. } else {
  12173. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12174. }
  12175. }
  12176. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12177. // Test request without Content-Length header exceeding 10MB limit
  12178. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12179. "Host: " +
  12180. std::string(HOST) + ":" +
  12181. std::to_string(PORT) +
  12182. "\r\n"
  12183. "Connection: close\r\n"
  12184. "\r\n";
  12185. // Add 12MB payload (exceeds 10MB limit)
  12186. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12187. request_without_content_length += large_payload;
  12188. std::string response;
  12189. bool result = send_request(10, request_without_content_length, &response);
  12190. if (!result) {
  12191. // Server should close connection due to payload limit
  12192. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12193. "(connection closed)";
  12194. } else {
  12195. // Check for error response
  12196. if (response.length() <= 10) {
  12197. SUCCEED()
  12198. << "Server closed connection for 12MB request exceeding 10MB limit";
  12199. } else {
  12200. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12201. response.find("Payload Too Large") != std::string::npos ||
  12202. response.find("400") != std::string::npos);
  12203. }
  12204. }
  12205. }
  12206. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12207. Server svr;
  12208. svr.Get("/", [](const Request &, Response &res) {
  12209. // Claims the most the client accepts, far more than it sends, then drops
  12210. // the connection.
  12211. res.set_content_provider(std::string().max_size(), "text/plain",
  12212. [](size_t, size_t, DataSink &sink) {
  12213. sink.write("abc", 3);
  12214. return false;
  12215. });
  12216. });
  12217. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12218. auto se = detail::scope_exit([&] {
  12219. svr.stop();
  12220. thread.join();
  12221. ASSERT_FALSE(svr.is_running());
  12222. });
  12223. svr.wait_until_ready();
  12224. Client cli(HOST, PORT);
  12225. cli.set_payload_max_length(0);
  12226. EXPECT_FALSE(cli.Get("/"));
  12227. }
  12228. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12229. // Stream API does, not as a plain read failure
  12230. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12231. Server svr;
  12232. svr.Get("/big", [](const Request &, Response &res) {
  12233. res.set_content(std::string(100000, 'b'), "text/plain");
  12234. });
  12235. auto port = svr.bind_to_any_port(HOST);
  12236. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12237. auto se = detail::scope_exit([&] {
  12238. svr.stop();
  12239. thread.join();
  12240. });
  12241. svr.wait_until_ready();
  12242. Client cli(HOST, port);
  12243. cli.set_payload_max_length(1000);
  12244. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12245. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12246. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12247. [](const char *, size_t) { return true; });
  12248. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12249. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12250. // Small on the wire, over the limit once decompressed
  12251. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12252. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12253. #endif
  12254. }
  12255. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12256. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12257. // path.
  12258. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12259. Server svr;
  12260. const size_t LIMIT = 64 * 1024; // 64KB
  12261. svr.set_payload_max_length(LIMIT);
  12262. size_t total = 0;
  12263. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12264. const ContentReader &content_reader) {
  12265. content_reader([&](const char * /*data*/, size_t len) {
  12266. total += len;
  12267. return true;
  12268. });
  12269. res.status = 200;
  12270. res.set_content("stream_ok", "text/plain");
  12271. });
  12272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12273. auto se = detail::scope_exit([&] {
  12274. svr.stop();
  12275. thread.join();
  12276. ASSERT_FALSE(svr.is_running());
  12277. });
  12278. svr.wait_until_ready();
  12279. // Prepare 256KB raw data and gzip-compress it
  12280. std::string raw(256 * 1024, 'A');
  12281. std::string gz;
  12282. {
  12283. z_stream zs{};
  12284. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12285. Z_DEFAULT_STRATEGY);
  12286. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12287. zs.avail_in = static_cast<uInt>(raw.size());
  12288. char outbuf[4096];
  12289. int ret;
  12290. do {
  12291. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12292. zs.avail_out = sizeof(outbuf);
  12293. ret = deflate(&zs, Z_FINISH);
  12294. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12295. } while (ret != Z_STREAM_END);
  12296. deflateEnd(&zs);
  12297. }
  12298. Client cli(HOST, PORT);
  12299. cli.set_connection_timeout(std::chrono::seconds(5));
  12300. Headers headers = {{"Content-Encoding", "gzip"}};
  12301. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12302. "application/octet-stream");
  12303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12304. // Server must reject oversized decompressed payloads with 413.
  12305. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12306. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12307. EXPECT_LE(total, LIMIT);
  12308. }
  12309. #ifndef CPPHTTPLIB_SSL_ENABLED
  12310. // For a request with neither Content-Length nor Transfer-Encoding, the
  12311. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12312. // compressed wire bytes straight to the ContentReader without ever routing
  12313. // them through the decompressor, so payload_max_length_ only bounded the
  12314. // compressed size on the wire, not the decompressed size.
  12315. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12316. Server svr;
  12317. const size_t LIMIT = 64 * 1024; // 64KB
  12318. svr.set_payload_max_length(LIMIT);
  12319. size_t total = 0;
  12320. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12321. const ContentReader &content_reader) {
  12322. content_reader([&](const char * /*data*/, size_t len) {
  12323. total += len;
  12324. return true;
  12325. });
  12326. res.status = 200;
  12327. res.set_content("stream_ok", "text/plain");
  12328. });
  12329. auto port = svr.bind_to_any_port(HOST);
  12330. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12331. auto se = detail::scope_exit([&] {
  12332. svr.stop();
  12333. thread.join();
  12334. ASSERT_FALSE(svr.is_running());
  12335. });
  12336. svr.wait_until_ready();
  12337. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12338. // StreamingGzipDecompression test above.
  12339. std::string raw(256 * 1024, 'A');
  12340. std::string gz;
  12341. {
  12342. httplib::detail::gzip_compressor compressor;
  12343. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12344. [&](const char *chunk, size_t len) {
  12345. gz.append(chunk, len);
  12346. return true;
  12347. });
  12348. ASSERT_TRUE(result);
  12349. }
  12350. // Send the gzip body over raw TCP with neither Content-Length nor
  12351. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12352. // kicks in.
  12353. std::string req = "POST /stream HTTP/1.1\r\n"
  12354. "Host: " +
  12355. std::string(HOST) + ":" + std::to_string(port) +
  12356. "\r\n"
  12357. "Content-Encoding: gzip\r\n"
  12358. "Connection: close\r\n"
  12359. "\r\n" +
  12360. gz;
  12361. std::string response;
  12362. ASSERT_TRUE(send_request(5, req, &response, port));
  12363. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12364. EXPECT_LE(total, LIMIT);
  12365. }
  12366. #endif
  12367. #endif
  12368. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12369. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12370. // the payload must be passed through untouched instead of being rejected.
  12371. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12372. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12373. Server svr;
  12374. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12375. res.set_content(body, "image/jpeg");
  12376. res.set_header("Content-Encoding", "UTF-8");
  12377. });
  12378. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12379. res.set_content(body, "image/jpeg");
  12380. res.set_header("Content-Encoding", "identity");
  12381. });
  12382. svr.Post("/echo", [](const Request &req, Response &res) {
  12383. res.set_content(req.body, "image/jpeg");
  12384. });
  12385. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12386. auto se = detail::scope_exit([&] {
  12387. svr.stop();
  12388. t.join();
  12389. ASSERT_FALSE(svr.is_running());
  12390. });
  12391. svr.wait_until_ready();
  12392. Client cli(HOST, PORT);
  12393. {
  12394. auto res = cli.Get("/image");
  12395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12396. EXPECT_EQ(StatusCode::OK_200, res->status);
  12397. EXPECT_EQ(body, res->body);
  12398. }
  12399. {
  12400. auto res = cli.Get("/identity");
  12401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12402. EXPECT_EQ(StatusCode::OK_200, res->status);
  12403. EXPECT_EQ(body, res->body);
  12404. }
  12405. {
  12406. // The same applies to a request body reaching the server.
  12407. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12408. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12410. EXPECT_EQ(StatusCode::OK_200, res->status);
  12411. EXPECT_EQ(body, res->body);
  12412. }
  12413. }
  12414. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12415. // gzip-encoded response even when the build has no zlib support.
  12416. static const char GZIPPED_HELLO_WORLD[] = {
  12417. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12418. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12419. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12420. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12421. // A content coding is a whole token, not something the field value merely
  12422. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12423. // as "fibre" look like Brotli, and turned a multi-coding value like
  12424. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12425. // it was never meant to see.
  12426. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12427. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12428. Server svr;
  12429. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12430. res.set_content(body, "image/jpeg");
  12431. res.set_header("Content-Encoding", "fibre");
  12432. });
  12433. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12434. res.set_content(body, "image/jpeg");
  12435. res.set_header("Content-Encoding", "gzip, br");
  12436. });
  12437. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12438. res.set_content(body, "image/jpeg");
  12439. res.set_header("Content-Encoding", "x-zstd-ish");
  12440. });
  12441. auto port = svr.bind_to_any_port(HOST);
  12442. thread t = thread([&]() { svr.listen_after_bind(); });
  12443. auto se = detail::scope_exit([&] {
  12444. svr.stop();
  12445. t.join();
  12446. ASSERT_FALSE(svr.is_running());
  12447. });
  12448. svr.wait_until_ready();
  12449. Client cli(HOST, port);
  12450. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12451. auto res = cli.Get(path);
  12452. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12453. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12454. // Not a coding we recognize, so the payload comes back untouched
  12455. EXPECT_EQ(body, res->body) << path;
  12456. }
  12457. }
  12458. // A content coding cpp-httplib recognizes but was not built with must be
  12459. // reported as such. Handing the still-compressed payload back to the caller
  12460. // would silently corrupt it.
  12461. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12462. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12463. Server svr;
  12464. // "image/jpeg" keeps the server from applying a content coding of its own,
  12465. // so the hand-crafted Content-Encoding below survives.
  12466. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12467. res.set_content(gzipped, "image/jpeg");
  12468. res.set_header("Content-Encoding", "gzip");
  12469. });
  12470. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12471. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12472. res.set_content(gzipped, "image/jpeg");
  12473. res.set_header("Content-Encoding", "GZIP");
  12474. });
  12475. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12476. auto se = detail::scope_exit([&] {
  12477. svr.stop();
  12478. t.join();
  12479. ASSERT_FALSE(svr.is_running());
  12480. });
  12481. svr.wait_until_ready();
  12482. Client cli(HOST, PORT);
  12483. {
  12484. auto res = cli.Get("/gzipped");
  12485. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12487. EXPECT_EQ("Hello World!", res->body);
  12488. #else
  12489. ASSERT_FALSE(res);
  12490. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12491. #endif
  12492. }
  12493. {
  12494. // open_stream() must behave the same way.
  12495. auto handle = cli.open_stream("GET", "/gzipped");
  12496. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12497. ASSERT_TRUE(handle.is_valid());
  12498. std::string received;
  12499. char buf[256];
  12500. ssize_t n;
  12501. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12502. received.append(buf, static_cast<size_t>(n));
  12503. }
  12504. EXPECT_EQ("Hello World!", received);
  12505. #else
  12506. EXPECT_FALSE(handle.is_valid());
  12507. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12508. #endif
  12509. }
  12510. {
  12511. // A differently-cased coding must not be mistaken for an unknown one, or
  12512. // the body would be handed back still compressed.
  12513. auto res = cli.Get("/gzipped-uppercase");
  12514. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12516. EXPECT_EQ("Hello World!", res->body);
  12517. #else
  12518. ASSERT_FALSE(res);
  12519. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12520. #endif
  12521. }
  12522. }
  12523. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12524. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12525. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12526. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12527. // body a second time and appending a second Content-Encoding field line, so
  12528. // clients that decode one coding per listed value handed back raw gzip bytes.
  12529. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12530. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12531. Server svr;
  12532. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12533. // keeps the server from applying a coding of its own.
  12534. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12535. res.set_content(gzipped, "text/plain");
  12536. res.set_header("Content-Encoding", "gzip");
  12537. });
  12538. auto port = svr.bind_to_any_port(HOST);
  12539. thread t = thread([&]() { svr.listen_after_bind(); });
  12540. auto se = detail::scope_exit([&] {
  12541. svr.stop();
  12542. t.join();
  12543. ASSERT_FALSE(svr.is_running());
  12544. });
  12545. svr.wait_until_ready();
  12546. Client cli(HOST, port);
  12547. Headers headers = {{"Accept-Encoding", "gzip"}};
  12548. auto res = cli.Get("/pre-gzipped", headers);
  12549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12550. EXPECT_EQ(StatusCode::OK_200, res->status);
  12551. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12552. EXPECT_EQ("Hello World!", res->body);
  12553. }
  12554. // A chunked provider settles its coding where the headers are written and
  12555. // reuses it at write time. Both ends of that have to hold: a handler's own
  12556. // Content-Encoding suppresses the coding, and a response without one is still
  12557. // compressed as it always was.
  12558. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12559. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12560. const std::string plain = "Hello World! Hello World! Hello World!";
  12561. Server svr;
  12562. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12563. res.set_header("Content-Encoding", "gzip");
  12564. res.set_chunked_content_provider(
  12565. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12566. sink.write(gzipped.data(), gzipped.size());
  12567. sink.done();
  12568. return true;
  12569. });
  12570. });
  12571. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12572. res.set_chunked_content_provider(
  12573. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12574. sink.write(plain.data(), plain.size());
  12575. sink.done();
  12576. return true;
  12577. });
  12578. });
  12579. auto port = svr.bind_to_any_port(HOST);
  12580. thread t = thread([&]() { svr.listen_after_bind(); });
  12581. auto se = detail::scope_exit([&] {
  12582. svr.stop();
  12583. t.join();
  12584. ASSERT_FALSE(svr.is_running());
  12585. });
  12586. svr.wait_until_ready();
  12587. Client cli(HOST, port);
  12588. Headers headers = {{"Accept-Encoding", "gzip"}};
  12589. {
  12590. auto res = cli.Get("/pre-gzipped", headers);
  12591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12592. EXPECT_EQ(StatusCode::OK_200, res->status);
  12593. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12594. EXPECT_EQ("Hello World!", res->body);
  12595. }
  12596. {
  12597. auto res = cli.Get("/negotiated", headers);
  12598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12599. EXPECT_EQ(StatusCode::OK_200, res->status);
  12600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12601. EXPECT_EQ(plain, res->body);
  12602. }
  12603. }
  12604. #endif
  12605. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12606. // the same message as the comma-joined one, so both have to be read the same
  12607. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12608. // single gzip coding, and a body the sender says was encoded twice was handed
  12609. // back after one pass, still compressed but presented as decoded.
  12610. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12611. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12612. Server svr;
  12613. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12614. res.set_content(body, "image/jpeg");
  12615. res.headers.emplace("Content-Encoding", "gzip");
  12616. res.headers.emplace("Content-Encoding", "gzip");
  12617. });
  12618. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12619. res.set_content(body, "image/jpeg");
  12620. res.set_header("Content-Encoding", "gzip, gzip");
  12621. });
  12622. auto port = svr.bind_to_any_port(HOST);
  12623. thread t = thread([&]() { svr.listen_after_bind(); });
  12624. auto se = detail::scope_exit([&] {
  12625. svr.stop();
  12626. t.join();
  12627. ASSERT_FALSE(svr.is_running());
  12628. });
  12629. svr.wait_until_ready();
  12630. Client cli(HOST, port);
  12631. // Two codings is not something cpp-httplib decodes, so both representations
  12632. // take the pass-through path rather than one of them being gunzipped once.
  12633. for (const char *path : {"/split", "/joined"}) {
  12634. auto res = cli.Get(path);
  12635. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12636. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12637. EXPECT_EQ(body, res->body) << path;
  12638. }
  12639. }
  12640. // Regression test for DoS vulnerability: a malicious server sending a response
  12641. // without Content-Length header must not cause unbounded memory consumption on
  12642. // the client side. The client should stop reading after a reasonable limit,
  12643. // similar to the server-side set_payload_max_length protection.
  12644. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12645. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12646. #ifndef _WIN32
  12647. signal(SIGPIPE, SIG_IGN);
  12648. #endif
  12649. auto server_thread = std::thread([] {
  12650. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12651. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12652. default_socket_options(srv);
  12653. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12654. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12655. sockaddr_in addr{};
  12656. addr.sin_family = AF_INET;
  12657. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12658. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12659. int opt = 1;
  12660. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12661. #ifdef _WIN32
  12662. reinterpret_cast<const char *>(&opt),
  12663. #else
  12664. &opt,
  12665. #endif
  12666. sizeof(opt));
  12667. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12668. ::listen(srv, 1);
  12669. sockaddr_in cli_addr{};
  12670. socklen_t cli_len = sizeof(cli_addr);
  12671. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12672. if (cli != INVALID_SOCKET) {
  12673. char buf[4096];
  12674. ::recv(cli, buf, sizeof(buf), 0);
  12675. // Malicious response: no Content-Length, no chunked encoding
  12676. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12677. "Connection: close\r\n"
  12678. "\r\n";
  12679. ::send(cli,
  12680. #ifdef _WIN32
  12681. static_cast<const char *>(response_header.c_str()),
  12682. static_cast<int>(response_header.size()),
  12683. #else
  12684. response_header.c_str(), response_header.size(),
  12685. #endif
  12686. 0);
  12687. // Send 10MB of data
  12688. std::string chunk(64 * 1024, 'A');
  12689. size_t total_sent = 0;
  12690. while (total_sent < MALICIOUS_DATA_SIZE) {
  12691. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12692. auto sent = ::send(cli,
  12693. #ifdef _WIN32
  12694. static_cast<const char *>(chunk.c_str()),
  12695. static_cast<int>(to_send),
  12696. #else
  12697. chunk.c_str(), to_send,
  12698. #endif
  12699. 0);
  12700. if (sent <= 0) break;
  12701. total_sent += static_cast<size_t>(sent);
  12702. }
  12703. detail::close_socket(cli);
  12704. }
  12705. detail::close_socket(srv);
  12706. });
  12707. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12708. size_t total_read = 0;
  12709. {
  12710. Client cli("127.0.0.1", PORT + 2);
  12711. cli.set_read_timeout(5, 0);
  12712. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12713. auto stream = cli.open_stream("GET", "/malicious");
  12714. ASSERT_TRUE(stream.is_valid());
  12715. char buffer[64 * 1024];
  12716. ssize_t n;
  12717. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12718. total_read += static_cast<size_t>(n);
  12719. }
  12720. } // StreamHandle and Client destroyed here, closing the socket
  12721. server_thread.join();
  12722. // With set_payload_max_length, the client must stop reading before consuming
  12723. // all 10MB. The read loop should be cut off at or near the configured limit.
  12724. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12725. << "Client read " << total_read << " bytes, exceeding the configured "
  12726. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12727. }
  12728. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12729. // the entire response body without truncation.
  12730. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12731. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12732. #ifndef _WIN32
  12733. signal(SIGPIPE, SIG_IGN);
  12734. #endif
  12735. auto server_thread = std::thread([] {
  12736. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12737. default_socket_options(srv);
  12738. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12739. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12740. sockaddr_in addr{};
  12741. addr.sin_family = AF_INET;
  12742. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12743. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12744. int opt = 1;
  12745. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12746. #ifdef _WIN32
  12747. reinterpret_cast<const char *>(&opt),
  12748. #else
  12749. &opt,
  12750. #endif
  12751. sizeof(opt));
  12752. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12753. ::listen(srv, 1);
  12754. sockaddr_in cli_addr{};
  12755. socklen_t cli_len = sizeof(cli_addr);
  12756. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12757. if (cli != INVALID_SOCKET) {
  12758. char buf[4096];
  12759. ::recv(cli, buf, sizeof(buf), 0);
  12760. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12761. "Connection: close\r\n"
  12762. "\r\n";
  12763. ::send(cli,
  12764. #ifdef _WIN32
  12765. static_cast<const char *>(response_header.c_str()),
  12766. static_cast<int>(response_header.size()),
  12767. #else
  12768. response_header.c_str(), response_header.size(),
  12769. #endif
  12770. 0);
  12771. std::string chunk(64 * 1024, 'A');
  12772. size_t total_sent = 0;
  12773. while (total_sent < DATA_SIZE) {
  12774. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12775. auto sent = ::send(cli,
  12776. #ifdef _WIN32
  12777. static_cast<const char *>(chunk.c_str()),
  12778. static_cast<int>(to_send),
  12779. #else
  12780. chunk.c_str(), to_send,
  12781. #endif
  12782. 0);
  12783. if (sent <= 0) break;
  12784. total_sent += static_cast<size_t>(sent);
  12785. }
  12786. #ifdef _WIN32
  12787. ::shutdown(cli, SD_SEND);
  12788. #else
  12789. ::shutdown(cli, SHUT_WR);
  12790. #endif
  12791. // Drain until the client closes its end, ensuring all data is delivered
  12792. char drain[1024];
  12793. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12794. detail::close_socket(cli);
  12795. }
  12796. detail::close_socket(srv);
  12797. });
  12798. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12799. size_t total_read = 0;
  12800. {
  12801. Client cli("127.0.0.1", PORT + 2);
  12802. cli.set_read_timeout(5, 0);
  12803. cli.set_payload_max_length(0); // 0 means no limit
  12804. auto stream = cli.open_stream("GET", "/data");
  12805. ASSERT_TRUE(stream.is_valid());
  12806. char buffer[64 * 1024];
  12807. ssize_t n;
  12808. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12809. total_read += static_cast<size_t>(n);
  12810. }
  12811. }
  12812. server_thread.join();
  12813. EXPECT_EQ(total_read, DATA_SIZE)
  12814. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12815. << " bytes without truncation, but only read " << total_read << " bytes.";
  12816. }
  12817. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12818. // enormous Content-Length must not cause the client to pre-allocate a huge
  12819. // response body buffer. The reservation is capped at payload_max_length_, and
  12820. // the read itself fails when the body exceeds the limit.
  12821. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12822. #ifndef _WIN32
  12823. signal(SIGPIPE, SIG_IGN);
  12824. #endif
  12825. auto server_thread = std::thread([] {
  12826. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12827. default_socket_options(srv);
  12828. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12829. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12830. sockaddr_in addr{};
  12831. addr.sin_family = AF_INET;
  12832. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12833. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12834. int opt = 1;
  12835. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12836. #ifdef _WIN32
  12837. reinterpret_cast<const char *>(&opt),
  12838. #else
  12839. &opt,
  12840. #endif
  12841. sizeof(opt));
  12842. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12843. ::listen(srv, 1);
  12844. sockaddr_in cli_addr{};
  12845. socklen_t cli_len = sizeof(cli_addr);
  12846. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12847. if (cli != INVALID_SOCKET) {
  12848. char buf[4096];
  12849. ::recv(cli, buf, sizeof(buf), 0);
  12850. // Malicious response: claim a 20GB body but send only a tiny payload.
  12851. std::string response = "HTTP/1.1 200 OK\r\n"
  12852. "Content-Length: 20000000000\r\n"
  12853. "\r\n"
  12854. "abc";
  12855. ::send(cli,
  12856. #ifdef _WIN32
  12857. static_cast<const char *>(response.c_str()),
  12858. static_cast<int>(response.size()),
  12859. #else
  12860. response.c_str(), response.size(),
  12861. #endif
  12862. 0);
  12863. detail::close_socket(cli);
  12864. }
  12865. detail::close_socket(srv);
  12866. });
  12867. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12868. {
  12869. Client cli("127.0.0.1", PORT + 2);
  12870. cli.set_read_timeout(5, 0);
  12871. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12872. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12873. // (server claims more bytes than payload_max_length permits), but it must
  12874. // not exhaust memory before getting there.
  12875. auto res = cli.Get("/malicious");
  12876. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12877. }
  12878. server_thread.join();
  12879. }
  12880. // Verify that content_receiver bypasses the default payload_max_length,
  12881. // allowing streaming downloads larger than 100MB without requiring an explicit
  12882. // set_payload_max_length call.
  12883. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12884. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12885. #ifndef _WIN32
  12886. signal(SIGPIPE, SIG_IGN);
  12887. #endif
  12888. auto server_thread = std::thread([] {
  12889. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12890. default_socket_options(srv);
  12891. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12892. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12893. sockaddr_in addr{};
  12894. addr.sin_family = AF_INET;
  12895. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12896. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12897. int opt = 1;
  12898. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12899. #ifdef _WIN32
  12900. reinterpret_cast<const char *>(&opt),
  12901. #else
  12902. &opt,
  12903. #endif
  12904. sizeof(opt));
  12905. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12906. ::listen(srv, 1);
  12907. sockaddr_in cli_addr{};
  12908. socklen_t cli_len = sizeof(cli_addr);
  12909. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12910. if (cli != INVALID_SOCKET) {
  12911. char buf[4096];
  12912. ::recv(cli, buf, sizeof(buf), 0);
  12913. // Response with Content-Length larger than default 100MB limit
  12914. auto content_length = std::to_string(DATA_SIZE);
  12915. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12916. "Content-Length: " +
  12917. content_length +
  12918. "\r\n"
  12919. "Connection: close\r\n"
  12920. "\r\n";
  12921. ::send(cli,
  12922. #ifdef _WIN32
  12923. static_cast<const char *>(response_header.c_str()),
  12924. static_cast<int>(response_header.size()),
  12925. #else
  12926. response_header.c_str(), response_header.size(),
  12927. #endif
  12928. 0);
  12929. std::string chunk(64 * 1024, 'A');
  12930. size_t total_sent = 0;
  12931. while (total_sent < DATA_SIZE) {
  12932. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12933. auto sent = ::send(cli,
  12934. #ifdef _WIN32
  12935. static_cast<const char *>(chunk.c_str()),
  12936. static_cast<int>(to_send),
  12937. #else
  12938. chunk.c_str(), to_send,
  12939. #endif
  12940. 0);
  12941. if (sent <= 0) break;
  12942. total_sent += static_cast<size_t>(sent);
  12943. }
  12944. detail::close_socket(cli);
  12945. }
  12946. detail::close_socket(srv);
  12947. });
  12948. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12949. size_t total_received = 0;
  12950. {
  12951. Client cli("127.0.0.1", PORT + 2);
  12952. cli.set_read_timeout(10, 0);
  12953. // Do NOT call set_payload_max_length — use the default 100MB limit
  12954. auto res =
  12955. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12956. total_received += data_length;
  12957. return true;
  12958. });
  12959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12960. EXPECT_EQ(StatusCode::OK_200, res->status);
  12961. }
  12962. server_thread.join();
  12963. EXPECT_EQ(total_received, DATA_SIZE)
  12964. << "With content_receiver, the client should read all " << DATA_SIZE
  12965. << " bytes despite the default 100MB payload_max_length, but only read "
  12966. << total_received << " bytes.";
  12967. }
  12968. // Verify that an explicit set_payload_max_length smaller than the response is
  12969. // enforced even when a content_receiver is used.
  12970. TEST(ClientVulnerabilityTest,
  12971. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12972. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12973. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12974. #ifndef _WIN32
  12975. signal(SIGPIPE, SIG_IGN);
  12976. #endif
  12977. auto server_thread = std::thread([] {
  12978. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12979. default_socket_options(srv);
  12980. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12981. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12982. sockaddr_in addr{};
  12983. addr.sin_family = AF_INET;
  12984. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12985. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12986. int opt = 1;
  12987. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12988. #ifdef _WIN32
  12989. reinterpret_cast<const char *>(&opt),
  12990. #else
  12991. &opt,
  12992. #endif
  12993. sizeof(opt));
  12994. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12995. ::listen(srv, 1);
  12996. sockaddr_in cli_addr{};
  12997. socklen_t cli_len = sizeof(cli_addr);
  12998. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12999. if (cli != INVALID_SOCKET) {
  13000. char buf[4096];
  13001. ::recv(cli, buf, sizeof(buf), 0);
  13002. auto content_length = std::to_string(DATA_SIZE);
  13003. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13004. "Content-Length: " +
  13005. content_length +
  13006. "\r\n"
  13007. "Connection: close\r\n"
  13008. "\r\n";
  13009. ::send(cli,
  13010. #ifdef _WIN32
  13011. static_cast<const char *>(response_header.c_str()),
  13012. static_cast<int>(response_header.size()),
  13013. #else
  13014. response_header.c_str(), response_header.size(),
  13015. #endif
  13016. 0);
  13017. std::string chunk(64 * 1024, 'A');
  13018. size_t total_sent = 0;
  13019. while (total_sent < DATA_SIZE) {
  13020. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13021. auto sent = ::send(cli,
  13022. #ifdef _WIN32
  13023. static_cast<const char *>(chunk.c_str()),
  13024. static_cast<int>(to_send),
  13025. #else
  13026. chunk.c_str(), to_send,
  13027. #endif
  13028. 0);
  13029. if (sent <= 0) break;
  13030. total_sent += static_cast<size_t>(sent);
  13031. }
  13032. detail::close_socket(cli);
  13033. }
  13034. detail::close_socket(srv);
  13035. });
  13036. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13037. size_t total_received = 0;
  13038. {
  13039. Client cli("127.0.0.1", PORT + 2);
  13040. cli.set_read_timeout(10, 0);
  13041. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13042. auto res =
  13043. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13044. total_received += data_length;
  13045. return true;
  13046. });
  13047. // Should fail because 200MB exceeds the explicit 150MB limit
  13048. EXPECT_FALSE(res);
  13049. }
  13050. server_thread.join();
  13051. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13052. << "Client with content_receiver should respect the explicit "
  13053. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13054. << total_received << " bytes.";
  13055. }
  13056. // Verify that an explicit set_payload_max_length larger than the response
  13057. // allows the content_receiver to read all data successfully.
  13058. TEST(ClientVulnerabilityTest,
  13059. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13060. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13061. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13062. #ifndef _WIN32
  13063. signal(SIGPIPE, SIG_IGN);
  13064. #endif
  13065. auto server_thread = std::thread([] {
  13066. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13067. default_socket_options(srv);
  13068. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13069. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13070. sockaddr_in addr{};
  13071. addr.sin_family = AF_INET;
  13072. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13073. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13074. int opt = 1;
  13075. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13076. #ifdef _WIN32
  13077. reinterpret_cast<const char *>(&opt),
  13078. #else
  13079. &opt,
  13080. #endif
  13081. sizeof(opt));
  13082. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13083. ::listen(srv, 1);
  13084. sockaddr_in cli_addr{};
  13085. socklen_t cli_len = sizeof(cli_addr);
  13086. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13087. if (cli != INVALID_SOCKET) {
  13088. char buf[4096];
  13089. ::recv(cli, buf, sizeof(buf), 0);
  13090. auto content_length = std::to_string(DATA_SIZE);
  13091. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13092. "Content-Length: " +
  13093. content_length +
  13094. "\r\n"
  13095. "Connection: close\r\n"
  13096. "\r\n";
  13097. ::send(cli,
  13098. #ifdef _WIN32
  13099. static_cast<const char *>(response_header.c_str()),
  13100. static_cast<int>(response_header.size()),
  13101. #else
  13102. response_header.c_str(), response_header.size(),
  13103. #endif
  13104. 0);
  13105. std::string chunk(64 * 1024, 'A');
  13106. size_t total_sent = 0;
  13107. while (total_sent < DATA_SIZE) {
  13108. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13109. auto sent = ::send(cli,
  13110. #ifdef _WIN32
  13111. static_cast<const char *>(chunk.c_str()),
  13112. static_cast<int>(to_send),
  13113. #else
  13114. chunk.c_str(), to_send,
  13115. #endif
  13116. 0);
  13117. if (sent <= 0) break;
  13118. total_sent += static_cast<size_t>(sent);
  13119. }
  13120. #ifdef _WIN32
  13121. ::shutdown(cli, SD_SEND);
  13122. #else
  13123. ::shutdown(cli, SHUT_WR);
  13124. #endif
  13125. char drain[1024];
  13126. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13127. detail::close_socket(cli);
  13128. }
  13129. detail::close_socket(srv);
  13130. });
  13131. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13132. size_t total_received = 0;
  13133. {
  13134. Client cli("127.0.0.1", PORT + 2);
  13135. cli.set_read_timeout(10, 0);
  13136. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13137. auto res =
  13138. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13139. total_received += data_length;
  13140. return true;
  13141. });
  13142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13143. EXPECT_EQ(StatusCode::OK_200, res->status);
  13144. }
  13145. server_thread.join();
  13146. EXPECT_EQ(total_received, DATA_SIZE)
  13147. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13148. << " bytes (larger than " << DATA_SIZE
  13149. << " bytes response), content_receiver should read all data, but only "
  13150. "read "
  13151. << total_received << " bytes.";
  13152. }
  13153. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13154. // Regression test for "zip bomb" attack on the client side: a malicious server
  13155. // sends a small gzip-compressed response that decompresses to a huge payload.
  13156. // The client must enforce payload_max_length on the decompressed size.
  13157. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13158. constexpr size_t DECOMPRESSED_SIZE =
  13159. 10 * 1024 * 1024; // 10MB after decompression
  13160. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13161. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13162. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13163. std::string compressed;
  13164. {
  13165. httplib::detail::gzip_compressor compressor;
  13166. bool ok =
  13167. compressor.compress(uncompressed.data(), uncompressed.size(),
  13168. /*last=*/true, [&](const char *buf, size_t len) {
  13169. compressed.append(buf, len);
  13170. return true;
  13171. });
  13172. ASSERT_TRUE(ok);
  13173. }
  13174. // Sanity: compressed data should be much smaller than the decompressed size
  13175. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13176. #ifndef _WIN32
  13177. signal(SIGPIPE, SIG_IGN);
  13178. #endif
  13179. // Set up the listening socket in the main thread so the server is guaranteed
  13180. // to be ready before the client connects (eliminates race condition).
  13181. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13182. default_socket_options(srv);
  13183. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13184. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13185. sockaddr_in addr{};
  13186. addr.sin_family = AF_INET;
  13187. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13188. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13189. int opt = 1;
  13190. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13191. #ifdef _WIN32
  13192. reinterpret_cast<const char *>(&opt),
  13193. #else
  13194. &opt,
  13195. #endif
  13196. sizeof(opt));
  13197. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13198. ASSERT_EQ(0, ::listen(srv, 1));
  13199. auto server_thread = std::thread([&compressed, srv] {
  13200. sockaddr_in cli_addr{};
  13201. socklen_t cli_len = sizeof(cli_addr);
  13202. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13203. if (cli != INVALID_SOCKET) {
  13204. // Read the full HTTP request (until \r\n\r\n)
  13205. char buf[4096];
  13206. size_t total = 0;
  13207. while (total < sizeof(buf)) {
  13208. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13209. if (n <= 0) break;
  13210. total += static_cast<size_t>(n);
  13211. // Check for end of headers
  13212. if (total >= 4) {
  13213. std::string req(buf, total);
  13214. if (req.find("\r\n\r\n") != std::string::npos) break;
  13215. }
  13216. }
  13217. // Malicious response: gzip-compressed body, no Content-Length
  13218. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13219. "Content-Encoding: gzip\r\n"
  13220. "Connection: close\r\n"
  13221. "\r\n";
  13222. ::send(cli,
  13223. #ifdef _WIN32
  13224. static_cast<const char *>(response_header.c_str()),
  13225. static_cast<int>(response_header.size()),
  13226. #else
  13227. response_header.c_str(), response_header.size(),
  13228. #endif
  13229. 0);
  13230. // Send the compressed payload (small on the wire, huge when decompressed)
  13231. size_t total_sent = 0;
  13232. while (total_sent < compressed.size()) {
  13233. auto to_send = std::min(compressed.size() - total_sent,
  13234. static_cast<size_t>(64 * 1024));
  13235. auto sent =
  13236. ::send(cli,
  13237. #ifdef _WIN32
  13238. static_cast<const char *>(compressed.c_str() + total_sent),
  13239. static_cast<int>(to_send),
  13240. #else
  13241. compressed.c_str() + total_sent, to_send,
  13242. #endif
  13243. 0);
  13244. if (sent <= 0) break;
  13245. total_sent += static_cast<size_t>(sent);
  13246. }
  13247. detail::close_socket(cli);
  13248. }
  13249. });
  13250. auto se = detail::scope_exit([&] {
  13251. detail::close_socket(srv);
  13252. server_thread.join();
  13253. });
  13254. size_t total_decompressed = 0;
  13255. {
  13256. Client cli("127.0.0.1", PORT + 3);
  13257. cli.set_read_timeout(5, 0);
  13258. cli.set_decompress(true);
  13259. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13260. auto stream = cli.open_stream("GET", "/zipbomb");
  13261. ASSERT_TRUE(stream.is_valid());
  13262. char buffer[64 * 1024];
  13263. ssize_t n;
  13264. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13265. total_decompressed += static_cast<size_t>(n);
  13266. }
  13267. }
  13268. // The decompressed size must be capped by payload_max_length. Without
  13269. // protection, the client would decompress the full 10MB from a tiny
  13270. // compressed payload, enabling a zip bomb DoS attack.
  13271. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13272. << "Client decompressed " << total_decompressed
  13273. << " bytes from a gzip response. The decompressed size should be "
  13274. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13275. }
  13276. #endif
  13277. TEST(HostAndPortPropertiesTest, NoSSL) {
  13278. httplib::Client cli("www.google.com", 1234);
  13279. ASSERT_EQ("www.google.com", cli.host());
  13280. ASSERT_EQ(1234, cli.port());
  13281. }
  13282. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13283. httplib::Client cli("www.google.com:1234");
  13284. ASSERT_EQ("www.google.com", cli.host());
  13285. ASSERT_EQ(1234, cli.port());
  13286. }
  13287. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13288. // Port number that overflows int — should not crash, client becomes invalid
  13289. httplib::Client cli("http://www.google.com:99999999999999999999");
  13290. ASSERT_FALSE(cli.is_valid());
  13291. }
  13292. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13293. // Port 99999 exceeds valid range (1-65535) — should not crash
  13294. httplib::Client cli("http://www.google.com:99999");
  13295. ASSERT_FALSE(cli.is_valid());
  13296. auto res = cli.Get("/");
  13297. EXPECT_FALSE(res);
  13298. EXPECT_EQ(Error::Connection, res.error());
  13299. }
  13300. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13301. httplib::Client cli("http://user:pass@localhost:1234");
  13302. ASSERT_FALSE(cli.is_valid());
  13303. EXPECT_FALSE(cli.Get("/"));
  13304. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13305. }
  13306. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13307. httplib::Client cli("http://www.google.com:80abc");
  13308. ASSERT_FALSE(cli.is_valid());
  13309. }
  13310. #ifdef CPPHTTPLIB_SSL_ENABLED
  13311. TEST(HostAndPortPropertiesTest, SSL) {
  13312. httplib::SSLClient cli("www.google.com");
  13313. ASSERT_EQ("www.google.com", cli.host());
  13314. ASSERT_EQ(443, cli.port());
  13315. }
  13316. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13317. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13318. std::string cert;
  13319. read_file(CA_CERT_FILE, cert);
  13320. httplib::SSLClient httplib_client("www.google.com");
  13321. // Load CA store first time
  13322. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13323. // Load CA store second time (update)
  13324. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13325. // Verify client is still valid and can make connections
  13326. httplib_client.enable_server_certificate_verification(true);
  13327. auto res = httplib_client.Get("/");
  13328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13329. // Google may return 200 or 301 depending on various factors
  13330. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13331. res->status == StatusCode::MovedPermanently_301);
  13332. }
  13333. TEST(SSLClientTest, ServerNameIndication_Online) {
  13334. auto host = "httpbingo.org";
  13335. auto path = std::string{"/get"};
  13336. SSLClient cli(host, 443);
  13337. auto res = cli.Get(path);
  13338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13339. ASSERT_EQ(StatusCode::OK_200, res->status);
  13340. }
  13341. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13342. // Use a site that will cause SSL verification failure due to self-signed cert
  13343. SSLClient cli("self-signed.badssl.com", 443);
  13344. cli.enable_server_certificate_verification(true);
  13345. auto res = cli.Get("/");
  13346. ASSERT_TRUE(!res);
  13347. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13348. // Verify backend error is captured for SSLServerVerification
  13349. // This occurs when certificate verification fails
  13350. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13351. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13352. EXPECT_NE(0UL, res.ssl_backend_error());
  13353. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13354. res.ssl_error());
  13355. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13356. #if !defined(_WIN32) || \
  13357. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13358. // On non-Windows or when Windows Schannel is disabled, the error comes
  13359. // from OpenSSL's verification
  13360. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13361. res.ssl_backend_error());
  13362. #endif
  13363. #endif
  13364. }
  13365. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13366. // Use a site where hostname doesn't match the certificate
  13367. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13368. SSLClient cli("wrong.host.badssl.com", 443);
  13369. cli.enable_server_certificate_verification(true);
  13370. cli.enable_server_hostname_verification(true);
  13371. auto res = cli.Get("/");
  13372. ASSERT_TRUE(!res);
  13373. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13374. // Verify backend error is captured for hostname verification failure
  13375. EXPECT_NE(0UL, res.ssl_backend_error());
  13376. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13377. res.ssl_error());
  13378. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13379. #if !defined(_WIN32) || \
  13380. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13381. // On non-Windows or when Windows Schannel is disabled, the error comes
  13382. // from OpenSSL's hostname verification
  13383. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13384. res.ssl_backend_error());
  13385. #endif
  13386. #endif
  13387. }
  13388. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13389. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13390. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13391. SSLClient cli("www.google.com", 443);
  13392. cli.enable_server_certificate_verification(true);
  13393. auto res = cli.Get("/");
  13394. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13395. }
  13396. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13397. SSLClient cli("www.google.com", 443);
  13398. cli.enable_server_certificate_verification(true);
  13399. cli.enable_windows_certificate_verification(false);
  13400. auto res = cli.Get("/");
  13401. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13402. }
  13403. // The server sends an intermediate cross-signed by a root Windows trusts,
  13404. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13405. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13406. SSLClient cli("accounts.spotify.com", 443);
  13407. auto res = cli.Get("/");
  13408. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13409. << " ssl_backend_error=" << res.ssl_backend_error();
  13410. }
  13411. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13412. // policy status, which no backend reports for a self-signed certificate.
  13413. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13414. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13415. ASSERT_TRUE(svr.is_valid());
  13416. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13417. auto se = detail::scope_exit([&] {
  13418. svr.stop();
  13419. t.join();
  13420. ASSERT_FALSE(svr.is_running());
  13421. });
  13422. svr.wait_until_ready();
  13423. SSLClient cli("127.0.0.1", PORT);
  13424. cli.set_connection_timeout(30);
  13425. auto res = cli.Get("/");
  13426. ASSERT_FALSE(res);
  13427. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13428. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13429. }
  13430. #endif
  13431. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13432. Client cli("https://google.com");
  13433. auto res = cli.Get("/");
  13434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13435. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13436. }
  13437. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13438. SSLClient cli("google.com");
  13439. cli.set_ca_cert_path(CA_CERT_FILE);
  13440. auto res = cli.Get("/");
  13441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13442. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13443. }
  13444. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13445. SSLClient cli("google.com");
  13446. cli.enable_server_certificate_verification(true);
  13447. cli.set_ca_cert_path("hello");
  13448. auto res = cli.Get("/");
  13449. ASSERT_TRUE(!res);
  13450. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13451. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13452. // should be set
  13453. EXPECT_EQ(0, res.ssl_error());
  13454. // Verify backend error is captured for SSLLoadingCerts
  13455. // This error occurs when loading CA certificates fails
  13456. EXPECT_NE(0UL, res.ssl_backend_error());
  13457. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13458. // OpenSSL specific error codes:
  13459. // > openssl errstr 0x80000002
  13460. // error:80000002:system library::No such file or directory
  13461. // > openssl errstr 0xA000126
  13462. // error:0A000126:SSL routines::unexpected eof while reading
  13463. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13464. res.ssl_backend_error() == 0xA000126);
  13465. #endif
  13466. }
  13467. TEST(SSLClientTest, ServerCertificateVerification4) {
  13468. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13469. ASSERT_TRUE(svr.is_valid());
  13470. svr.Get("/test", [&](const Request &, Response &res) {
  13471. res.set_content("test", "text/plain");
  13472. svr.stop();
  13473. ASSERT_TRUE(true);
  13474. });
  13475. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13476. auto se = detail::scope_exit([&] {
  13477. t.join();
  13478. ASSERT_FALSE(svr.is_running());
  13479. });
  13480. svr.wait_until_ready();
  13481. SSLClient cli("127.0.0.1", PORT);
  13482. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13483. cli.enable_server_certificate_verification(true);
  13484. cli.set_connection_timeout(30);
  13485. auto res = cli.Get("/test");
  13486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13487. ASSERT_EQ(StatusCode::OK_200, res->status);
  13488. }
  13489. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13490. std::string cert;
  13491. read_file(CA_CERT_FILE, cert);
  13492. SSLClient cli("google.com");
  13493. cli.load_ca_cert_store(cert.data(), cert.size());
  13494. const auto res = cli.Get("/");
  13495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13496. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13497. }
  13498. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13499. // clang-format off
  13500. static constexpr char cert[] =
  13501. "GlobalSign Root CA\n"
  13502. "==================\n"
  13503. "-----BEGIN CERTIFICATE-----\n"
  13504. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13505. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13506. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13507. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13508. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13509. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13510. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13511. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13512. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13513. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13514. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13515. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13516. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13517. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13518. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13519. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13520. "-----END CERTIFICATE-----\n";
  13521. // clang-format on
  13522. SSLClient cli("google.com");
  13523. cli.load_ca_cert_store(cert, sizeof(cert));
  13524. const auto res = cli.Get("/");
  13525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13526. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13527. }
  13528. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13529. SSLClient cli("www.youtube.com");
  13530. cli.set_ca_cert_path(CA_CERT_FILE);
  13531. cli.enable_server_certificate_verification(true);
  13532. cli.set_follow_location(true);
  13533. auto res = cli.Get("/");
  13534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13535. ASSERT_EQ(StatusCode::OK_200, res->status);
  13536. }
  13537. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13538. SSLClient cli("wWw.YouTube.Com");
  13539. cli.set_ca_cert_path(CA_CERT_FILE);
  13540. cli.enable_server_certificate_verification(true);
  13541. cli.enable_server_hostname_verification(true);
  13542. cli.set_follow_location(true);
  13543. auto res = cli.Get("/");
  13544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13545. ASSERT_EQ(StatusCode::OK_200, res->status);
  13546. }
  13547. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13548. SSLClient cli("gOoGlE.COm");
  13549. cli.enable_server_certificate_verification(true);
  13550. cli.enable_server_hostname_verification(true);
  13551. cli.set_follow_location(true);
  13552. auto res = cli.Get("/");
  13553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13554. ASSERT_EQ(StatusCode::OK_200, res->status);
  13555. }
  13556. TEST(SSLClientTest, Issue2004_Online) {
  13557. Client client("https://google.com");
  13558. client.set_follow_location(true);
  13559. auto res = client.Get("/");
  13560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13561. ASSERT_EQ(StatusCode::OK_200, res->status);
  13562. auto body = res->body;
  13563. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13564. }
  13565. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13566. // Create SSLClient with invalid cert/key to make is_valid() return false
  13567. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13568. "nonexistent_key.pem");
  13569. // is_valid() should be false due to cert loading failure
  13570. ASSERT_FALSE(cli.is_valid());
  13571. auto res = cli.Get("/");
  13572. ASSERT_FALSE(res);
  13573. EXPECT_EQ(Error::SSLConnection, res.error());
  13574. }
  13575. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13576. // Test for Issue #2251: SSL error not properly reported when client cert
  13577. // and key paths are swapped or mismatched
  13578. // This simulates the scenario where user accidentally swaps the cert and key
  13579. // files
  13580. // Using client cert file as private key and vice versa (completely wrong)
  13581. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13582. // Should fail validation due to cert/key mismatch
  13583. ASSERT_FALSE(cli.is_valid());
  13584. // Attempt to make a request should fail with proper error
  13585. auto res = cli.Get("/");
  13586. ASSERT_FALSE(res);
  13587. EXPECT_EQ(Error::SSLConnection, res.error());
  13588. // SSL error should be recorded in the Result object (this is the key fix for
  13589. // Issue #2251)
  13590. auto backend_error = res.ssl_backend_error();
  13591. EXPECT_NE(0u, backend_error);
  13592. }
  13593. // Tests cert/key mismatch detection at the TLS context level
  13594. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13595. // Test that using mismatched cert/key causes connection failure.
  13596. // We verify this at the SSLClient level rather than through internal
  13597. // TLS API functions.
  13598. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13599. cli.enable_server_certificate_verification(false);
  13600. cli.set_connection_timeout(2);
  13601. // The mismatch should cause a connection or handshake error
  13602. auto res = cli.Get("/test");
  13603. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13604. // Either way, the request should fail
  13605. EXPECT_FALSE(res);
  13606. }
  13607. #endif
  13608. #if 0
  13609. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13610. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13611. ASSERT_TRUE(cli != nullptr);
  13612. cli->set_address_family(AF_INET6);
  13613. cli->set_interface("en0");
  13614. auto res = cli->Get("/get");
  13615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13616. ASSERT_EQ(StatusCode::OK_200, res->status);
  13617. }
  13618. #endif
  13619. // Client certificate tests - work with all TLS backends
  13620. #ifdef CPPHTTPLIB_SSL_ENABLED
  13621. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13622. void ClientCertPresent(
  13623. const std::string &client_cert_file,
  13624. const std::string &client_private_key_file,
  13625. const std::string &client_encrypted_private_key_pass = std::string(),
  13626. const ClientCertServerSetup &setup = nullptr) {
  13627. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13628. ASSERT_TRUE(svr.is_valid());
  13629. if (setup) { setup(svr); }
  13630. svr.Get("/test", [&](const Request &req, Response &res) {
  13631. res.set_content("test", "text/plain");
  13632. auto cert = req.peer_cert();
  13633. ASSERT_TRUE(static_cast<bool>(cert));
  13634. std::string common_name = cert.subject_cn();
  13635. EXPECT_EQ("Common Name", common_name);
  13636. });
  13637. auto port = svr.bind_to_any_port(HOST);
  13638. ASSERT_LT(0, port);
  13639. thread t = thread([&]() { svr.listen_after_bind(); });
  13640. auto se = detail::scope_exit([&] {
  13641. svr.stop();
  13642. t.join();
  13643. ASSERT_FALSE(svr.is_running());
  13644. });
  13645. svr.wait_until_ready();
  13646. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13647. client_encrypted_private_key_pass);
  13648. cli.enable_server_certificate_verification(false);
  13649. cli.set_connection_timeout(30);
  13650. auto res = cli.Get("/test");
  13651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13652. ASSERT_EQ(StatusCode::OK_200, res->status);
  13653. }
  13654. TEST(SSLClientServerTest, ClientCertPresent) {
  13655. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13656. }
  13657. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13658. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13659. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13660. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13661. }
  13662. // Expects svr, which must require client certificates, to reject a client
  13663. // that has none
  13664. void RejectsClientWithoutCert(SSLServer &svr) {
  13665. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13666. auto port = svr.bind_to_any_port(HOST);
  13667. ASSERT_LT(0, port);
  13668. thread t = thread([&]() { svr.listen_after_bind(); });
  13669. auto se = detail::scope_exit([&] {
  13670. svr.stop();
  13671. t.join();
  13672. ASSERT_FALSE(svr.is_running());
  13673. });
  13674. svr.wait_until_ready();
  13675. SSLClient cli(HOST, port);
  13676. cli.set_connection_timeout(30);
  13677. // Skip the server certificate check, so that the request fails because the
  13678. // client certificate is missing rather than because cert.pem is not trusted
  13679. cli.enable_server_certificate_verification(false);
  13680. auto res = cli.Get("/test");
  13681. ASSERT_FALSE(res);
  13682. // The server rejects the client during the handshake, or on TLS 1.3 right
  13683. // after it, which the client notices on its first write or read
  13684. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13685. res.error() == Error::Write || res.error() == Error::Read)
  13686. << to_string(res.error());
  13687. if (res.error() == Error::SSLConnection) {
  13688. EXPECT_NE(0UL, res.ssl_backend_error());
  13689. }
  13690. // A rejection noticed on the write keeps the TLS error the write hit
  13691. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13692. }
  13693. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13695. ASSERT_TRUE(svr.is_valid());
  13696. if (setup) { setup(svr); }
  13697. RejectsClientWithoutCert(svr);
  13698. }
  13699. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13700. // A server that requires client certificates must keep requiring them after
  13701. // setup changes it, and keep accepting a client that has one
  13702. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13703. ClientCertMissing(setup);
  13704. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13705. setup);
  13706. }
  13707. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13708. ClientCertStillRequired([](SSLServer &svr) {
  13709. ASSERT_TRUE(tls::set_verify_callback(
  13710. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13711. });
  13712. }
  13713. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13714. ClientCertStillRequired([](SSLServer &svr) {
  13715. ASSERT_TRUE(tls::set_verify_callback(
  13716. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13717. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13718. });
  13719. }
  13720. // The client verifies the server certificate during the handshake, so a
  13721. // server that fails the check never gets the client certificate, even when a
  13722. // verifier of the client's own accepts it
  13723. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13724. struct Case {
  13725. const char *trusted_ca;
  13726. const char *host;
  13727. Error error;
  13728. };
  13729. // cert2.pem names localhost: the first client does not trust it, and the
  13730. // second trusts it but asks for another name
  13731. for (const auto &c :
  13732. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13733. Case{SERVER_CERT2_FILE, "example.com",
  13734. Error::SSLServerHostnameVerification}}) {
  13735. for (auto with_verifier : {false, true}) {
  13736. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13737. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13738. CLIENT_CA_CERT_FILE);
  13739. ASSERT_TRUE(svr.is_valid());
  13740. std::atomic<bool> got_client_cert{false};
  13741. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13742. [&](const tls::VerifyContext &) {
  13743. got_client_cert = true;
  13744. return true;
  13745. }));
  13746. auto port = svr.bind_to_any_port("127.0.0.1");
  13747. ASSERT_LT(0, port);
  13748. thread t = thread([&] { svr.listen_after_bind(); });
  13749. svr.wait_until_ready();
  13750. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13751. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13752. cli.set_ca_cert_path(c.trusted_ca);
  13753. if (with_verifier) {
  13754. cli.set_server_certificate_verifier(
  13755. [](const tls::VerifyContext &) { return true; });
  13756. }
  13757. auto res = cli.Get("/");
  13758. EXPECT_FALSE(res);
  13759. EXPECT_EQ(c.error, res.error());
  13760. svr.stop();
  13761. t.join();
  13762. EXPECT_FALSE(got_client_cert);
  13763. }
  13764. }
  13765. }
  13766. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13767. std::string cert_pem, key_pem, ca_pem;
  13768. read_file(SERVER_CERT_FILE, cert_pem);
  13769. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13770. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13771. ASSERT_TRUE(
  13772. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13773. }
  13774. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13776. ASSERT_TRUE(svr.is_valid());
  13777. UpdateCertsPemWithClientCA(svr);
  13778. RejectsClientWithoutCert(svr);
  13779. }
  13780. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13781. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13782. }
  13783. // A TLS error from one request must not show up in a later request's Result
  13784. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13786. ASSERT_TRUE(svr.is_valid());
  13787. svr.Get("/test", [](const Request &, Response &res) {
  13788. res.set_content("test", "text/plain");
  13789. });
  13790. auto port = svr.bind_to_any_port(HOST);
  13791. ASSERT_LT(0, port);
  13792. thread t = thread([&]() { svr.listen_after_bind(); });
  13793. auto se = detail::scope_exit([&] {
  13794. svr.stop();
  13795. t.join();
  13796. ASSERT_FALSE(svr.is_running());
  13797. });
  13798. svr.wait_until_ready();
  13799. SSLClient cli(HOST, port);
  13800. cli.set_connection_timeout(30);
  13801. cli.enable_server_hostname_verification(false);
  13802. // cert.pem is not trusted, so the handshake fails
  13803. ASSERT_FALSE(cli.Get("/test"));
  13804. cli.enable_server_certificate_verification(false);
  13805. auto res = cli.Get("/test");
  13806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13807. EXPECT_EQ(0, res.ssl_error());
  13808. EXPECT_EQ(0UL, res.ssl_backend_error());
  13809. }
  13810. // PEM memory-based constructor tests (works with all TLS backends).
  13811. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13812. // terminator after it.
  13813. void PemMemoryClientCertPresent(
  13814. const std::string &client_cert_file,
  13815. const std::string &client_private_key_file,
  13816. const std::string &client_encrypted_private_key_pass = std::string(),
  13817. bool exact_size = false) {
  13818. // Read PEM files into memory
  13819. std::string server_cert_pem, server_key_pem;
  13820. std::string client_ca_pem;
  13821. std::string client_cert_pem, client_key_pem;
  13822. read_file(SERVER_CERT_FILE, server_cert_pem);
  13823. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13824. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13825. read_file(client_cert_file, client_cert_pem);
  13826. read_file(client_private_key_file, client_key_pem);
  13827. std::list<std::vector<char>> exact_copies;
  13828. auto data = [&](const std::string &pem) -> const char * {
  13829. if (!exact_size) { return pem.c_str(); }
  13830. exact_copies.emplace_back(pem.begin(), pem.end());
  13831. return exact_copies.back().data();
  13832. };
  13833. // Create server with PEM memory
  13834. SSLServer::PemMemory server_pem = {
  13835. data(server_cert_pem),
  13836. server_cert_pem.size(),
  13837. data(server_key_pem),
  13838. server_key_pem.size(),
  13839. data(client_ca_pem),
  13840. client_ca_pem.size(),
  13841. nullptr // no password for server key
  13842. };
  13843. SSLServer svr(server_pem);
  13844. ASSERT_TRUE(svr.is_valid());
  13845. svr.Get("/test", [&](const Request &req, Response &res) {
  13846. res.set_content("test", "text/plain");
  13847. auto cert = req.peer_cert();
  13848. ASSERT_TRUE(static_cast<bool>(cert));
  13849. EXPECT_EQ("Common Name", cert.subject_cn());
  13850. });
  13851. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13852. auto se = detail::scope_exit([&] {
  13853. svr.stop();
  13854. t.join();
  13855. ASSERT_FALSE(svr.is_running());
  13856. });
  13857. svr.wait_until_ready();
  13858. // Create client with PEM memory
  13859. const char *password = client_encrypted_private_key_pass.empty()
  13860. ? nullptr
  13861. : client_encrypted_private_key_pass.c_str();
  13862. SSLClient::PemMemory client_pem = {
  13863. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13864. client_key_pem.size(), password};
  13865. SSLClient cli(HOST, PORT, client_pem);
  13866. cli.enable_server_certificate_verification(false);
  13867. cli.set_connection_timeout(30);
  13868. auto res = cli.Get("/test");
  13869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13870. ASSERT_EQ(StatusCode::OK_200, res->status);
  13871. }
  13872. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13873. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13874. }
  13875. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13876. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13877. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13878. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13879. }
  13880. // A server built from PEM memory with a client CA requires client certificates,
  13881. // also when the CA is a NUL-terminated string passed with a length of 0
  13882. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13883. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13884. read_file(SERVER_CERT_FILE, server_cert_pem);
  13885. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13886. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13887. SSLServer::PemMemory server_pem = {
  13888. server_cert_pem.c_str(),
  13889. server_cert_pem.size(),
  13890. server_key_pem.c_str(),
  13891. server_key_pem.size(),
  13892. client_ca_pem.c_str(),
  13893. client_ca_pem.size(),
  13894. nullptr // no password for server key
  13895. };
  13896. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13897. SCOPED_TRACE(client_ca_pem_len);
  13898. server_pem.client_ca_pem_len = client_ca_pem_len;
  13899. SSLServer svr(server_pem);
  13900. ASSERT_TRUE(svr.is_valid());
  13901. RejectsClientWithoutCert(svr);
  13902. }
  13903. // An empty CA fails to load instead of turning the check off
  13904. server_pem.client_ca_pem = "";
  13905. server_pem.client_ca_pem_len = 0;
  13906. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13907. }
  13908. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13909. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13910. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13911. true);
  13912. }
  13913. // A length shorter than the PEM cuts it short, so it no longer loads
  13914. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13915. std::string cert, key;
  13916. read_file(SERVER_CERT_FILE, cert);
  13917. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13918. for (auto cut_cert : {true, false}) {
  13919. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13920. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13921. SSLServer::PemMemory server_pem = {
  13922. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13923. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13924. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13925. key_len, nullptr};
  13926. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13927. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13928. key.c_str(), key_len, nullptr};
  13929. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13930. }
  13931. }
  13932. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13933. class NoListenSSLServer : public SSLServer {
  13934. public:
  13935. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13936. const char *client_ca_cert_file_path,
  13937. const char *client_ca_cert_dir_path = nullptr)
  13938. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13939. client_ca_cert_dir_path),
  13940. stop_(false) {}
  13941. std::atomic_bool stop_;
  13942. private:
  13943. bool process_and_close_socket(socket_t /*sock*/) override {
  13944. // Don't create SSL context
  13945. while (!stop_.load()) {
  13946. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13947. }
  13948. return true;
  13949. }
  13950. };
  13951. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13952. CLIENT_CA_CERT_FILE);
  13953. ASSERT_TRUE(svr.is_valid());
  13954. svr.Get("/test", [&](const Request &, Response &res) {
  13955. res.set_content("test", "text/plain");
  13956. });
  13957. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13958. auto se = detail::scope_exit([&] {
  13959. svr.stop_ = true;
  13960. svr.stop();
  13961. t.join();
  13962. ASSERT_FALSE(svr.is_running());
  13963. });
  13964. svr.wait_until_ready();
  13965. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13966. cli.enable_server_certificate_verification(false);
  13967. cli.set_connection_timeout(1);
  13968. auto res = cli.Get("/test");
  13969. ASSERT_TRUE(!res);
  13970. EXPECT_EQ(Error::SSLConnection, res.error());
  13971. // Timeout results in WantRead error code (maps to backend-specific value)
  13972. EXPECT_NE(0, res.ssl_error());
  13973. }
  13974. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13975. // Test SSLServer with client certificate verification using the standard
  13976. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13977. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13978. CLIENT_CA_CERT_DIR);
  13979. ASSERT_TRUE(svr.is_valid());
  13980. svr.Get("/test", [&](const Request &req, Response &res) {
  13981. res.set_content("test", "text/plain");
  13982. auto cert = req.peer_cert();
  13983. ASSERT_TRUE(static_cast<bool>(cert));
  13984. auto common_name = cert.subject_cn();
  13985. EXPECT_EQ("Common Name", common_name);
  13986. });
  13987. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13988. auto se = detail::scope_exit([&] {
  13989. svr.stop();
  13990. t.join();
  13991. ASSERT_FALSE(svr.is_running());
  13992. });
  13993. svr.wait_until_ready();
  13994. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13995. cli.enable_server_certificate_verification(false);
  13996. cli.set_connection_timeout(30);
  13997. auto res = cli.Get("/test");
  13998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13999. ASSERT_EQ(StatusCode::OK_200, res->status);
  14000. }
  14001. // Test verify_hostname for both OpenSSL and MbedTLS backends
  14002. // Verifies that wildcard matching and exact matching work consistently
  14003. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14004. using namespace httplib::tls;
  14005. // We need a running server to test against
  14006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14007. ASSERT_TRUE(svr.is_valid());
  14008. svr.Get("/test", [](const Request &, Response &res) {
  14009. res.set_content("ok", "text/plain");
  14010. });
  14011. thread t([&]() { svr.listen(HOST, PORT); });
  14012. auto se = detail::scope_exit([&] {
  14013. svr.stop();
  14014. t.join();
  14015. });
  14016. svr.wait_until_ready();
  14017. bool verify_callback_called = false;
  14018. bool verify_result_wrong = false;
  14019. SSLClient cli(HOST, PORT);
  14020. cli.enable_server_certificate_verification(true);
  14021. cli.set_ca_cert_path(CA_CERT_FILE);
  14022. cli.set_connection_timeout(5);
  14023. // Note: Test certificate has CN="Common Name", not "localhost"
  14024. bool verify_result_cn = false;
  14025. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14026. verify_callback_called = true;
  14027. if (!ctx.cert) return false;
  14028. // Test 1: "Common Name" should match (our test server cert CN)
  14029. verify_result_cn = ctx.check_hostname("Common Name");
  14030. // Test 2: wrong hostname should not match
  14031. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14032. return true; // Accept for the purpose of this test
  14033. });
  14034. auto res = cli.Get("/test");
  14035. // The request may succeed or fail depending on cert configuration
  14036. // but the callback should have been called
  14037. ASSERT_TRUE(verify_callback_called)
  14038. << "Verify callback should have been called";
  14039. // CN="Common Name" should match our test certificate
  14040. //
  14041. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14042. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14043. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14044. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14045. // <openssl/base.h>, which is included transitively when
  14046. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14047. #if defined(OPENSSL_IS_BORINGSSL)
  14048. EXPECT_FALSE(verify_result_cn)
  14049. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14050. #else
  14051. EXPECT_TRUE(verify_result_cn)
  14052. << "verify_hostname should match 'Common Name' (certificate CN)";
  14053. #endif
  14054. // Wrong hostname should not match
  14055. EXPECT_FALSE(verify_result_wrong)
  14056. << "verify_hostname should not match 'wronghost.example.com'";
  14057. }
  14058. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14059. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14060. // X509_check_ip behavior and must hold for every backend.
  14061. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14062. using namespace httplib::tls;
  14063. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14064. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14065. ASSERT_TRUE(svr.is_valid());
  14066. svr.Get("/test", [](const Request &, Response &res) {
  14067. res.set_content("ok", "text/plain");
  14068. });
  14069. thread t([&]() { svr.listen(HOST, PORT); });
  14070. auto se = detail::scope_exit([&] {
  14071. svr.stop();
  14072. t.join();
  14073. });
  14074. svr.wait_until_ready();
  14075. bool verify_callback_called = false;
  14076. bool ip_matched_via_cn = true;
  14077. SSLClient cli(HOST, PORT);
  14078. cli.enable_server_certificate_verification(true);
  14079. cli.set_ca_cert_path(CA_CERT_FILE);
  14080. cli.set_connection_timeout(5);
  14081. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14082. verify_callback_called = true;
  14083. if (!ctx.cert) return false;
  14084. // The IP appears only in the CN, so it must NOT be accepted.
  14085. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14086. return true; // Accept for the purpose of this test
  14087. });
  14088. cli.Get("/test");
  14089. ASSERT_TRUE(verify_callback_called)
  14090. << "Verify callback should have been called";
  14091. EXPECT_FALSE(ip_matched_via_cn)
  14092. << "An IP host must not be authenticated via the certificate CN";
  14093. }
  14094. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14095. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14096. using namespace httplib::tls;
  14097. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14098. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14099. ASSERT_TRUE(svr.is_valid());
  14100. svr.Get("/test", [](const Request &, Response &res) {
  14101. res.set_content("ok", "text/plain");
  14102. });
  14103. thread t([&]() { svr.listen(HOST, PORT); });
  14104. auto se = detail::scope_exit([&] {
  14105. svr.stop();
  14106. t.join();
  14107. });
  14108. svr.wait_until_ready();
  14109. bool verify_callback_called = false;
  14110. bool san_matched = false;
  14111. bool wrong_ipv6_matched = true;
  14112. bool cn_ipv6_matched = true;
  14113. SSLClient cli(HOST, PORT);
  14114. cli.enable_server_certificate_verification(true);
  14115. cli.set_ca_cert_path(CA_CERT_FILE);
  14116. cli.set_connection_timeout(5);
  14117. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14118. verify_callback_called = true;
  14119. if (!ctx.cert) return false;
  14120. // Matches the IPv6 iPAddress SAN.
  14121. san_matched = ctx.check_hostname("2001:db8::1");
  14122. // A different IPv6 address must not match.
  14123. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14124. // "::1" lives only in the CN, so it must not be accepted.
  14125. cn_ipv6_matched = ctx.check_hostname("::1");
  14126. return true; // Accept for the purpose of this test
  14127. });
  14128. cli.Get("/test");
  14129. ASSERT_TRUE(verify_callback_called)
  14130. << "Verify callback should have been called";
  14131. EXPECT_TRUE(san_matched)
  14132. << "verify_hostname should match an IPv6 iPAddress SAN";
  14133. EXPECT_FALSE(wrong_ipv6_matched)
  14134. << "verify_hostname should not match a non-matching IPv6 address";
  14135. EXPECT_FALSE(cn_ipv6_matched)
  14136. << "An IPv6 host must not be authenticated via the certificate CN";
  14137. }
  14138. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14139. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14140. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14141. using namespace httplib::tls;
  14142. // SANs: DNS:a.zz, IP:42.46.122.122
  14143. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14144. ASSERT_TRUE(svr.is_valid());
  14145. svr.Get("/test", [](const Request &, Response &res) {
  14146. res.set_content("ok", "text/plain");
  14147. });
  14148. auto port = svr.bind_to_any_port(HOST);
  14149. thread t([&]() { svr.listen_after_bind(); });
  14150. auto se = detail::scope_exit([&] {
  14151. svr.stop();
  14152. t.join();
  14153. });
  14154. svr.wait_until_ready();
  14155. bool verify_callback_called = false;
  14156. bool dns_san_matched = false;
  14157. bool ip_san_matched = false;
  14158. bool ip_matched_via_dns_san = true;
  14159. bool dns_matched_via_ip_san = true;
  14160. bool cn_matched_next_to_dns_san = true;
  14161. SSLClient cli(HOST, port);
  14162. cli.enable_server_certificate_verification(true);
  14163. cli.set_ca_cert_path(CA_CERT_FILE);
  14164. cli.set_connection_timeout(5);
  14165. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14166. verify_callback_called = true;
  14167. if (!ctx.cert) return false;
  14168. dns_san_matched = ctx.check_hostname("a.zz");
  14169. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14170. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14171. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14172. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14173. return true; // Accept for the purpose of this test
  14174. });
  14175. cli.Get("/test");
  14176. ASSERT_TRUE(verify_callback_called)
  14177. << "Verify callback should have been called";
  14178. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14179. EXPECT_TRUE(ip_san_matched)
  14180. << "verify_hostname should match an iPAddress SAN";
  14181. EXPECT_FALSE(ip_matched_via_dns_san)
  14182. << "An IP host must not be authenticated via a dNSName SAN";
  14183. EXPECT_FALSE(dns_matched_via_ip_san)
  14184. << "A DNS host must not be authenticated via an iPAddress SAN";
  14185. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14186. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14187. }
  14188. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14189. // "www.*.example.test" names one host and not every host under example.test.
  14190. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14191. using namespace httplib::tls;
  14192. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14193. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14194. ASSERT_TRUE(svr.is_valid());
  14195. svr.Get("/test", [](const Request &, Response &res) {
  14196. res.set_content("ok", "text/plain");
  14197. });
  14198. auto port = svr.bind_to_any_port(HOST);
  14199. thread t([&]() { svr.listen_after_bind(); });
  14200. auto se = detail::scope_exit([&] {
  14201. svr.stop();
  14202. t.join();
  14203. });
  14204. svr.wait_until_ready();
  14205. bool verify_callback_called = false;
  14206. bool leftmost_wildcard_matched = false;
  14207. bool wildcard_spanned_labels = true;
  14208. bool inner_wildcard_matched = true;
  14209. SSLClient cli(HOST, port);
  14210. cli.enable_server_certificate_verification(true);
  14211. cli.set_ca_cert_path(CA_CERT_FILE);
  14212. cli.set_connection_timeout(5);
  14213. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14214. verify_callback_called = true;
  14215. if (!ctx.cert) return false;
  14216. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14217. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14218. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14219. return true; // Accept for the purpose of this test
  14220. });
  14221. cli.Get("/test");
  14222. ASSERT_TRUE(verify_callback_called)
  14223. << "Verify callback should have been called";
  14224. EXPECT_TRUE(leftmost_wildcard_matched)
  14225. << "A leftmost wildcard should match a single label";
  14226. EXPECT_FALSE(wildcard_spanned_labels)
  14227. << "A wildcard label must not match more than one label";
  14228. EXPECT_FALSE(inner_wildcard_matched)
  14229. << "A wildcard outside the leftmost label must not be honoured";
  14230. }
  14231. // sans() must report each SAN entry under its own type.
  14232. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14233. using namespace httplib::tls;
  14234. // SANs: DNS:a.zz, IP:42.46.122.122
  14235. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14236. ASSERT_TRUE(svr.is_valid());
  14237. svr.Get("/test", [](const Request &, Response &res) {
  14238. res.set_content("ok", "text/plain");
  14239. });
  14240. auto port = svr.bind_to_any_port(HOST);
  14241. thread t([&]() { svr.listen_after_bind(); });
  14242. auto se = detail::scope_exit([&] {
  14243. svr.stop();
  14244. t.join();
  14245. });
  14246. svr.wait_until_ready();
  14247. bool verify_callback_called = false;
  14248. std::vector<SanEntry> sans;
  14249. SSLClient cli(HOST, port);
  14250. cli.enable_server_certificate_verification(true);
  14251. cli.set_ca_cert_path(CA_CERT_FILE);
  14252. cli.set_connection_timeout(5);
  14253. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14254. verify_callback_called = true;
  14255. if (!ctx.cert) return false;
  14256. sans = ctx.sans();
  14257. return true; // Accept for the purpose of this test
  14258. });
  14259. cli.Get("/test");
  14260. ASSERT_TRUE(verify_callback_called)
  14261. << "Verify callback should have been called";
  14262. auto has_san = [&](SanType type, const std::string &value) {
  14263. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14264. return san.type == type && san.value == value;
  14265. });
  14266. };
  14267. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14268. << "sans() should report the dNSName SAN";
  14269. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14270. << "sans() should report the iPAddress SAN";
  14271. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14272. << "sans() must not report the dNSName SAN as an address";
  14273. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14274. << "sans() must not report the iPAddress SAN as a DNS name";
  14275. }
  14276. #endif
  14277. // mbedTLS-specific callback constructor test
  14278. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14279. #ifdef CPPHTTPLIB_SSL_ENABLED
  14280. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14282. ASSERT_TRUE(svr.is_valid());
  14283. // Set up a handler to verify client certificate is present
  14284. bool client_cert_verified = false;
  14285. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14286. // Verify that client certificate was provided
  14287. client_cert_verified = true;
  14288. res.set_content("success", "text/plain");
  14289. });
  14290. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14291. auto se = detail::scope_exit([&] {
  14292. svr.stop();
  14293. t.join();
  14294. ASSERT_FALSE(svr.is_running());
  14295. });
  14296. svr.wait_until_ready();
  14297. // Client with certificate
  14298. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14299. cli.enable_server_certificate_verification(false);
  14300. cli.set_connection_timeout(30);
  14301. auto res = cli.Get("/test");
  14302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14303. ASSERT_EQ(StatusCode::OK_200, res->status);
  14304. ASSERT_TRUE(client_cert_verified);
  14305. EXPECT_EQ("success", res->body);
  14306. }
  14307. #endif
  14308. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14309. // backends
  14310. #ifdef CPPHTTPLIB_SSL_ENABLED
  14311. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14312. using namespace httplib::tls;
  14313. // Test that when client CA cert file is provided,
  14314. // the server properly requests and validates client certificates
  14315. // Create a server with client authentication
  14316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14317. ASSERT_TRUE(svr.is_valid());
  14318. bool handler_called = false;
  14319. svr.Get("/test", [&](const Request &req, Response &res) {
  14320. handler_called = true;
  14321. // Verify that a client certificate was provided
  14322. auto cert = req.peer_cert();
  14323. ASSERT_TRUE(static_cast<bool>(cert));
  14324. // Get the issuer name
  14325. std::string issuer_str = cert.issuer_name();
  14326. ASSERT_FALSE(issuer_str.empty());
  14327. // The client certificate should be issued by our test CA
  14328. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14329. res.set_content("authenticated", "text/plain");
  14330. });
  14331. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14332. auto se = detail::scope_exit([&] {
  14333. svr.stop();
  14334. t.join();
  14335. ASSERT_FALSE(svr.is_running());
  14336. });
  14337. svr.wait_until_ready();
  14338. // Connect with a client certificate issued by the CA
  14339. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14340. cli.enable_server_certificate_verification(false);
  14341. cli.set_connection_timeout(30);
  14342. auto res = cli.Get("/test");
  14343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14344. ASSERT_EQ(StatusCode::OK_200, res->status);
  14345. ASSERT_TRUE(handler_called);
  14346. EXPECT_EQ("authenticated", res->body);
  14347. }
  14348. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14349. using namespace httplib::tls;
  14350. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14351. ASSERT_TRUE(svr.is_valid());
  14352. svr.Get("/test", [](const Request &, Response &res) {
  14353. res.set_content("ok", "text/plain");
  14354. });
  14355. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14356. auto se = detail::scope_exit([&] {
  14357. svr.stop();
  14358. t.join();
  14359. });
  14360. svr.wait_until_ready();
  14361. SSLClient cli(HOST, PORT);
  14362. cli.enable_server_certificate_verification(false);
  14363. cli.set_connection_timeout(30);
  14364. bool cert_checked = false;
  14365. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14366. if (ctx.cert) {
  14367. auto sans = ctx.sans();
  14368. // Test certificate may or may not have SANs - just verify the API
  14369. // works If SANs exist, verify the types are valid
  14370. for (const auto &san : sans) {
  14371. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14372. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14373. san.type == SanType::OTHER);
  14374. EXPECT_FALSE(san.value.empty());
  14375. }
  14376. cert_checked = true;
  14377. }
  14378. return true;
  14379. });
  14380. auto res = cli.Get("/test");
  14381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14382. EXPECT_TRUE(cert_checked);
  14383. }
  14384. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14385. using namespace httplib::tls;
  14386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14387. ASSERT_TRUE(svr.is_valid());
  14388. svr.Get("/test", [](const Request &, Response &res) {
  14389. res.set_content("ok", "text/plain");
  14390. });
  14391. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14392. auto se = detail::scope_exit([&] {
  14393. svr.stop();
  14394. t.join();
  14395. });
  14396. svr.wait_until_ready();
  14397. SSLClient cli(HOST, PORT);
  14398. cli.enable_server_certificate_verification(false);
  14399. cli.set_connection_timeout(30);
  14400. bool validity_checked = false;
  14401. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14402. if (ctx.cert) {
  14403. time_t not_before = 0, not_after = 0;
  14404. bool result = ctx.validity(not_before, not_after);
  14405. EXPECT_TRUE(result);
  14406. // Verify that not_before < now < not_after for a valid cert
  14407. time_t now = time(nullptr);
  14408. EXPECT_LT(not_before, now);
  14409. EXPECT_GT(not_after, now);
  14410. validity_checked = true;
  14411. }
  14412. return true;
  14413. });
  14414. auto res = cli.Get("/test");
  14415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14416. EXPECT_TRUE(validity_checked);
  14417. }
  14418. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14419. using namespace httplib::tls;
  14420. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14421. ASSERT_TRUE(svr.is_valid());
  14422. svr.Get("/test", [](const Request &, Response &res) {
  14423. res.set_content("ok", "text/plain");
  14424. });
  14425. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14426. auto se = detail::scope_exit([&] {
  14427. svr.stop();
  14428. t.join();
  14429. });
  14430. svr.wait_until_ready();
  14431. SSLClient cli(HOST, PORT);
  14432. cli.enable_server_certificate_verification(false);
  14433. cli.set_connection_timeout(30);
  14434. bool serial_checked = false;
  14435. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14436. if (ctx.cert) {
  14437. std::string serial = ctx.serial();
  14438. EXPECT_FALSE(serial.empty());
  14439. // Serial should be a hex string
  14440. for (char c : serial) {
  14441. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14442. (c >= 'a' && c <= 'f'));
  14443. }
  14444. serial_checked = true;
  14445. }
  14446. return true;
  14447. });
  14448. auto res = cli.Get("/test");
  14449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14450. EXPECT_TRUE(serial_checked);
  14451. }
  14452. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14453. // Test 1: Valid CA file - no error should be recorded
  14454. {
  14455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14456. CLIENT_CA_CERT_FILE);
  14457. ASSERT_TRUE(svr.is_valid());
  14458. // With valid setup, last_ssl_error should be 0
  14459. EXPECT_EQ(0, svr.ssl_last_error());
  14460. }
  14461. // Test 2: Invalid CA file content
  14462. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14463. {
  14464. // Create a temporary file with completely invalid content
  14465. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14466. {
  14467. std::ofstream ofs(temp_invalid_ca);
  14468. ofs << "This is not a certificate file at all\n";
  14469. ofs << "Just plain text content\n";
  14470. }
  14471. // Create server with invalid CA file
  14472. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14473. // Clean up temporary file
  14474. std::remove(temp_invalid_ca);
  14475. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14476. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14477. // Note: SSL_CTX_load_verify_locations typically fails first,
  14478. // but our error handling code path is still exercised
  14479. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14480. }
  14481. }
  14482. TEST(VerifyCallbackTest, VerifyContextFields) {
  14483. using namespace httplib::tls;
  14484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14485. ASSERT_TRUE(svr.is_valid());
  14486. svr.Get("/test", [](const Request &, Response &res) {
  14487. res.set_content("ok", "text/plain");
  14488. });
  14489. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14490. auto se = detail::scope_exit([&] {
  14491. svr.stop();
  14492. t.join();
  14493. });
  14494. svr.wait_until_ready();
  14495. SSLClient cli(HOST, PORT);
  14496. cli.enable_server_certificate_verification(false);
  14497. cli.set_connection_timeout(30);
  14498. int callback_count = 0;
  14499. bool saw_leaf_cert = false;
  14500. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14501. if (ctx.cert) {
  14502. callback_count++;
  14503. // We should see at least one certificate (the leaf)
  14504. std::string cn = ctx.subject_cn();
  14505. if (!cn.empty()) { saw_leaf_cert = true; }
  14506. // Verify context fields are populated
  14507. EXPECT_NE(ctx.session, nullptr);
  14508. EXPECT_GE(ctx.depth, 0);
  14509. }
  14510. return true;
  14511. });
  14512. auto res = cli.Get("/test");
  14513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14514. EXPECT_GT(callback_count, 0);
  14515. EXPECT_TRUE(saw_leaf_cert);
  14516. }
  14517. // A verifier that accepts runs alongside the built-in verification, and is the
  14518. // only check once that is turned off.
  14519. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14520. using namespace httplib::tls;
  14521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14522. ASSERT_TRUE(svr.is_valid());
  14523. svr.Get("/test", [](const Request &, Response &res) {
  14524. res.set_content("ok", "text/plain");
  14525. });
  14526. auto port = svr.bind_to_any_port(HOST);
  14527. thread t([&]() { svr.listen_after_bind(); });
  14528. auto se = detail::scope_exit([&] {
  14529. svr.stop();
  14530. t.join();
  14531. });
  14532. svr.wait_until_ready();
  14533. SSLClient cli(HOST, port);
  14534. cli.enable_server_hostname_verification(false);
  14535. auto calls = 0;
  14536. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14537. calls++;
  14538. return true;
  14539. });
  14540. // cert.pem is not trusted
  14541. auto res = cli.Get("/test");
  14542. ASSERT_FALSE(res);
  14543. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14544. EXPECT_GT(calls, 0);
  14545. cli.enable_server_certificate_verification(false);
  14546. res = cli.Get("/test");
  14547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14548. EXPECT_EQ("ok", res->body);
  14549. }
  14550. // A verifier belongs to the client that set it, not to the thread that set it.
  14551. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14552. using namespace httplib::tls;
  14553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14554. ASSERT_TRUE(svr.is_valid());
  14555. svr.Get("/test", [](const Request &, Response &res) {
  14556. res.set_content("ok", "text/plain");
  14557. });
  14558. auto port = svr.bind_to_any_port(HOST);
  14559. thread t([&]() { svr.listen_after_bind(); });
  14560. auto se = detail::scope_exit([&] {
  14561. svr.stop();
  14562. t.join();
  14563. });
  14564. svr.wait_until_ready();
  14565. auto rejecting_calls = 0;
  14566. SSLClient rejecting(HOST, port);
  14567. rejecting.enable_server_certificate_verification(false);
  14568. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14569. rejecting_calls++;
  14570. return false;
  14571. });
  14572. auto accepting_calls = 0;
  14573. SSLClient accepting(HOST, port);
  14574. accepting.enable_server_certificate_verification(false);
  14575. // Set on another thread than the requests below.
  14576. thread([&]() {
  14577. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14578. accepting_calls++;
  14579. return true;
  14580. });
  14581. }).join();
  14582. // Requested on another thread than the verifier was set on.
  14583. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14584. EXPECT_GT(rejecting_calls, 0);
  14585. auto res = accepting.Get("/test");
  14586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14587. EXPECT_GT(accepting_calls, 0);
  14588. }
  14589. // A verifier replaced while a handshake runs it lives until it returns.
  14590. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14591. using namespace httplib::tls;
  14592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14593. ASSERT_TRUE(svr.is_valid());
  14594. svr.Get("/test", [](const Request &, Response &res) {
  14595. res.set_content("ok", "text/plain");
  14596. });
  14597. auto port = svr.bind_to_any_port(HOST);
  14598. thread t([&]() { svr.listen_after_bind(); });
  14599. auto se = detail::scope_exit([&] {
  14600. svr.stop();
  14601. t.join();
  14602. });
  14603. svr.wait_until_ready();
  14604. SSLClient cli(HOST, port);
  14605. cli.enable_server_certificate_verification(false);
  14606. std::promise<void> entered;
  14607. std::promise<void> replaced;
  14608. auto replaced_future = replaced.get_future();
  14609. auto first_call = true;
  14610. // Long enough to live on the heap
  14611. std::string expected(64, 'v');
  14612. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14613. if (first_call) {
  14614. first_call = false;
  14615. entered.set_value();
  14616. replaced_future.wait();
  14617. }
  14618. return expected == std::string(64, 'v');
  14619. });
  14620. thread request([&]() {
  14621. auto res = cli.Get("/test");
  14622. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14623. });
  14624. entered.get_future().wait();
  14625. cli.set_server_certificate_verifier(
  14626. [](const VerifyContext &) { return true; });
  14627. replaced.set_value();
  14628. request.join();
  14629. }
  14630. // VerifyContext::session is the same handle the other tls:: functions take.
  14631. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14632. using namespace httplib::tls;
  14633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14634. ASSERT_TRUE(svr.is_valid());
  14635. svr.Get("/test", [](const Request &, Response &res) {
  14636. res.set_content("ok", "text/plain");
  14637. });
  14638. auto port = svr.bind_to_any_port(HOST);
  14639. thread t([&]() { svr.listen_after_bind(); });
  14640. auto se = detail::scope_exit([&] {
  14641. svr.stop();
  14642. t.join();
  14643. });
  14644. svr.wait_until_ready();
  14645. SSLClient cli(HOST, port);
  14646. cli.enable_server_certificate_verification(false);
  14647. session_t verifier_session = nullptr;
  14648. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14649. verifier_session = ctx.session;
  14650. return true;
  14651. });
  14652. session_t session_verifier_session = nullptr;
  14653. cli.set_session_verifier([&](session_t session) {
  14654. session_verifier_session = session;
  14655. return SSLVerifierResponse::NoDecisionMade;
  14656. });
  14657. auto res = cli.Get("/test");
  14658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14659. EXPECT_NE(nullptr, verifier_session);
  14660. EXPECT_EQ(session_verifier_session, verifier_session);
  14661. }
  14662. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14663. using httplib::tls::TlsError;
  14664. // Test that verify_error_to_string returns empty for success
  14665. std::string success_str = TlsError::verify_error_to_string(0);
  14666. EXPECT_TRUE(success_str.empty());
  14667. // Test that verify_error_to_string returns non-empty for error codes
  14668. // Using a common error code (certificate expired)
  14669. std::string error_str =
  14670. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14671. EXPECT_FALSE(error_str.empty());
  14672. }
  14673. TEST(SessionVerifierTest, CertificateAccepted) {
  14674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14675. ASSERT_TRUE(svr.is_valid());
  14676. svr.Get("/test", [](const Request &, Response &res) {
  14677. res.set_content("ok", "text/plain");
  14678. });
  14679. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14680. auto se = detail::scope_exit([&] {
  14681. svr.stop();
  14682. t.join();
  14683. });
  14684. svr.wait_until_ready();
  14685. SSLClient cli(HOST, PORT);
  14686. cli.enable_server_certificate_verification(false);
  14687. cli.set_connection_timeout(30);
  14688. bool callback_called = false;
  14689. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14690. EXPECT_NE(session, nullptr);
  14691. callback_called = true;
  14692. return SSLVerifierResponse::CertificateAccepted;
  14693. });
  14694. auto res = cli.Get("/test");
  14695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14696. EXPECT_EQ(200, res->status);
  14697. EXPECT_TRUE(callback_called);
  14698. }
  14699. TEST(SessionVerifierTest, CertificateRejected) {
  14700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14701. ASSERT_TRUE(svr.is_valid());
  14702. svr.Get("/test", [](const Request &, Response &res) {
  14703. res.set_content("ok", "text/plain");
  14704. });
  14705. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14706. auto se = detail::scope_exit([&] {
  14707. svr.stop();
  14708. t.join();
  14709. });
  14710. svr.wait_until_ready();
  14711. SSLClient cli(HOST, PORT);
  14712. cli.enable_server_certificate_verification(false);
  14713. cli.set_connection_timeout(30);
  14714. bool callback_called = false;
  14715. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14716. EXPECT_NE(session, nullptr);
  14717. callback_called = true;
  14718. return SSLVerifierResponse::CertificateRejected;
  14719. });
  14720. auto res = cli.Get("/test");
  14721. EXPECT_FALSE(res);
  14722. EXPECT_TRUE(callback_called);
  14723. }
  14724. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14726. ASSERT_TRUE(svr.is_valid());
  14727. svr.Get("/test", [](const Request &, Response &res) {
  14728. res.set_content("ok", "text/plain");
  14729. });
  14730. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14731. auto se = detail::scope_exit([&] {
  14732. svr.stop();
  14733. t.join();
  14734. });
  14735. svr.wait_until_ready();
  14736. // NoDecisionMade with verification disabled should succeed (no default check)
  14737. SSLClient cli(HOST, PORT);
  14738. cli.enable_server_certificate_verification(false);
  14739. cli.set_connection_timeout(30);
  14740. bool callback_called = false;
  14741. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14742. EXPECT_NE(session, nullptr);
  14743. callback_called = true;
  14744. return SSLVerifierResponse::NoDecisionMade;
  14745. });
  14746. auto res = cli.Get("/test");
  14747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14748. EXPECT_EQ(200, res->status);
  14749. EXPECT_TRUE(callback_called);
  14750. }
  14751. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14752. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14753. ASSERT_TRUE(svr.is_valid());
  14754. svr.Get("/test", [](const Request &, Response &res) {
  14755. res.set_content("ok", "text/plain");
  14756. });
  14757. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14758. auto se = detail::scope_exit([&] {
  14759. svr.stop();
  14760. t.join();
  14761. });
  14762. svr.wait_until_ready();
  14763. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14764. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14765. // so we only check that the request fails, not whether the callback was
  14766. // called.
  14767. SSLClient cli(HOST, PORT);
  14768. cli.enable_server_certificate_verification(true);
  14769. cli.set_connection_timeout(30);
  14770. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14771. EXPECT_NE(session, nullptr);
  14772. return SSLVerifierResponse::NoDecisionMade;
  14773. });
  14774. auto res = cli.Get("/test");
  14775. EXPECT_FALSE(res);
  14776. }
  14777. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14778. // Test SSL server using PemMemory constructor with client CA certificates
  14779. // Read PEM files
  14780. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14781. read_file(SERVER_CERT_FILE, server_cert_pem);
  14782. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14783. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14784. // Create SSLServer with PemMemory constructor including client CA
  14785. SSLServer::PemMemory server_pem = {
  14786. server_cert_pem.c_str(),
  14787. server_cert_pem.size(),
  14788. server_key_pem.c_str(),
  14789. server_key_pem.size(),
  14790. client_ca_pem.c_str(),
  14791. client_ca_pem.size(),
  14792. nullptr // no password for server key
  14793. };
  14794. SSLServer svr(server_pem);
  14795. ASSERT_TRUE(svr.is_valid());
  14796. // No SSL error should be recorded for valid setup
  14797. EXPECT_EQ(0, svr.ssl_last_error());
  14798. // Set up server endpoints
  14799. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14800. res.set_content("ok", "text/plain");
  14801. });
  14802. // Start server in a thread
  14803. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14804. svr.wait_until_ready();
  14805. // Connect with client certificate (using constructor with paths)
  14806. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14807. cli.enable_server_certificate_verification(false);
  14808. auto res = cli.Get("/test-pem-ca");
  14809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14810. EXPECT_EQ(200, res->status);
  14811. EXPECT_EQ("ok", res->body);
  14812. svr.stop();
  14813. server_thread.join();
  14814. }
  14815. #endif
  14816. #ifdef _WIN32
  14817. TEST(CleanupTest, WSACleanup) {
  14818. int ret = WSACleanup();
  14819. ASSERT_EQ(0, ret);
  14820. }
  14821. #endif
  14822. #ifndef CPPHTTPLIB_SSL_ENABLED
  14823. TEST(NoSSLSupport, SimpleInterface) {
  14824. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14825. }
  14826. #endif
  14827. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14828. TEST(InvalidScheme, SimpleInterface) {
  14829. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14830. }
  14831. #endif
  14832. TEST(NoScheme, SimpleInterface) {
  14833. Client cli("yahoo.com:80");
  14834. ASSERT_TRUE(cli.is_valid());
  14835. }
  14836. TEST(SendAPI, SimpleInterface_Online) {
  14837. Client cli("http://yahoo.com");
  14838. Request req;
  14839. req.method = "GET";
  14840. req.path = "/";
  14841. auto res = cli.send(req);
  14842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14843. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14844. }
  14845. TEST(SendAPI, WithParamsInRequest) {
  14846. Server svr;
  14847. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14848. EXPECT_TRUE(req.has_param("test"));
  14849. EXPECT_EQ("test_value", req.get_param_value("test"));
  14850. });
  14851. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14852. auto se = detail::scope_exit([&] {
  14853. svr.stop();
  14854. t.join();
  14855. ASSERT_FALSE(svr.is_running());
  14856. });
  14857. svr.wait_until_ready();
  14858. Client cli(HOST, PORT);
  14859. {
  14860. Request req;
  14861. req.method = "GET";
  14862. req.path = "/";
  14863. req.params.emplace("test", "test_value");
  14864. auto res = cli.send(req);
  14865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14866. }
  14867. {
  14868. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14870. }
  14871. }
  14872. TEST(ClientImplMethods, GetSocketTest) {
  14873. httplib::Server svr;
  14874. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14875. res.status = StatusCode::OK_200;
  14876. });
  14877. auto port = svr.bind_to_any_port("127.0.0.1");
  14878. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14879. auto se = detail::scope_exit([&] {
  14880. svr.stop();
  14881. thread.join();
  14882. ASSERT_FALSE(svr.is_running());
  14883. });
  14884. svr.wait_until_ready();
  14885. {
  14886. httplib::Client cli("127.0.0.1", port);
  14887. cli.set_keep_alive(true);
  14888. // Use the behavior of cpp-httplib of opening the connection
  14889. // only when the first request happens. If that changes,
  14890. // this test would be obsolete.
  14891. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14892. // This also implicitly tests the server. But other tests would fail much
  14893. // earlier than this one to be considered.
  14894. auto res = cli.Get("/");
  14895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14896. EXPECT_EQ(StatusCode::OK_200, res->status);
  14897. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14898. }
  14899. }
  14900. #ifdef CPPHTTPLIB_SSL_ENABLED
  14901. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14902. Client cli("http://yahoo.com");
  14903. auto res = cli.Get("/");
  14904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14905. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14906. cli.set_follow_location(true);
  14907. res = cli.Get("/");
  14908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14909. EXPECT_EQ(StatusCode::OK_200, res->status);
  14910. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14911. }
  14912. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14913. Client cli("https://yahoo.com");
  14914. auto res = cli.Get("/");
  14915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14916. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14917. cli.set_follow_location(true);
  14918. res = cli.Get("/");
  14919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14920. EXPECT_EQ(StatusCode::OK_200, res->status);
  14921. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14922. }
  14923. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14924. Client cli("https://yahoo.com");
  14925. auto res = cli.Get("/");
  14926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14927. ASSERT_FALSE(!res);
  14928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14929. ASSERT_FALSE(res == nullptr);
  14930. ASSERT_TRUE(res != nullptr);
  14931. EXPECT_EQ(Error::Success, res.error());
  14932. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14933. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14934. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14935. cli.set_follow_location(true);
  14936. res = cli.Get("/");
  14937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14938. EXPECT_EQ(Error::Success, res.error());
  14939. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14940. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14941. EXPECT_EQ(StatusCode::OK_200, res->status);
  14942. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14943. }
  14944. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14945. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14946. Client cli("https://cdnjs.cloudflare.com");
  14947. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14948. Headers{{"Accept-Encoding", "br"}});
  14949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14950. EXPECT_EQ(StatusCode::OK_200, res->status);
  14951. EXPECT_EQ(287630U, res->body.size());
  14952. EXPECT_EQ("application/javascript; charset=utf-8",
  14953. res->get_header_value("Content-Type"));
  14954. }
  14955. #endif
  14956. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14957. #undef REDIR_HOST // Silence compiler warning
  14958. #define REDIR_HOST "https://httpbingo.org"
  14959. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14960. Client cli(REDIR_HOST);
  14961. cli.set_follow_location(true);
  14962. auto res =
  14963. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14965. EXPECT_EQ(StatusCode::OK_200, res->status);
  14966. }
  14967. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14968. Client cli(REDIR_HOST);
  14969. cli.set_follow_location(true);
  14970. Params params;
  14971. params.emplace("url", "http://example.com");
  14972. params.emplace("status_code", "302");
  14973. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14975. EXPECT_EQ(StatusCode::OK_200, res->status);
  14976. }
  14977. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14978. Client cli(REDIR_HOST);
  14979. cli.set_follow_location(true);
  14980. Params params;
  14981. params.emplace("url", "http://example.com");
  14982. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14984. EXPECT_EQ(StatusCode::OK_200, res->status);
  14985. }
  14986. TEST(HttpToHttpsRedirectTest, CertFile) {
  14987. auto ssl_port = PORT + 1;
  14988. Server svr;
  14989. ASSERT_TRUE(svr.is_valid());
  14990. svr.Get("/index", [&](const Request &, Response &res) {
  14991. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14992. "/index");
  14993. svr.stop();
  14994. });
  14995. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14996. ASSERT_TRUE(ssl_svr.is_valid());
  14997. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14998. res.set_content("test", "text/plain");
  14999. ssl_svr.stop();
  15000. });
  15001. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15002. thread t2 =
  15003. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15004. auto se = detail::scope_exit([&] {
  15005. t2.join();
  15006. t.join();
  15007. ASSERT_FALSE(svr.is_running());
  15008. });
  15009. svr.wait_until_ready();
  15010. ssl_svr.wait_until_ready();
  15011. Client cli("127.0.0.1", PORT);
  15012. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15013. cli.enable_server_certificate_verification(true);
  15014. cli.set_follow_location(true);
  15015. cli.set_connection_timeout(30);
  15016. auto res = cli.Get("/index");
  15017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15018. ASSERT_EQ(StatusCode::OK_200, res->status);
  15019. }
  15020. TEST(SSLClientRedirectTest, CertFile) {
  15021. auto ssl_port = PORT + 1;
  15022. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15023. ASSERT_TRUE(ssl_svr1.is_valid());
  15024. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15025. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15026. "/index");
  15027. ssl_svr1.stop();
  15028. });
  15029. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15030. ASSERT_TRUE(ssl_svr2.is_valid());
  15031. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15032. res.set_content("test", "text/plain");
  15033. ssl_svr2.stop();
  15034. });
  15035. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15036. thread t2 =
  15037. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15038. auto se = detail::scope_exit([&] {
  15039. t2.join();
  15040. t.join();
  15041. ASSERT_FALSE(ssl_svr1.is_running());
  15042. });
  15043. ssl_svr1.wait_until_ready();
  15044. ssl_svr2.wait_until_ready();
  15045. SSLClient cli("127.0.0.1", PORT);
  15046. std::string cert;
  15047. read_file(SERVER_CERT2_FILE, cert);
  15048. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15049. cli.enable_server_certificate_verification(true);
  15050. cli.set_follow_location(true);
  15051. cli.set_connection_timeout(30);
  15052. auto res = cli.Get("/index");
  15053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15054. ASSERT_EQ(StatusCode::OK_200, res->status);
  15055. }
  15056. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15057. // another port, so the client follows it with a new client.
  15058. static Result GetThroughTlsRedirectToDifferentPort(
  15059. const std::function<void(SSLClient &)> &setup,
  15060. const char *target_cert = SERVER_CERT2_FILE,
  15061. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15062. auto ssl_port = PORT + 1;
  15063. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15064. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15065. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15066. "/index");
  15067. });
  15068. SSLServer ssl_svr2(target_cert, target_key);
  15069. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15070. res.set_content("test", "text/plain");
  15071. });
  15072. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15073. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15074. auto se = detail::scope_exit([&] {
  15075. ssl_svr2.stop();
  15076. ssl_svr1.stop();
  15077. t2.join();
  15078. t.join();
  15079. });
  15080. ssl_svr1.wait_until_ready();
  15081. ssl_svr2.wait_until_ready();
  15082. SSLClient cli("127.0.0.1", PORT);
  15083. cli.set_follow_location(true);
  15084. cli.set_connection_timeout(30);
  15085. setup(cli);
  15086. return cli.Get("/index");
  15087. }
  15088. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15089. auto calls = 0;
  15090. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15091. cli.enable_server_certificate_verification(false);
  15092. // Accept the first server only.
  15093. cli.set_session_verifier([&](tls::session_t) {
  15094. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15095. : SSLVerifierResponse::CertificateRejected;
  15096. });
  15097. });
  15098. ASSERT_FALSE(res);
  15099. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15100. EXPECT_EQ(2, calls);
  15101. }
  15102. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15103. std::string pinned;
  15104. auto res = GetThroughTlsRedirectToDifferentPort(
  15105. [&](SSLClient &cli) {
  15106. cli.enable_server_certificate_verification(false);
  15107. // Pin the first certificate seen.
  15108. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15109. if (pinned.empty()) { pinned = ctx.serial(); }
  15110. return ctx.serial() == pinned;
  15111. });
  15112. },
  15113. // A certificate other than the first server's.
  15114. SERVER_CERT_FILE);
  15115. EXPECT_FALSE(res);
  15116. EXPECT_FALSE(pinned.empty());
  15117. }
  15118. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15119. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15120. std::string cert;
  15121. read_file(SERVER_CERT2_FILE, cert);
  15122. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15123. });
  15124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15125. EXPECT_EQ(StatusCode::OK_200, res->status);
  15126. }
  15127. // The target's certificate is signed by the root CA, which the first server's
  15128. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15129. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15130. auto res = GetThroughTlsRedirectToDifferentPort(
  15131. [](SSLClient &cli) {
  15132. std::string root_ca, cert;
  15133. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15134. read_file(SERVER_CERT2_FILE, cert);
  15135. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15136. cli.load_ca_cert_store(cert.data(), cert.size());
  15137. cli.enable_server_hostname_verification(false);
  15138. },
  15139. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15141. EXPECT_EQ(StatusCode::OK_200, res->status);
  15142. }
  15143. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15144. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15145. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15146. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15147. auto res = GetThroughTlsRedirectToDifferentPort(
  15148. [](SSLClient &cli) {
  15149. std::string root_ca, cert;
  15150. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15151. read_file(SERVER_CERT2_FILE, cert);
  15152. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15153. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15154. cli.enable_server_hostname_verification(false);
  15155. },
  15156. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15157. ASSERT_FALSE(res);
  15158. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15159. }
  15160. #endif
  15161. #endif
  15162. #ifdef CPPHTTPLIB_SSL_ENABLED
  15163. // Test that set_ca_cert_store() skips system certs (consistent with
  15164. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15165. // should be trusted - system certs should NOT be loaded.
  15166. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15167. // Load a specific cert that is NOT a system CA cert
  15168. std::string cert;
  15169. read_file(SERVER_CERT2_FILE, cert);
  15170. SSLClient cli("google.com");
  15171. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15172. cli.enable_server_certificate_verification(true);
  15173. // This should FAIL because:
  15174. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15175. // 2. System certs should NOT be loaded when custom store is set
  15176. // If system certs WERE loaded, this would succeed
  15177. auto res = cli.Get("/");
  15178. ASSERT_FALSE(res);
  15179. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15180. }
  15181. // Same as above, but through the native store handle path. Regression test:
  15182. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15183. // merged system certs into the user-provided store.
  15184. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15185. std::string cert;
  15186. read_file(SERVER_CERT2_FILE, cert);
  15187. SSLClient cli("google.com");
  15188. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15189. cli.enable_server_certificate_verification(true);
  15190. auto res = cli.Get("/");
  15191. ASSERT_FALSE(res);
  15192. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15193. }
  15194. // A custom store set via the native handle must still verify a server whose
  15195. // cert it does contain.
  15196. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15197. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15198. ASSERT_TRUE(svr.is_valid());
  15199. svr.Get("/test", [&](const Request &, Response &res) {
  15200. res.set_content("test", "text/plain");
  15201. });
  15202. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15203. auto se = detail::scope_exit([&] {
  15204. svr.stop();
  15205. t.join();
  15206. ASSERT_FALSE(svr.is_running());
  15207. });
  15208. svr.wait_until_ready();
  15209. SSLClient cli("127.0.0.1", PORT);
  15210. std::string cert;
  15211. read_file(SERVER_CERT2_FILE, cert);
  15212. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15213. cli.enable_server_certificate_verification(true);
  15214. cli.set_connection_timeout(30);
  15215. auto res = cli.Get("/test");
  15216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15217. ASSERT_EQ(StatusCode::OK_200, res->status);
  15218. }
  15219. // CA certs loaded through the universal Client must be transferred to the
  15220. // client created internally for following an HTTPS redirect. Regression test:
  15221. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15222. // the CA data for redirect transfer.
  15223. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15224. auto ssl_port = PORT + 1;
  15225. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15226. ASSERT_TRUE(ssl_svr1.is_valid());
  15227. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15228. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15229. "/index");
  15230. });
  15231. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15232. ASSERT_TRUE(ssl_svr2.is_valid());
  15233. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15234. res.set_content("test", "text/plain");
  15235. });
  15236. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15237. thread t2 =
  15238. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15239. auto se = detail::scope_exit([&] {
  15240. ssl_svr2.stop();
  15241. ssl_svr1.stop();
  15242. t2.join();
  15243. t.join();
  15244. ASSERT_FALSE(ssl_svr1.is_running());
  15245. });
  15246. ssl_svr1.wait_until_ready();
  15247. ssl_svr2.wait_until_ready();
  15248. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15249. std::string cert;
  15250. read_file(SERVER_CERT2_FILE, cert);
  15251. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15252. cli.enable_server_certificate_verification(true);
  15253. cli.set_follow_location(true);
  15254. cli.set_connection_timeout(30);
  15255. auto res = cli.Get("/index");
  15256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15257. ASSERT_EQ(StatusCode::OK_200, res->status);
  15258. }
  15259. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15260. // so a host signed by a system CA verifies even though a custom CA is set
  15261. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15262. std::string cert;
  15263. read_file(SERVER_CERT2_FILE, cert);
  15264. SSLClient cli("google.com");
  15265. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15266. cli.enable_system_ca(true);
  15267. cli.enable_server_certificate_verification(true);
  15268. auto res = cli.Get("/");
  15269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15270. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15271. }
  15272. // The custom CA remains effective when combined with the system CA
  15273. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15274. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15275. ASSERT_TRUE(svr.is_valid());
  15276. svr.Get("/test", [&](const Request &, Response &res) {
  15277. res.set_content("test", "text/plain");
  15278. });
  15279. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15280. auto se = detail::scope_exit([&] {
  15281. svr.stop();
  15282. t.join();
  15283. ASSERT_FALSE(svr.is_running());
  15284. });
  15285. svr.wait_until_ready();
  15286. SSLClient cli("127.0.0.1", PORT);
  15287. std::string cert;
  15288. read_file(SERVER_CERT2_FILE, cert);
  15289. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15290. cli.enable_system_ca(true);
  15291. cli.enable_server_certificate_verification(true);
  15292. cli.set_connection_timeout(30);
  15293. auto res = cli.Get("/test");
  15294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15295. ASSERT_EQ(StatusCode::OK_200, res->status);
  15296. }
  15297. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15298. // skip chain verification entirely (only the certificate identity was
  15299. // checked), so a server presenting an untrusted certificate with a matching
  15300. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15301. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15302. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15303. ASSERT_TRUE(svr.is_valid());
  15304. svr.Get("/test", [&](const Request &, Response &res) {
  15305. res.set_content("test", "text/plain");
  15306. });
  15307. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15308. auto se = detail::scope_exit([&] {
  15309. svr.stop();
  15310. t.join();
  15311. ASSERT_FALSE(svr.is_running());
  15312. });
  15313. svr.wait_until_ready();
  15314. SSLClient cli("127.0.0.1", PORT);
  15315. std::string cert;
  15316. // A trusted CA that did not sign the server certificate. The server cert
  15317. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15318. // this connection.
  15319. read_file(CLIENT_CA_CERT_FILE, cert);
  15320. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15321. cli.enable_server_certificate_verification(true);
  15322. cli.set_connection_timeout(30);
  15323. auto res = cli.Get("/test");
  15324. ASSERT_FALSE(res);
  15325. }
  15326. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15327. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15328. // CA that failed to come through fails verification instead of trusting them.
  15329. // (wolfSSL does not list the system CAs it loaded.)
  15330. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15331. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15332. ASSERT_TRUE(svr.is_valid());
  15333. auto port = svr.bind_to_any_port("127.0.0.1");
  15334. ASSERT_LT(0, port);
  15335. thread t = thread([&] { svr.listen_after_bind(); });
  15336. auto se = detail::scope_exit([&] {
  15337. svr.stop();
  15338. t.join();
  15339. ASSERT_FALSE(svr.is_running());
  15340. });
  15341. svr.wait_until_ready();
  15342. // The CAs a client trusts once its first request has loaded them
  15343. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15344. Client cli("https://127.0.0.1:" + std::to_string(port));
  15345. setup(cli);
  15346. cli.Get("/");
  15347. return tls::get_ca_names(cli.tls_context()).size();
  15348. };
  15349. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15350. EXPECT_EQ(0u,
  15351. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15352. }
  15353. #endif
  15354. // enable_system_ca(false) prevents system CA loading entirely
  15355. TEST(SSLClientTest, DisableSystemCa_Online) {
  15356. SSLClient cli("google.com");
  15357. cli.enable_system_ca(false);
  15358. cli.enable_server_certificate_verification(true);
  15359. auto res = cli.Get("/");
  15360. ASSERT_FALSE(res);
  15361. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15362. // itself when the CA chain is empty
  15363. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15364. res.error() == Error::SSLConnection);
  15365. }
  15366. // The universal Client forwards enable_system_ca()
  15367. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15368. std::string cert;
  15369. read_file(SERVER_CERT2_FILE, cert);
  15370. Client cli("https://google.com");
  15371. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15372. cli.enable_system_ca(true);
  15373. cli.enable_server_certificate_verification(true);
  15374. auto res = cli.Get("/");
  15375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15376. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15377. }
  15378. // The system CA policy must carry over to the client created internally for
  15379. // following a cross-host HTTPS redirect
  15380. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15381. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15382. ASSERT_TRUE(svr.is_valid());
  15383. svr.Get("/index", [&](const Request &, Response &res) {
  15384. res.set_redirect("https://www.google.com/");
  15385. });
  15386. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15387. auto se = detail::scope_exit([&] {
  15388. svr.stop();
  15389. t.join();
  15390. ASSERT_FALSE(svr.is_running());
  15391. });
  15392. svr.wait_until_ready();
  15393. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15394. std::string cert;
  15395. read_file(SERVER_CERT2_FILE, cert);
  15396. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15397. cli.enable_system_ca(true);
  15398. cli.enable_server_certificate_verification(true);
  15399. cli.set_follow_location(true);
  15400. cli.set_connection_timeout(30);
  15401. // Receiving any response proves the redirect client completed the TLS
  15402. // handshake with a system-CA-signed host
  15403. auto res = cli.Get("/index");
  15404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15405. }
  15406. TEST(MultipartFormDataTest, LargeData) {
  15407. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15408. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15409. const ContentReader &content_reader) {
  15410. if (req.is_multipart_form_data()) {
  15411. std::vector<FormData> items;
  15412. content_reader(
  15413. [&](const FormData &file) {
  15414. items.push_back(file);
  15415. return true;
  15416. },
  15417. [&](const char *data, size_t data_length) {
  15418. items.back().content.append(data, data_length);
  15419. return true;
  15420. });
  15421. EXPECT_TRUE(std::string(items[0].name) == "document");
  15422. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15423. EXPECT_TRUE(items[0].filename == "2MB_data");
  15424. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15425. EXPECT_TRUE(items[1].name == "hello");
  15426. EXPECT_TRUE(items[1].content == "world");
  15427. EXPECT_TRUE(items[1].filename == "");
  15428. EXPECT_TRUE(items[1].content_type == "");
  15429. } else {
  15430. std::string body;
  15431. content_reader([&](const char *data, size_t data_length) {
  15432. body.append(data, data_length);
  15433. return true;
  15434. });
  15435. }
  15436. });
  15437. auto port = svr.bind_to_any_port(HOST);
  15438. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15439. auto se = detail::scope_exit([&] {
  15440. svr.stop();
  15441. t.join();
  15442. ASSERT_FALSE(svr.is_running());
  15443. });
  15444. svr.wait_until_ready();
  15445. {
  15446. std::string data(1024 * 1024 * 2, '.');
  15447. std::stringstream buffer;
  15448. buffer << data;
  15449. SSLClient cli(HOST, port);
  15450. cli.enable_server_certificate_verification(false);
  15451. UploadFormDataItems items{
  15452. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15453. {"hello", "world", "", ""},
  15454. };
  15455. auto res = cli.Post("/post", items);
  15456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15457. ASSERT_EQ(StatusCode::OK_200, res->status);
  15458. }
  15459. }
  15460. TEST(MultipartFormDataTest, DataProviderItems) {
  15461. std::random_device seed_gen;
  15462. std::mt19937 random(seed_gen());
  15463. std::string rand1;
  15464. rand1.resize(1000);
  15465. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15466. std::string rand2;
  15467. rand2.resize(3000);
  15468. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15469. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15470. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15471. const ContentReader &content_reader) {
  15472. ASSERT_FALSE(req.is_multipart_form_data());
  15473. std::string body;
  15474. content_reader([&](const char *data, size_t data_length) {
  15475. body.append(data, data_length);
  15476. return true;
  15477. });
  15478. EXPECT_EQ(body, "");
  15479. });
  15480. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15481. const ContentReader &content_reader) {
  15482. ASSERT_TRUE(req.is_multipart_form_data());
  15483. std::vector<FormData> items;
  15484. content_reader(
  15485. [&](const FormData &file) {
  15486. items.push_back(file);
  15487. return true;
  15488. },
  15489. [&](const char *data, size_t data_length) {
  15490. items.back().content.append(data, data_length);
  15491. return true;
  15492. });
  15493. ASSERT_TRUE(items.size() == 2);
  15494. EXPECT_EQ(std::string(items[0].name), "name1");
  15495. EXPECT_EQ(items[0].content, "Testing123");
  15496. EXPECT_EQ(items[0].filename, "filename1");
  15497. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15498. EXPECT_EQ(items[1].name, "name2");
  15499. EXPECT_EQ(items[1].content, "Testing456");
  15500. EXPECT_EQ(items[1].filename, "");
  15501. EXPECT_EQ(items[1].content_type, "");
  15502. });
  15503. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15504. const ContentReader &content_reader) {
  15505. ASSERT_TRUE(req.is_multipart_form_data());
  15506. std::vector<FormData> items;
  15507. content_reader(
  15508. [&](const FormData &file) {
  15509. items.push_back(file);
  15510. return true;
  15511. },
  15512. [&](const char *data, size_t data_length) {
  15513. items.back().content.append(data, data_length);
  15514. return true;
  15515. });
  15516. ASSERT_TRUE(items.size() == 2);
  15517. EXPECT_EQ(items[0].name, "name3");
  15518. EXPECT_EQ(items[0].content, rand1);
  15519. EXPECT_EQ(items[0].filename, "filename3");
  15520. EXPECT_EQ(items[0].content_type, "");
  15521. EXPECT_EQ(items[1].name, "name4");
  15522. EXPECT_EQ(items[1].content, rand2);
  15523. EXPECT_EQ(items[1].filename, "filename4");
  15524. EXPECT_EQ(items[1].content_type, "");
  15525. });
  15526. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15527. const ContentReader &content_reader) {
  15528. ASSERT_TRUE(req.is_multipart_form_data());
  15529. std::vector<FormData> items;
  15530. content_reader(
  15531. [&](const FormData &file) {
  15532. items.push_back(file);
  15533. return true;
  15534. },
  15535. [&](const char *data, size_t data_length) {
  15536. items.back().content.append(data, data_length);
  15537. return true;
  15538. });
  15539. ASSERT_TRUE(items.size() == 4);
  15540. EXPECT_EQ(std::string(items[0].name), "name1");
  15541. EXPECT_EQ(items[0].content, "Testing123");
  15542. EXPECT_EQ(items[0].filename, "filename1");
  15543. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15544. EXPECT_EQ(items[1].name, "name2");
  15545. EXPECT_EQ(items[1].content, "Testing456");
  15546. EXPECT_EQ(items[1].filename, "");
  15547. EXPECT_EQ(items[1].content_type, "");
  15548. EXPECT_EQ(items[2].name, "name3");
  15549. EXPECT_EQ(items[2].content, rand1);
  15550. EXPECT_EQ(items[2].filename, "filename3");
  15551. EXPECT_EQ(items[2].content_type, "");
  15552. EXPECT_EQ(items[3].name, "name4");
  15553. EXPECT_EQ(items[3].content, rand2);
  15554. EXPECT_EQ(items[3].filename, "filename4");
  15555. EXPECT_EQ(items[3].content_type, "");
  15556. });
  15557. auto port = svr.bind_to_any_port("localhost");
  15558. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15559. auto se = detail::scope_exit([&] {
  15560. svr.stop();
  15561. t.join();
  15562. ASSERT_FALSE(svr.is_running());
  15563. });
  15564. svr.wait_until_ready();
  15565. {
  15566. SSLClient cli("localhost", port);
  15567. cli.enable_server_certificate_verification(false);
  15568. UploadFormDataItems items{
  15569. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15570. {"name2", "Testing456", "", ""}, // not a file
  15571. };
  15572. {
  15573. auto res = cli.Post("/post-none", {}, {}, {});
  15574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15575. ASSERT_EQ(StatusCode::OK_200, res->status);
  15576. }
  15577. FormDataProviderItems providers;
  15578. {
  15579. auto res =
  15580. cli.Post("/post-items", {}, items, providers); // empty providers
  15581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15582. ASSERT_EQ(StatusCode::OK_200, res->status);
  15583. }
  15584. providers.push_back({"name3",
  15585. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15586. // test the offset is given correctly at each step
  15587. if (!offset)
  15588. sink.os.write(rand1.data(), 30);
  15589. else if (offset == 30)
  15590. sink.os.write(rand1.data() + 30, 300);
  15591. else if (offset == 330)
  15592. sink.os.write(rand1.data() + 330, 670);
  15593. else if (offset == rand1.size())
  15594. sink.done();
  15595. return true;
  15596. },
  15597. "filename3",
  15598. {}});
  15599. providers.push_back({"name4",
  15600. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15601. // test the offset is given correctly at each step
  15602. if (!offset)
  15603. sink.os.write(rand2.data(), 2000);
  15604. else if (offset == 2000)
  15605. sink.os.write(rand2.data() + 2000, 1);
  15606. else if (offset == 2001)
  15607. sink.os.write(rand2.data() + 2001, 999);
  15608. else if (offset == rand2.size())
  15609. sink.done();
  15610. return true;
  15611. },
  15612. "filename4",
  15613. {}});
  15614. {
  15615. auto res = cli.Post("/post-providers", {}, {}, providers);
  15616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15617. ASSERT_EQ(StatusCode::OK_200, res->status);
  15618. }
  15619. {
  15620. auto res = cli.Post("/post-both", {}, items, providers);
  15621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15622. ASSERT_EQ(StatusCode::OK_200, res->status);
  15623. }
  15624. }
  15625. }
  15626. TEST(MultipartFormDataTest, BadHeader) {
  15627. Server svr;
  15628. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15629. res.set_content("ok", "text/plain");
  15630. });
  15631. thread t = thread([&] { svr.listen(HOST, PORT); });
  15632. auto se = detail::scope_exit([&] {
  15633. svr.stop();
  15634. t.join();
  15635. ASSERT_FALSE(svr.is_running());
  15636. });
  15637. svr.wait_until_ready();
  15638. const std::string body =
  15639. "This is the preamble. It is to be ignored, though it\r\n"
  15640. "is a handy place for composition agents to include an\r\n"
  15641. "explanatory note to non-MIME conformant readers.\r\n"
  15642. "\r\n"
  15643. "\r\n"
  15644. "--simple boundary\r\n"
  15645. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15646. ": BAD...\r\n"
  15647. "\r\n"
  15648. "value1\r\n"
  15649. "--simple boundary\r\n"
  15650. "Content-Disposition: form-data; name=\"field2\"; "
  15651. "filename=\"example.txt\"\r\n"
  15652. "\r\n"
  15653. "value2\r\n"
  15654. "--simple boundary--\r\n"
  15655. "This is the epilogue. It is also to be ignored.\r\n";
  15656. std::string content_type =
  15657. R"(multipart/form-data; boundary="simple boundary")";
  15658. Client cli(HOST, PORT);
  15659. auto res = cli.Post("/post", body, content_type.c_str());
  15660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15661. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15662. }
  15663. TEST(MultipartFormDataTest, WithPreamble) {
  15664. Server svr;
  15665. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15666. res.set_content("ok", "text/plain");
  15667. });
  15668. thread t = thread([&] { svr.listen(HOST, PORT); });
  15669. auto se = detail::scope_exit([&] {
  15670. svr.stop();
  15671. t.join();
  15672. ASSERT_FALSE(svr.is_running());
  15673. });
  15674. svr.wait_until_ready();
  15675. const std::string body =
  15676. "This is the preamble. It is to be ignored, though it\r\n"
  15677. "is a handy place for composition agents to include an\r\n"
  15678. "explanatory note to non-MIME conformant readers.\r\n"
  15679. "\r\n"
  15680. "\r\n"
  15681. "--simple boundary\r\n"
  15682. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15683. "\r\n"
  15684. "value1\r\n"
  15685. "--simple boundary\r\n"
  15686. "Content-Disposition: form-data; name=\"field2\"; "
  15687. "filename=\"example.txt\"\r\n"
  15688. "\r\n"
  15689. "value2\r\n"
  15690. "--simple boundary--\r\n"
  15691. "This is the epilogue. It is also to be ignored.\r\n";
  15692. std::string content_type =
  15693. R"(multipart/form-data; boundary="simple boundary")";
  15694. Client cli(HOST, PORT);
  15695. auto res = cli.Post("/post", body, content_type.c_str());
  15696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15697. EXPECT_EQ(StatusCode::OK_200, res->status);
  15698. }
  15699. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15701. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15702. const ContentReader &content_reader) {
  15703. if (req.is_multipart_form_data()) {
  15704. std::vector<FormData> items;
  15705. content_reader(
  15706. [&](const FormData &file) {
  15707. items.push_back(file);
  15708. return true;
  15709. },
  15710. [&](const char *data, size_t data_length) {
  15711. items.back().content.append(data, data_length);
  15712. return true;
  15713. });
  15714. EXPECT_TRUE(std::string(items[0].name) == "document");
  15715. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15716. EXPECT_TRUE(items[0].filename == "2MB_data");
  15717. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15718. EXPECT_TRUE(items[1].name == "hello");
  15719. EXPECT_TRUE(items[1].content == "world");
  15720. EXPECT_TRUE(items[1].filename == "");
  15721. EXPECT_TRUE(items[1].content_type == "");
  15722. } else {
  15723. std::string body;
  15724. content_reader([&](const char *data, size_t data_length) {
  15725. body.append(data, data_length);
  15726. return true;
  15727. });
  15728. }
  15729. });
  15730. auto port = svr.bind_to_any_port("localhost");
  15731. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15732. auto se = detail::scope_exit([&] {
  15733. svr.stop();
  15734. t.join();
  15735. ASSERT_FALSE(svr.is_running());
  15736. });
  15737. svr.wait_until_ready();
  15738. {
  15739. std::string data(1024 * 1024 * 2, '.');
  15740. std::stringstream buffer;
  15741. buffer << data;
  15742. SSLClient cli("localhost", port);
  15743. cli.enable_server_certificate_verification(false);
  15744. UploadFormDataItems items{
  15745. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15746. {"hello", "world", "", ""},
  15747. };
  15748. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15750. ASSERT_EQ(StatusCode::OK_200, res->status);
  15751. }
  15752. }
  15753. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15754. std::string data(1024 * 1024 * 2, '&');
  15755. std::stringstream buffer;
  15756. buffer << data;
  15757. Client cli("https://localhost:8080");
  15758. UploadFormDataItems items{
  15759. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15760. {"hello", "world", "", ""},
  15761. };
  15762. for (const char &c : " \t\r\n") {
  15763. auto res =
  15764. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15765. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15766. ASSERT_FALSE(res);
  15767. }
  15768. }
  15769. TEST(MultipartFormDataTest, PutFormData) {
  15770. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15771. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15772. const ContentReader &content_reader) {
  15773. if (req.is_multipart_form_data()) {
  15774. std::vector<FormData> items;
  15775. content_reader(
  15776. [&](const FormData &file) {
  15777. items.push_back(file);
  15778. return true;
  15779. },
  15780. [&](const char *data, size_t data_length) {
  15781. items.back().content.append(data, data_length);
  15782. return true;
  15783. });
  15784. EXPECT_TRUE(std::string(items[0].name) == "document");
  15785. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15786. EXPECT_TRUE(items[0].filename == "2MB_data");
  15787. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15788. EXPECT_TRUE(items[1].name == "hello");
  15789. EXPECT_TRUE(items[1].content == "world");
  15790. EXPECT_TRUE(items[1].filename == "");
  15791. EXPECT_TRUE(items[1].content_type == "");
  15792. } else {
  15793. std::string body;
  15794. content_reader([&](const char *data, size_t data_length) {
  15795. body.append(data, data_length);
  15796. return true;
  15797. });
  15798. }
  15799. });
  15800. auto port = svr.bind_to_any_port("localhost");
  15801. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15802. auto se = detail::scope_exit([&] {
  15803. svr.stop();
  15804. t.join();
  15805. ASSERT_FALSE(svr.is_running());
  15806. });
  15807. svr.wait_until_ready();
  15808. {
  15809. std::string data(1024 * 1024 * 2, '&');
  15810. std::stringstream buffer;
  15811. buffer << data;
  15812. SSLClient cli("localhost", port);
  15813. cli.enable_server_certificate_verification(false);
  15814. UploadFormDataItems items{
  15815. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15816. {"hello", "world", "", ""},
  15817. };
  15818. auto res = cli.Put("/put", items);
  15819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15820. ASSERT_EQ(StatusCode::OK_200, res->status);
  15821. }
  15822. }
  15823. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15824. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15825. svr.Put("/put_customboundary",
  15826. [&](const Request &req, const Response & /*res*/,
  15827. const ContentReader &content_reader) {
  15828. if (req.is_multipart_form_data()) {
  15829. std::vector<FormData> items;
  15830. content_reader(
  15831. [&](const FormData &file) {
  15832. items.push_back(file);
  15833. return true;
  15834. },
  15835. [&](const char *data, size_t data_length) {
  15836. items.back().content.append(data, data_length);
  15837. return true;
  15838. });
  15839. EXPECT_TRUE(std::string(items[0].name) == "document");
  15840. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15841. EXPECT_TRUE(items[0].filename == "2MB_data");
  15842. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15843. EXPECT_TRUE(items[1].name == "hello");
  15844. EXPECT_TRUE(items[1].content == "world");
  15845. EXPECT_TRUE(items[1].filename == "");
  15846. EXPECT_TRUE(items[1].content_type == "");
  15847. } else {
  15848. std::string body;
  15849. content_reader([&](const char *data, size_t data_length) {
  15850. body.append(data, data_length);
  15851. return true;
  15852. });
  15853. }
  15854. });
  15855. auto port = svr.bind_to_any_port("localhost");
  15856. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15857. auto se = detail::scope_exit([&] {
  15858. svr.stop();
  15859. t.join();
  15860. ASSERT_FALSE(svr.is_running());
  15861. });
  15862. svr.wait_until_ready();
  15863. {
  15864. std::string data(1024 * 1024 * 2, '&');
  15865. std::stringstream buffer;
  15866. buffer << data;
  15867. SSLClient cli("localhost", port);
  15868. cli.enable_server_certificate_verification(false);
  15869. UploadFormDataItems items{
  15870. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15871. {"hello", "world", "", ""},
  15872. };
  15873. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15875. ASSERT_EQ(StatusCode::OK_200, res->status);
  15876. }
  15877. }
  15878. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15879. std::string data(1024 * 1024 * 2, '&');
  15880. std::stringstream buffer;
  15881. buffer << data;
  15882. Client cli("https://localhost:8080");
  15883. cli.enable_server_certificate_verification(false);
  15884. UploadFormDataItems items{
  15885. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15886. {"hello", "world", "", ""},
  15887. };
  15888. for (const char &c : " \t\r\n") {
  15889. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15890. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15891. ASSERT_FALSE(res);
  15892. }
  15893. }
  15894. TEST(MultipartFormDataTest, AlternateFilename) {
  15895. auto handled = false;
  15896. Server svr;
  15897. svr.Post("/test", [&](const Request &req, Response &res) {
  15898. ASSERT_EQ(2u, req.form.files.size());
  15899. ASSERT_EQ(1u, req.form.fields.size());
  15900. // Test files
  15901. const auto &file1 = req.form.get_file("file1");
  15902. ASSERT_EQ("file1", file1.name);
  15903. ASSERT_EQ("A.txt", file1.filename);
  15904. ASSERT_EQ("text/plain", file1.content_type);
  15905. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15906. const auto &file2 = req.form.get_file("file2");
  15907. ASSERT_EQ("file2", file2.name);
  15908. ASSERT_EQ("a.html", file2.filename);
  15909. ASSERT_EQ("text/html", file2.content_type);
  15910. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15911. file2.content);
  15912. // Test text field
  15913. const auto &text = req.form.get_field("text");
  15914. ASSERT_EQ("text default", text);
  15915. res.set_content("ok", "text/plain");
  15916. handled = true;
  15917. });
  15918. thread t = thread([&] { svr.listen(HOST, PORT); });
  15919. auto se = detail::scope_exit([&] {
  15920. svr.stop();
  15921. t.join();
  15922. ASSERT_FALSE(svr.is_running());
  15923. ASSERT_TRUE(handled);
  15924. });
  15925. svr.wait_until_ready();
  15926. auto req = "POST /test HTTP/1.1\r\n"
  15927. "Host: localhost\r\n"
  15928. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15929. "Content-Length: 399\r\n"
  15930. "\r\n"
  15931. "----------\r\n"
  15932. "Content-Disposition: form-data; name=\"text\"\r\n"
  15933. "\r\n"
  15934. "text default\r\n"
  15935. "----------\r\n"
  15936. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15937. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15938. "Content-Type: text/plain\r\n"
  15939. "\r\n"
  15940. "Content of a.txt.\r\n"
  15941. "\r\n"
  15942. "----------\r\n"
  15943. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15944. "\"a.html\"\r\n"
  15945. "Content-Type: text/html\r\n"
  15946. "\r\n"
  15947. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15948. "\r\n"
  15949. "------------\r\n";
  15950. ASSERT_TRUE(send_request(1, req));
  15951. }
  15952. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15953. auto handled = false;
  15954. Server svr;
  15955. svr.Post("/test", [&](const Request &req, Response &res) {
  15956. // Case-insensitive "utf-8''" prefix with a long value
  15957. const auto &file = req.form.get_file("file1");
  15958. ASSERT_EQ("file1", file.name);
  15959. // 8000 chars exercises both the Content-Disposition parser and the
  15960. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15961. // Prior to the fix, std::regex_match on this header would cause O(N)
  15962. // stack recursion in libstdc++, leading to SIGSEGV.
  15963. std::string expected_filename(8000, 'A');
  15964. ASSERT_EQ(expected_filename, file.filename);
  15965. res.set_content("ok", "text/plain");
  15966. handled = true;
  15967. });
  15968. thread t = thread([&] { svr.listen(HOST, PORT); });
  15969. auto se = detail::scope_exit([&] {
  15970. svr.stop();
  15971. t.join();
  15972. ASSERT_FALSE(svr.is_running());
  15973. ASSERT_TRUE(handled);
  15974. });
  15975. svr.wait_until_ready();
  15976. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15977. // Regression test for GHSA-qq6v-r583-3h69
  15978. std::string long_filename(8000, 'A');
  15979. std::string body = "----------\r\n"
  15980. "Content-Disposition: form-data; name=\"file1\"; "
  15981. "filename*=\"Utf-8''" +
  15982. long_filename +
  15983. "\"\r\n"
  15984. "\r\n"
  15985. "hello\r\n"
  15986. "------------\r\n";
  15987. auto req = "POST /test HTTP/1.1\r\n"
  15988. "Host: localhost\r\n"
  15989. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15990. "Content-Length: " +
  15991. std::to_string(body.size()) + "\r\n\r\n" + body;
  15992. ASSERT_TRUE(send_request(1, req));
  15993. }
  15994. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15995. auto handled = false;
  15996. Server svr;
  15997. svr.Post("/test", [&](const Request &req, Response &) {
  15998. ASSERT_EQ(2u, req.form.fields.size());
  15999. const auto &text1 = req.form.get_field("text1");
  16000. ASSERT_EQ("text1", text1);
  16001. const auto &text2 = req.form.get_field("text2");
  16002. ASSERT_EQ("text2", text2);
  16003. handled = true;
  16004. });
  16005. thread t = thread([&] { svr.listen(HOST, PORT); });
  16006. auto se = detail::scope_exit([&] {
  16007. svr.stop();
  16008. t.join();
  16009. ASSERT_FALSE(svr.is_running());
  16010. ASSERT_TRUE(handled);
  16011. });
  16012. svr.wait_until_ready();
  16013. auto req = "POST /test HTTP/1.1\r\n"
  16014. "Host: localhost\r\n"
  16015. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16016. "Content-Length: 146\r\n"
  16017. "\r\n----------\r\n"
  16018. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16019. "\r\n"
  16020. "text1"
  16021. "\r\n----------\r\n"
  16022. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16023. "\r\n"
  16024. "text2"
  16025. "\r\n------------";
  16026. std::string response;
  16027. ASSERT_TRUE(send_request(1, req, &response));
  16028. ASSERT_EQ("200", response.substr(9, 3));
  16029. }
  16030. TEST(MultipartFormDataTest, ContentLength) {
  16031. auto handled = false;
  16032. Server svr;
  16033. svr.Post("/test", [&](const Request &req, Response &) {
  16034. ASSERT_EQ(2u, req.form.fields.size());
  16035. const auto &text1 = req.form.get_field("text1");
  16036. ASSERT_EQ("text1", text1);
  16037. const auto &text2 = req.form.get_field("text2");
  16038. ASSERT_EQ("text2", text2);
  16039. handled = true;
  16040. });
  16041. thread t = thread([&] { svr.listen(HOST, PORT); });
  16042. auto se = detail::scope_exit([&] {
  16043. svr.stop();
  16044. t.join();
  16045. ASSERT_FALSE(svr.is_running());
  16046. ASSERT_TRUE(handled);
  16047. });
  16048. svr.wait_until_ready();
  16049. auto req = "POST /test HTTP/1.1\r\n"
  16050. "Host: localhost\r\n"
  16051. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16052. "Content-Length: 167\r\n"
  16053. "\r\n----------\r\n"
  16054. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16055. "Content-Length: 5\r\n"
  16056. "\r\n"
  16057. "text1"
  16058. "\r\n----------\r\n"
  16059. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16060. "\r\n"
  16061. "text2"
  16062. "\r\n------------\r\n";
  16063. std::string response;
  16064. ASSERT_TRUE(send_request(1, req, &response));
  16065. ASSERT_EQ("200", response.substr(9, 3));
  16066. }
  16067. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16068. auto handled = false;
  16069. Server svr;
  16070. svr.Post("/test", [&](const Request &req, Response &) {
  16071. ASSERT_EQ(2u, req.form.fields.size());
  16072. const auto &text1 = req.form.get_field("text1");
  16073. ASSERT_EQ("text1", text1);
  16074. // TODO: Add header access for text fields if needed
  16075. const auto &text2 = req.form.get_field("text2");
  16076. ASSERT_EQ("text2", text2);
  16077. // TODO: Header access for text fields needs to be implemented
  16078. // auto &headers = it->second.headers;
  16079. // ASSERT_EQ(3U, headers.size());
  16080. // auto custom_header = headers.find("x-whatever");
  16081. // ASSERT_TRUE(custom_header != headers.end());
  16082. // ASSERT_NE("customvalue", custom_header->second);
  16083. // ASSERT_EQ("CustomValue", custom_header->second);
  16084. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16085. handled = true;
  16086. });
  16087. thread t = thread([&] { svr.listen(HOST, PORT); });
  16088. auto se = detail::scope_exit([&] {
  16089. svr.stop();
  16090. t.join();
  16091. ASSERT_FALSE(svr.is_running());
  16092. ASSERT_TRUE(handled);
  16093. });
  16094. svr.wait_until_ready();
  16095. auto req = "POST /test HTTP/1.1\r\n"
  16096. "Host: localhost\r\n"
  16097. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16098. "Content-Length: 232\r\n"
  16099. "\r\n----------\r\n"
  16100. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16101. "Content-Length: 5\r\n"
  16102. "X-Test: 1\r\n"
  16103. "\r\n"
  16104. "text1"
  16105. "\r\n----------\r\n"
  16106. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16107. "Content-Type: text/plain\r\n"
  16108. "X-Whatever: CustomValue\r\n"
  16109. "\r\n"
  16110. "text2"
  16111. "\r\n------------\r\n"
  16112. "That should be disregarded. Not even read";
  16113. std::string response;
  16114. ASSERT_TRUE(send_request(1, req, &response));
  16115. ASSERT_EQ("200", response.substr(9, 3));
  16116. }
  16117. TEST(MultipartFormDataTest, LargeHeader) {
  16118. auto handled = false;
  16119. Server svr;
  16120. svr.Post("/test", [&](const Request &req, Response &) {
  16121. ASSERT_EQ(1u, req.form.fields.size());
  16122. const auto &text = req.form.get_field("name1");
  16123. ASSERT_EQ("text1", text);
  16124. handled = true;
  16125. });
  16126. thread t = thread([&] { svr.listen(HOST, PORT); });
  16127. auto se = detail::scope_exit([&] {
  16128. svr.stop();
  16129. t.join();
  16130. ASSERT_FALSE(svr.is_running());
  16131. ASSERT_TRUE(handled);
  16132. });
  16133. svr.wait_until_ready();
  16134. auto boundary = std::string("cpp-httplib-multipart-data");
  16135. std::string content = "--" + boundary +
  16136. "\r\n"
  16137. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16138. "\r\n"
  16139. "text1\r\n"
  16140. "--" +
  16141. boundary + "--\r\n";
  16142. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16143. "Host: localhost\r\n"
  16144. "Content-Type: multipart/form-data;boundary=" +
  16145. boundary +
  16146. "\r\n"
  16147. "Content-Length: " +
  16148. std::to_string(content.size()) +
  16149. "\r\n"
  16150. "Dummy-Header: ";
  16151. std::string header_suffix = "\r\n"
  16152. "\r\n";
  16153. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16154. size_t header_dummy_size =
  16155. read_buff_size -
  16156. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16157. auto header_dummy = std::string(header_dummy_size, '@');
  16158. auto req = header_prefix + header_dummy + header_suffix + content;
  16159. std::string response;
  16160. ASSERT_TRUE(send_request(1, req, &response));
  16161. ASSERT_EQ("200", response.substr(9, 3));
  16162. }
  16163. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16164. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16165. // (not chunked Transfer-Encoding) after the streaming refactor.
  16166. auto handled = false;
  16167. Server svr;
  16168. svr.Post("/upload", [&](const Request &req, Response &res) {
  16169. auto cl_it = req.headers.find("Content-Length");
  16170. EXPECT_TRUE(cl_it != req.headers.end());
  16171. auto te_it = req.headers.find("Transfer-Encoding");
  16172. EXPECT_TRUE(te_it == req.headers.end());
  16173. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16174. res.set_content("ok", "text/plain");
  16175. handled = true;
  16176. });
  16177. auto port = svr.bind_to_any_port(HOST);
  16178. auto t = thread([&] { svr.listen_after_bind(); });
  16179. auto se = detail::scope_exit([&] {
  16180. svr.stop();
  16181. t.join();
  16182. ASSERT_FALSE(svr.is_running());
  16183. ASSERT_TRUE(handled);
  16184. });
  16185. svr.wait_until_ready();
  16186. UploadFormDataItems items = {
  16187. {"field1", "hello", "", "text/plain"},
  16188. {"file1", "world", "test.txt", "application/octet-stream"},
  16189. };
  16190. Client cli(HOST, port);
  16191. auto res = cli.Post("/upload", {}, items);
  16192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16193. EXPECT_EQ(StatusCode::OK_200, res->status);
  16194. }
  16195. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16196. // Verify that make_multipart_content_provider coalesces many small segments
  16197. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16198. constexpr size_t kItemCount = 1000;
  16199. UploadFormDataItems items;
  16200. items.reserve(kItemCount);
  16201. for (size_t i = 0; i < kItemCount; i++) {
  16202. items.push_back(
  16203. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16204. }
  16205. const std::string boundary = "----test-boundary";
  16206. auto content_length = detail::get_multipart_content_length(items, boundary);
  16207. auto provider = detail::make_multipart_content_provider(items, boundary);
  16208. // Drive the provider the same way write_content_with_progress does
  16209. size_t write_count = 0;
  16210. size_t total_bytes = 0;
  16211. DataSink sink;
  16212. size_t offset = 0;
  16213. sink.write = [&](const char *d, size_t l) -> bool {
  16214. (void)d;
  16215. write_count++;
  16216. total_bytes += l;
  16217. offset += l;
  16218. return true;
  16219. };
  16220. sink.is_writable = []() -> bool { return true; };
  16221. while (offset < content_length) {
  16222. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16223. }
  16224. EXPECT_EQ(content_length, total_bytes);
  16225. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16226. // With buffering into 64KB blocks, write_count should be much smaller.
  16227. auto segment_count = 3 * kItemCount + 1;
  16228. EXPECT_LT(write_count, segment_count / 10);
  16229. }
  16230. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16231. // Integration test: send many UploadFormDataItems and verify the server
  16232. // receives all of them correctly (#2410).
  16233. constexpr size_t kItemCount = 500;
  16234. auto handled = false;
  16235. Server svr;
  16236. svr.Post("/upload", [&](const Request &req, Response &res) {
  16237. EXPECT_EQ(kItemCount, req.form.fields.size());
  16238. for (size_t i = 0; i < kItemCount; i++) {
  16239. auto key = "field" + std::to_string(i);
  16240. auto val = "value" + std::to_string(i);
  16241. auto it = req.form.fields.find(key);
  16242. if (it != req.form.fields.end()) {
  16243. EXPECT_EQ(val, it->second.content);
  16244. } else {
  16245. ADD_FAILURE() << "Missing field: " << key;
  16246. }
  16247. }
  16248. res.set_content("ok", "text/plain");
  16249. handled = true;
  16250. });
  16251. auto port = svr.bind_to_any_port(HOST);
  16252. auto t = thread([&] { svr.listen_after_bind(); });
  16253. auto se = detail::scope_exit([&] {
  16254. svr.stop();
  16255. t.join();
  16256. ASSERT_FALSE(svr.is_running());
  16257. ASSERT_TRUE(handled);
  16258. });
  16259. svr.wait_until_ready();
  16260. UploadFormDataItems items;
  16261. items.reserve(kItemCount);
  16262. for (size_t i = 0; i < kItemCount; i++) {
  16263. items.push_back(
  16264. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16265. }
  16266. Client cli(HOST, port);
  16267. auto res = cli.Post("/upload", items);
  16268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16269. EXPECT_EQ(StatusCode::OK_200, res->status);
  16270. }
  16271. TEST(MultipartFormDataTest, MakeFileProvider) {
  16272. // Verify make_file_provider sends a file's contents correctly.
  16273. const std::string file_content(4096, 'Z');
  16274. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16275. {
  16276. std::ofstream ofs(tmp_path, std::ios::binary);
  16277. ofs.write(file_content.data(),
  16278. static_cast<std::streamsize>(file_content.size()));
  16279. }
  16280. auto handled = false;
  16281. Server svr;
  16282. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16283. const ContentReader &content_reader) {
  16284. ASSERT_TRUE(req.is_multipart_form_data());
  16285. std::vector<FormData> items;
  16286. content_reader(
  16287. [&](const FormData &file) {
  16288. items.push_back(file);
  16289. return true;
  16290. },
  16291. [&](const char *data, size_t data_length) {
  16292. items.back().content.append(data, data_length);
  16293. return true;
  16294. });
  16295. ASSERT_EQ(1u, items.size());
  16296. EXPECT_EQ("myfile", items[0].name);
  16297. EXPECT_EQ("data.bin", items[0].filename);
  16298. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16299. EXPECT_EQ(file_content, items[0].content);
  16300. handled = true;
  16301. });
  16302. auto port = svr.bind_to_any_port(HOST);
  16303. auto t = thread([&] { svr.listen_after_bind(); });
  16304. auto se = detail::scope_exit([&] {
  16305. svr.stop();
  16306. t.join();
  16307. ASSERT_FALSE(svr.is_running());
  16308. ASSERT_TRUE(handled);
  16309. std::remove(tmp_path.c_str());
  16310. });
  16311. svr.wait_until_ready();
  16312. FormDataProviderItems providers;
  16313. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16314. "application/octet-stream"));
  16315. Client cli(HOST, port);
  16316. auto res = cli.Post("/upload", {}, {}, providers);
  16317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16318. EXPECT_EQ(StatusCode::OK_200, res->status);
  16319. }
  16320. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16321. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16322. // (100) headers is rejected with a 400 Bad Request response.
  16323. Server svr;
  16324. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16325. res.set_content("ok", "text/plain");
  16326. });
  16327. thread t = thread([&] { svr.listen(HOST, PORT); });
  16328. auto se = detail::scope_exit([&] {
  16329. svr.stop();
  16330. t.join();
  16331. ASSERT_FALSE(svr.is_running());
  16332. });
  16333. svr.wait_until_ready();
  16334. // Build a multipart part with 101 custom headers (exceeding
  16335. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16336. std::stringstream body;
  16337. body << "--simpleboundary\r\n"
  16338. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16339. for (int i = 0; i < 101; i++) {
  16340. body << "X-Custom-Header-" << i << ": value\r\n";
  16341. }
  16342. body << "\r\n"
  16343. << "value1\r\n"
  16344. << "--simpleboundary--\r\n";
  16345. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16346. Client cli(HOST, PORT);
  16347. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16349. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16350. }
  16351. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16352. // A body that never contains the declared boundary must not be accumulated
  16353. // while the parser waits for it. Buffering it would also make every read
  16354. // rescan everything seen so far, which is quadratic in the body size.
  16355. Server svr;
  16356. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16357. res.set_content("ok", "text/plain");
  16358. });
  16359. auto port = svr.bind_to_any_port(HOST);
  16360. thread t = thread([&] { svr.listen_after_bind(); });
  16361. auto se = detail::scope_exit([&] {
  16362. svr.stop();
  16363. t.join();
  16364. ASSERT_FALSE(svr.is_running());
  16365. });
  16366. svr.wait_until_ready();
  16367. Client cli(HOST, port);
  16368. cli.set_read_timeout(60, 0);
  16369. cli.set_write_timeout(60, 0);
  16370. // '-' is the worst case: it matches the first character of the boundary, so
  16371. // every position has to be checked against it.
  16372. auto post_dashes = [&](size_t size) {
  16373. const std::string body(size, '-');
  16374. auto start = std::chrono::steady_clock::now();
  16375. auto res =
  16376. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16377. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16378. std::chrono::steady_clock::now() - start)
  16379. .count();
  16380. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16381. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16382. return ms;
  16383. };
  16384. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16385. // Windows.
  16386. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16387. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16388. // Comparing the two sizes rather than checking an absolute duration keeps
  16389. // this meaningful across build types and CI load, both of which move the
  16390. // absolute numbers by more than an order of magnitude. Four times the bytes
  16391. // costs about four times the time when parsing is linear, and about sixteen
  16392. // times when the body is buffered and rescanned.
  16393. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16394. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16395. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16396. << "ms, which suggests the body is being buffered and rescanned";
  16397. }
  16398. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16399. // A boundary can only be followed by CRLF or by "--", so anything else is
  16400. // malformed no matter what comes next. The parser must say so right away
  16401. // instead of buffering the rest of the declared body.
  16402. Server svr;
  16403. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16404. res.set_content("ok", "text/plain");
  16405. });
  16406. auto port = svr.bind_to_any_port(HOST);
  16407. thread t = thread([&] { svr.listen_after_bind(); });
  16408. auto se = detail::scope_exit([&] {
  16409. svr.stop();
  16410. t.join();
  16411. ASSERT_FALSE(svr.is_running());
  16412. });
  16413. svr.wait_until_ready();
  16414. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16415. // buffers instead of failing would still be waiting for the remaining bytes.
  16416. const std::string body = "--zzzz\r\n"
  16417. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16418. "\r\n"
  16419. "text1"
  16420. "\r\n--zzzzXX";
  16421. const std::string req = "POST /post HTTP/1.1\r\n"
  16422. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16423. "Content-Length: 1048576\r\n"
  16424. "\r\n" +
  16425. body;
  16426. std::string response;
  16427. ASSERT_TRUE(send_request(3, req, &response, port));
  16428. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16429. EXPECT_EQ("400", response.substr(9, 3));
  16430. }
  16431. // Posts a multipart body split into two writes, so that the server sees the
  16432. // split at whatever offset the caller chose, and expects the single "text1"
  16433. // field to come through.
  16434. static void expect_split_multipart_ok(const std::string &body1,
  16435. const std::string &body2) {
  16436. auto handled = false;
  16437. Server svr;
  16438. svr.Post("/post", [&](const Request &req, Response &) {
  16439. EXPECT_EQ(1u, req.form.fields.size());
  16440. EXPECT_EQ("text1", req.form.get_field("text1"));
  16441. handled = true;
  16442. });
  16443. auto port = svr.bind_to_any_port(HOST);
  16444. thread t = thread([&] { svr.listen_after_bind(); });
  16445. auto se = detail::scope_exit([&] {
  16446. svr.stop();
  16447. t.join();
  16448. ASSERT_FALSE(svr.is_running());
  16449. ASSERT_TRUE(handled);
  16450. });
  16451. svr.wait_until_ready();
  16452. // "Connection: close" makes the server close once it has answered, so the
  16453. // response drain ends immediately instead of idling until the read timeout.
  16454. const std::string head =
  16455. "POST /post HTTP/1.1\r\n"
  16456. "Host: localhost\r\n"
  16457. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16458. "Connection: close\r\n"
  16459. "Content-Length: " +
  16460. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16461. std::string response;
  16462. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16463. ASSERT_GE(response.size(), 12u) << "no response";
  16464. EXPECT_EQ("200", response.substr(9, 3));
  16465. }
  16466. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16467. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16468. // ignored, including when it does not arrive in the same read as the
  16469. // close-delimiter itself.
  16470. expect_split_multipart_ok("--zzzz\r\n"
  16471. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16472. "\r\n"
  16473. "text1"
  16474. "\r\n--zzzz--",
  16475. "\r\nthis epilogue must be ignored\r\n");
  16476. }
  16477. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16478. // The initial boundary may be preceded by a preamble of any length and may
  16479. // straddle a read boundary. Discarding data while waiting for it must not
  16480. // throw away a partial boundary sitting at the end of the buffer.
  16481. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16482. "zz\r\n"
  16483. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16484. "\r\n"
  16485. "text1"
  16486. "\r\n--zzzz--\r\n");
  16487. }
  16488. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16489. // The received boundary was only checked for being non-empty, so it could be
  16490. // as long as a header is allowed to be. The parser scans the body for
  16491. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16492. // costs a nearly full comparison at nearly every position, making the
  16493. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16494. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16495. Server svr;
  16496. svr.Post("/post", [](const Request &req, Response &res) {
  16497. EXPECT_EQ(1u, req.form.fields.size());
  16498. EXPECT_EQ("text1", req.form.get_field("text1"));
  16499. res.set_content("ok", "text/plain");
  16500. });
  16501. auto port = svr.bind_to_any_port(HOST);
  16502. thread t = thread([&] { svr.listen_after_bind(); });
  16503. auto se = detail::scope_exit([&] {
  16504. svr.stop();
  16505. t.join();
  16506. ASSERT_FALSE(svr.is_running());
  16507. });
  16508. svr.wait_until_ready();
  16509. Client cli(HOST, port);
  16510. auto post_with_boundary_of_length = [&](size_t len) {
  16511. const std::string boundary(len, 'a');
  16512. const std::string body =
  16513. "--" + boundary +
  16514. "\r\n"
  16515. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16516. "\r\n"
  16517. "text1"
  16518. "\r\n--" +
  16519. boundary + "--\r\n";
  16520. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16521. };
  16522. auto res = post_with_boundary_of_length(70);
  16523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16524. EXPECT_EQ(StatusCode::OK_200, res->status);
  16525. res = post_with_boundary_of_length(71);
  16526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16527. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16528. }
  16529. TEST(MakeFileBodyTest, Basic) {
  16530. const std::string file_content(4096, 'Z');
  16531. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16532. {
  16533. std::ofstream ofs(tmp_path, std::ios::binary);
  16534. ofs.write(file_content.data(),
  16535. static_cast<std::streamsize>(file_content.size()));
  16536. }
  16537. auto handled = false;
  16538. Server svr;
  16539. svr.Post("/upload", [&](const Request &req, Response &res) {
  16540. EXPECT_EQ(file_content, req.body);
  16541. handled = true;
  16542. res.status = StatusCode::OK_200;
  16543. });
  16544. auto port = svr.bind_to_any_port(HOST);
  16545. auto t = thread([&] { svr.listen_after_bind(); });
  16546. auto se = detail::scope_exit([&] {
  16547. svr.stop();
  16548. t.join();
  16549. ASSERT_FALSE(svr.is_running());
  16550. ASSERT_TRUE(handled);
  16551. std::remove(tmp_path.c_str());
  16552. });
  16553. svr.wait_until_ready();
  16554. auto fb = make_file_body(tmp_path);
  16555. ASSERT_GT(fb.first, 0u);
  16556. Client cli(HOST, port);
  16557. auto res =
  16558. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16560. EXPECT_EQ(StatusCode::OK_200, res->status);
  16561. }
  16562. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16563. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16564. {
  16565. std::ofstream ofs(path, std::ios::binary);
  16566. const std::string content(100, 'A');
  16567. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16568. }
  16569. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16570. auto body = make_file_body(path);
  16571. ASSERT_EQ(100u, body.first);
  16572. ASSERT_TRUE(static_cast<bool>(body.second));
  16573. // Rewritten shorter after its length was measured - and, on a server, after
  16574. // that length has already gone out as Content-Length.
  16575. {
  16576. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16577. const std::string content(10, 'A');
  16578. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16579. }
  16580. std::string written;
  16581. DataSink sink;
  16582. sink.write = [&](const char *d, size_t l) {
  16583. written.append(d, l);
  16584. return true;
  16585. };
  16586. // The provider has to report failure. write_content_with_progress() advances
  16587. // its offset only by what was written, so a provider that returns true
  16588. // without completing the length it promised is called again straight away,
  16589. // and again.
  16590. EXPECT_FALSE(body.second(0, body.first, sink));
  16591. EXPECT_EQ(std::string(10, 'A'), written);
  16592. }
  16593. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16594. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16595. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16596. {
  16597. std::ofstream ofs(path, std::ios::binary);
  16598. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16599. }
  16600. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16601. auto body = make_file_body(path);
  16602. ASSERT_EQ(content.size(), body.first);
  16603. ASSERT_TRUE(static_cast<bool>(body.second));
  16604. std::string written;
  16605. DataSink sink;
  16606. sink.write = [&](const char *d, size_t l) {
  16607. written.append(d, l);
  16608. return true;
  16609. };
  16610. EXPECT_TRUE(body.second(0, body.first, sink));
  16611. EXPECT_EQ(content, written);
  16612. }
  16613. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16614. static constexpr unsigned int number_of_tasks{1000000};
  16615. std::atomic_uint count{0};
  16616. std::unique_ptr<TaskQueue> task_queue{
  16617. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16618. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16619. auto queued = task_queue->enqueue(
  16620. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16621. EXPECT_TRUE(queued);
  16622. }
  16623. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16624. task_queue->shutdown();
  16625. #else
  16626. EXPECT_NO_THROW(task_queue->shutdown());
  16627. #endif
  16628. EXPECT_EQ(number_of_tasks, count.load());
  16629. }
  16630. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16631. static constexpr unsigned int number_of_tasks{1000000};
  16632. static constexpr unsigned int qlimit{2};
  16633. unsigned int queued_count{0};
  16634. std::atomic_uint count{0};
  16635. std::unique_ptr<TaskQueue> task_queue{
  16636. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16637. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16638. if (task_queue->enqueue(
  16639. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16640. queued_count++;
  16641. }
  16642. }
  16643. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16644. task_queue->shutdown();
  16645. #else
  16646. EXPECT_NO_THROW(task_queue->shutdown());
  16647. #endif
  16648. EXPECT_EQ(queued_count, count.load());
  16649. EXPECT_TRUE(queued_count <= number_of_tasks);
  16650. EXPECT_TRUE(queued_count >= qlimit);
  16651. }
  16652. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16653. // Use a short idle timeout so a dynamic thread spawns, times out and
  16654. // exits during the test, and the pool keeps working afterwards.
  16655. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16656. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16657. /*idle_timeout_sec=*/1}};
  16658. std::atomic_uint count{0};
  16659. std::condition_variable cv;
  16660. std::mutex mtx;
  16661. bool release = false;
  16662. // Block the base thread so the second task spawns a dynamic thread.
  16663. EXPECT_TRUE(task_queue->enqueue([&] {
  16664. std::unique_lock<std::mutex> lock(mtx);
  16665. while (!release) {
  16666. cv.wait(lock);
  16667. }
  16668. count++;
  16669. }));
  16670. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16671. // Let the dynamic thread finish its task and exceed the idle timeout.
  16672. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16673. {
  16674. std::unique_lock<std::mutex> lock(mtx);
  16675. release = true;
  16676. }
  16677. cv.notify_all();
  16678. // The pool must still accept and run tasks after the dynamic thread exited.
  16679. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16680. task_queue->shutdown();
  16681. EXPECT_EQ(3u, count.load());
  16682. }
  16683. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16684. static constexpr size_t number_of_tasks{32};
  16685. std::unique_ptr<TaskQueue> task_queue{
  16686. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16687. // Let the base threads go idle so the burst below finds them waiting.
  16688. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16689. std::mutex mtx;
  16690. std::condition_variable cv;
  16691. size_t running = 0;
  16692. bool release = false;
  16693. for (size_t i = 0; i < number_of_tasks; i++) {
  16694. EXPECT_TRUE(task_queue->enqueue([&] {
  16695. std::unique_lock<std::mutex> lock(mtx);
  16696. running++;
  16697. cv.notify_all();
  16698. cv.wait(lock, [&] { return release; });
  16699. }));
  16700. }
  16701. {
  16702. std::unique_lock<std::mutex> lock(mtx);
  16703. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16704. [&] { return running == number_of_tasks; }));
  16705. release = true;
  16706. }
  16707. cv.notify_all();
  16708. task_queue->shutdown();
  16709. }
  16710. TEST(TaskQueueTest, MaxQueuedRequests) {
  16711. static constexpr unsigned int qlimit{3};
  16712. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16713. std::condition_variable sem_cv;
  16714. std::mutex sem_mtx;
  16715. int credits = 0;
  16716. bool queued;
  16717. /* Fill up the queue with tasks that will block until we give them credits to
  16718. * complete. */
  16719. for (unsigned int n = 0; n <= qlimit;) {
  16720. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16721. std::unique_lock<std::mutex> lock(sem_mtx);
  16722. while (credits <= 0) {
  16723. sem_cv.wait(lock);
  16724. }
  16725. /* Consume the credit and signal the test code if they are all gone. */
  16726. if (--credits == 0) { sem_cv.notify_one(); }
  16727. });
  16728. if (n < qlimit) {
  16729. /* The first qlimit enqueues must succeed. */
  16730. EXPECT_TRUE(queued);
  16731. } else {
  16732. /* The last one will succeed only when the worker thread
  16733. * starts and dequeues the first blocking task. Although
  16734. * not necessary for the correctness of this test, we sleep for
  16735. * a short while to avoid busy waiting. */
  16736. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16737. }
  16738. if (queued) { n++; }
  16739. }
  16740. /* Further enqueues must fail since the queue is full. */
  16741. for (auto i = 0; i < 4; i++) {
  16742. queued = task_queue->enqueue([] {});
  16743. EXPECT_FALSE(queued);
  16744. }
  16745. /* Give the credits to allow the previous tasks to complete. */
  16746. {
  16747. std::unique_lock<std::mutex> lock(sem_mtx);
  16748. credits += qlimit + 1;
  16749. }
  16750. sem_cv.notify_all();
  16751. /* Wait for all the credits to be consumed. */
  16752. {
  16753. std::unique_lock<std::mutex> lock(sem_mtx);
  16754. while (credits > 0) {
  16755. sem_cv.wait(lock);
  16756. }
  16757. }
  16758. /* Check that we are able again to enqueue at least qlimit tasks. */
  16759. for (unsigned int i = 0; i < qlimit; i++) {
  16760. queued = task_queue->enqueue([] {});
  16761. EXPECT_TRUE(queued);
  16762. }
  16763. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16764. task_queue->shutdown();
  16765. #else
  16766. EXPECT_NO_THROW(task_queue->shutdown());
  16767. #endif
  16768. }
  16769. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16770. Server svr;
  16771. std::string method;
  16772. std::string body;
  16773. auto has_content_length = false;
  16774. auto has_transfer_encoding = false;
  16775. std::atomic<int> bad_requests{0};
  16776. // Leftover body bytes get parsed as a malformed request and answered with
  16777. // 400
  16778. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16779. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16780. });
  16781. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16782. res.set_redirect("/down", StatusCode::SeeOther_303);
  16783. });
  16784. svr.Get("/down", [&](const Request &req, Response &res) {
  16785. method = req.method;
  16786. body = req.body;
  16787. has_content_length = req.has_header("Content-Length");
  16788. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16789. res.set_content("ok", "text/plain");
  16790. });
  16791. auto port = svr.bind_to_any_port(HOST);
  16792. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16793. auto se = detail::scope_exit([&] {
  16794. svr.stop();
  16795. thread.join();
  16796. ASSERT_FALSE(svr.is_running());
  16797. });
  16798. svr.wait_until_ready();
  16799. const std::string payload = "SECRET-BODY";
  16800. auto check = [&](Client &cli, const Result &res) {
  16801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16802. EXPECT_EQ(StatusCode::OK_200, res->status);
  16803. EXPECT_EQ("ok", res->body);
  16804. EXPECT_EQ("GET", method);
  16805. EXPECT_TRUE(body.empty());
  16806. EXPECT_FALSE(has_content_length);
  16807. EXPECT_FALSE(has_transfer_encoding);
  16808. // Nothing of the original body may be left on the connection
  16809. auto res2 = cli.Get("/down");
  16810. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16811. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16812. EXPECT_EQ("ok", res2->body);
  16813. EXPECT_EQ(0, bad_requests);
  16814. };
  16815. // With content length
  16816. {
  16817. Client cli(HOST, port);
  16818. cli.set_keep_alive(true);
  16819. cli.set_follow_location(true);
  16820. auto res = cli.Post(
  16821. "/up", payload.size(),
  16822. [&](size_t offset, size_t length, DataSink &sink) {
  16823. return sink.write(payload.data() + offset, length);
  16824. },
  16825. "text/plain");
  16826. check(cli, res);
  16827. }
  16828. // Without content length (chunked)
  16829. {
  16830. Client cli(HOST, port);
  16831. cli.set_keep_alive(true);
  16832. cli.set_follow_location(true);
  16833. auto res = cli.Post(
  16834. "/up",
  16835. [&](size_t /*offset*/, DataSink &sink) {
  16836. sink.write(payload.data(), payload.size());
  16837. sink.done();
  16838. return true;
  16839. },
  16840. "text/plain");
  16841. check(cli, res);
  16842. }
  16843. }
  16844. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16845. Server svr;
  16846. std::string target;
  16847. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16848. // Echo the still-encoded name back in the Location
  16849. const std::string prefix = "/start/";
  16850. res.status = StatusCode::Found_302;
  16851. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16852. });
  16853. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16854. target = req.target;
  16855. res.set_content("ok", "text/plain");
  16856. });
  16857. auto port = svr.bind_to_any_port(HOST);
  16858. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16859. auto se = detail::scope_exit([&] {
  16860. svr.stop();
  16861. thread.join();
  16862. ASSERT_FALSE(svr.is_running());
  16863. });
  16864. svr.wait_until_ready();
  16865. // Decoding the Location path would turn the first four into a path
  16866. // separator, a query delimiter, a fragment delimiter and a different
  16867. // percent-encoded octet. The rest must keep reaching the server as they are.
  16868. const std::vector<std::string> names = {
  16869. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16870. };
  16871. for (auto path_encode : {true, false}) {
  16872. Client cli(HOST, port);
  16873. cli.set_follow_location(true);
  16874. cli.set_path_encode(path_encode);
  16875. for (const auto &name : names) {
  16876. target.clear();
  16877. auto res = cli.Get("/start/" + name);
  16878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16879. EXPECT_EQ(StatusCode::OK_200, res->status);
  16880. EXPECT_EQ("/dest/" + name, target);
  16881. }
  16882. }
  16883. }
  16884. TEST(RedirectTest, NotModifiedIsReturned) {
  16885. Server svr;
  16886. svr.Get("/cached", [](const Request &, Response &res) {
  16887. res.status = StatusCode::NotModified_304;
  16888. });
  16889. auto port = svr.bind_to_any_port(HOST);
  16890. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16891. auto se = detail::scope_exit([&] {
  16892. svr.stop();
  16893. thread.join();
  16894. ASSERT_FALSE(svr.is_running());
  16895. });
  16896. svr.wait_until_ready();
  16897. Client cli(HOST, port);
  16898. cli.set_follow_location(true);
  16899. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16901. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16902. }
  16903. TEST(RedirectTest, NoLocationIsReturned) {
  16904. Server svr;
  16905. svr.Get("/no-location", [](const Request &, Response &res) {
  16906. res.status = StatusCode::Found_302;
  16907. res.set_content("no location", "text/plain");
  16908. });
  16909. auto port = svr.bind_to_any_port(HOST);
  16910. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16911. auto se = detail::scope_exit([&] {
  16912. svr.stop();
  16913. thread.join();
  16914. ASSERT_FALSE(svr.is_running());
  16915. });
  16916. svr.wait_until_ready();
  16917. Client cli(HOST, port);
  16918. cli.set_follow_location(true);
  16919. auto res = cli.Get("/no-location");
  16920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16921. EXPECT_EQ(StatusCode::Found_302, res->status);
  16922. EXPECT_EQ("no location", res->body);
  16923. // The callbacks see the body of the response that is returned
  16924. auto handler_called = false;
  16925. auto progress_called = false;
  16926. std::string body;
  16927. auto res2 = cli.Get(
  16928. "/no-location",
  16929. [&](const Response &) {
  16930. handler_called = true;
  16931. return true;
  16932. },
  16933. [&](const char *data, size_t data_length) {
  16934. body.append(data, data_length);
  16935. return true;
  16936. },
  16937. [&](size_t, size_t) {
  16938. progress_called = true;
  16939. return true;
  16940. });
  16941. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16942. EXPECT_EQ(StatusCode::Found_302, res2->status);
  16943. EXPECT_TRUE(handler_called);
  16944. EXPECT_TRUE(progress_called);
  16945. EXPECT_EQ("no location", body);
  16946. }
  16947. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16948. Server svr;
  16949. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16950. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16951. });
  16952. svr.Get("/hello", [](const Request &req, Response &res) {
  16953. res.set_content(req.get_param_value("key"), "text/plain");
  16954. });
  16955. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16956. auto se = detail::scope_exit([&] {
  16957. svr.stop();
  16958. thread.join();
  16959. ASSERT_FALSE(svr.is_running());
  16960. });
  16961. svr.wait_until_ready();
  16962. {
  16963. Client cli(HOST, PORT);
  16964. cli.set_follow_location(true);
  16965. auto res = cli.Get("/");
  16966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16967. EXPECT_EQ(StatusCode::OK_200, res->status);
  16968. EXPECT_EQ("val&key2=val2", res->body);
  16969. }
  16970. }
  16971. #endif
  16972. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16973. Server svr;
  16974. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16975. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16976. });
  16977. svr.Get("/hello", [](const Request &req, Response &res) {
  16978. res.set_content(req.get_param_value("key"), "text/plain");
  16979. });
  16980. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16981. auto se = detail::scope_exit([&] {
  16982. svr.stop();
  16983. thread.join();
  16984. ASSERT_FALSE(svr.is_running());
  16985. });
  16986. svr.wait_until_ready();
  16987. {
  16988. Client cli(HOST, PORT);
  16989. cli.set_follow_location(true);
  16990. auto res = cli.Get("/");
  16991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16992. EXPECT_EQ(StatusCode::OK_200, res->status);
  16993. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16994. }
  16995. }
  16996. TEST(RedirectTest, RedirectWithPlusInPath) {
  16997. Server svr;
  16998. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16999. res.set_redirect("/a+b");
  17000. });
  17001. // Route pattern uses regex; escape + as \\+
  17002. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17003. res.set_content(req.path, "text/plain");
  17004. });
  17005. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17006. auto se = detail::scope_exit([&] {
  17007. svr.stop();
  17008. thread.join();
  17009. ASSERT_FALSE(svr.is_running());
  17010. });
  17011. svr.wait_until_ready();
  17012. {
  17013. Client cli(HOST, PORT);
  17014. cli.set_follow_location(true);
  17015. auto res = cli.Get("/");
  17016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17017. EXPECT_EQ(StatusCode::OK_200, res->status);
  17018. EXPECT_EQ("/a+b", res->body);
  17019. }
  17020. }
  17021. TEST(RedirectTest, ResolveRelativeLocation) {
  17022. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17023. const std::vector<std::pair<std::string, std::string>> cases = {
  17024. {"g", "/b/c/g"},
  17025. {"./g", "/b/c/g"},
  17026. {"g/", "/b/c/g/"},
  17027. {"?y", "/b/c/d;p?y"},
  17028. {"g?y", "/b/c/g?y"},
  17029. {"#s", "/b/c/d;p?q#s"},
  17030. {"g#s", "/b/c/g#s"},
  17031. {"g?y#s", "/b/c/g?y#s"},
  17032. {";x", "/b/c/;x"},
  17033. {"g;x", "/b/c/g;x"},
  17034. {".", "/b/c/"},
  17035. {"./", "/b/c/"},
  17036. {"..", "/b/"},
  17037. {"../", "/b/"},
  17038. {"../g", "/b/g"},
  17039. {"../..", "/"},
  17040. {"../../", "/"},
  17041. {"../../g", "/g"},
  17042. {"../../../g", "/g"},
  17043. {"g.", "/b/c/g."},
  17044. {".g", "/b/c/.g"},
  17045. {"g..", "/b/c/g.."},
  17046. {"..g", "/b/c/..g"},
  17047. {"./../g", "/b/g"},
  17048. {"./g/.", "/b/c/g/"},
  17049. {"g/./h", "/b/c/g/h"},
  17050. {"g/../h", "/b/c/h"},
  17051. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17052. {"g;x=1/../y", "/b/c/y"},
  17053. {"g?y/./x", "/b/c/g?y/./x"},
  17054. {"g#s/../x", "/b/c/g#s/../x"},
  17055. // Not relative-path references, so left for parse_url.
  17056. {"/g", "/g"},
  17057. {"//g", "//g"},
  17058. {"http://g/x", "http://g/x"},
  17059. {"g:h", "g:h"},
  17060. };
  17061. for (const auto &c : cases) {
  17062. EXPECT_EQ(c.second,
  17063. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17064. << c.first;
  17065. }
  17066. }
  17067. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17068. Server svr;
  17069. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17070. res.set_redirect(req.get_param_value("to"));
  17071. });
  17072. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17073. res.set_content(req.target, "text/plain");
  17074. });
  17075. svr.Get("/other", [](const Request &req, Response &res) {
  17076. res.set_content(req.target, "text/plain");
  17077. });
  17078. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17079. auto se = detail::scope_exit([&] {
  17080. svr.stop();
  17081. thread.join();
  17082. ASSERT_FALSE(svr.is_running());
  17083. });
  17084. svr.wait_until_ready();
  17085. const std::vector<std::pair<std::string, std::string>> cases = {
  17086. {"next", "/dir/next"},
  17087. {"./next?x=1", "/dir/next?x=1"},
  17088. {"../other", "/other"},
  17089. };
  17090. for (const auto &c : cases) {
  17091. Client cli(HOST, PORT);
  17092. cli.set_follow_location(true);
  17093. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17094. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17095. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17096. EXPECT_EQ(c.second, res->body) << c.first;
  17097. }
  17098. }
  17099. #ifdef CPPHTTPLIB_SSL_ENABLED
  17100. TEST(RedirectTest, Issue2185_Online) {
  17101. SSLClient client("github.com");
  17102. client.set_follow_location(true);
  17103. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17104. "Coollab-Windows.zip");
  17105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17106. EXPECT_EQ(StatusCode::OK_200, res->status);
  17107. EXPECT_EQ(9920427U, res->body.size());
  17108. }
  17109. #endif
  17110. TEST(VulnerabilityTest, CRLFInjection) {
  17111. Server svr;
  17112. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17113. res.set_content("Hello 1", "text/plain");
  17114. });
  17115. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17116. res.set_content("Hello 2", "text/plain");
  17117. });
  17118. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17119. res.set_content("Hello 3", "text/plain");
  17120. });
  17121. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17122. res.set_content("Hello 4", "text/plain");
  17123. });
  17124. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17125. for (const auto &x : req.headers) {
  17126. auto key = x.first;
  17127. EXPECT_STRNE("evil", key.c_str());
  17128. }
  17129. });
  17130. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17131. auto se = detail::scope_exit([&] {
  17132. svr.stop();
  17133. thread.join();
  17134. ASSERT_FALSE(svr.is_running());
  17135. });
  17136. svr.wait_until_ready();
  17137. {
  17138. Client cli(HOST, PORT);
  17139. cli.Post("/test1", "A=B",
  17140. "application/x-www-form-urlencoded\r\nevil: hello1");
  17141. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17142. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17143. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17144. }
  17145. }
  17146. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17147. auto server_thread = std::thread([] {
  17148. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17149. default_socket_options(srv);
  17150. sockaddr_in addr{};
  17151. addr.sin_family = AF_INET;
  17152. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17153. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17154. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17155. ::listen(srv, 1);
  17156. sockaddr_in cli_addr{};
  17157. socklen_t cli_len = sizeof(cli_addr);
  17158. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17159. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17160. std::string buf_all;
  17161. char buf[2048];
  17162. ssize_t n;
  17163. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17164. buf_all.append(buf, static_cast<size_t>(n));
  17165. size_t pos;
  17166. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17167. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17168. auto e = request_block.find("\r\n");
  17169. if (e != std::string::npos) {
  17170. auto request_line = request_block.substr(0, e);
  17171. std::string msg =
  17172. "CRLF injection detected in request line: '" + request_line + "'";
  17173. EXPECT_FALSE(true) << msg;
  17174. }
  17175. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17176. ::send(cli,
  17177. #ifdef _WIN32
  17178. static_cast<const char *>(resp.c_str()),
  17179. static_cast<int>(resp.size()),
  17180. #else
  17181. resp.c_str(), resp.size(),
  17182. #endif
  17183. 0);
  17184. buf_all.erase(0, pos + 4);
  17185. }
  17186. }
  17187. detail::close_socket(cli);
  17188. detail::close_socket(srv);
  17189. });
  17190. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17191. auto cli = Client("127.0.0.1", PORT + 1);
  17192. auto headers = Headers{
  17193. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17194. {"Connection", "keep-alive"}};
  17195. auto res = cli.Get("/hi", headers);
  17196. EXPECT_FALSE(res);
  17197. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17198. server_thread.join();
  17199. }
  17200. // A request rejected before any byte reaches the socket must fail right away
  17201. // instead of waiting for a response the server will never send.
  17202. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17203. // The kernel completes the TCP handshake from the listen backlog, so the
  17204. // client connects, but nothing ever reads, responds or closes.
  17205. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17206. default_socket_options(srv);
  17207. sockaddr_in addr{};
  17208. addr.sin_family = AF_INET;
  17209. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17210. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17211. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17212. ASSERT_EQ(0, ::listen(srv, 8));
  17213. auto cli = Client("127.0.0.1", PORT + 1);
  17214. cli.set_read_timeout(10, 0);
  17215. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17216. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17217. std::chrono::steady_clock::now() - start)
  17218. .count();
  17219. };
  17220. {
  17221. Request req;
  17222. req.method = "GE T";
  17223. req.path = "/";
  17224. auto start = std::chrono::steady_clock::now();
  17225. auto res = cli.send(req);
  17226. EXPECT_FALSE(res);
  17227. EXPECT_EQ(Error::Write, res.error());
  17228. EXPECT_LT(elapsed_ms(start), 1000);
  17229. }
  17230. {
  17231. auto start = std::chrono::steady_clock::now();
  17232. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17233. EXPECT_FALSE(res);
  17234. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17235. EXPECT_LT(elapsed_ms(start), 1000);
  17236. }
  17237. EXPECT_FALSE(cli.is_socket_open());
  17238. detail::close_socket(srv);
  17239. }
  17240. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17241. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17242. default_socket_options(srv);
  17243. sockaddr_in addr{};
  17244. addr.sin_family = AF_INET;
  17245. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17246. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17247. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17248. ASSERT_EQ(0, ::listen(srv, 1));
  17249. std::string received;
  17250. auto server_thread = std::thread([&] {
  17251. auto sock = ::accept(srv, nullptr, nullptr);
  17252. if (sock == INVALID_SOCKET) { return; }
  17253. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17254. char buf[2048];
  17255. ssize_t n;
  17256. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17257. received.append(buf, static_cast<size_t>(n));
  17258. }
  17259. detail::close_socket(sock);
  17260. });
  17261. {
  17262. auto cli = Client("127.0.0.1", PORT + 1);
  17263. // "Z" sorts after the default headers, so writing straight to the socket
  17264. // would have sent the request line and those headers before the rejection.
  17265. auto handle =
  17266. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17267. EXPECT_FALSE(handle.is_valid());
  17268. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17269. }
  17270. server_thread.join();
  17271. detail::close_socket(srv);
  17272. EXPECT_TRUE(received.empty()) << received;
  17273. }
  17274. TEST(PathParamsTest, StaticMatch) {
  17275. const auto pattern = "/users/all";
  17276. detail::PathParamsMatcher matcher(pattern);
  17277. Request request;
  17278. request.path = "/users/all";
  17279. ASSERT_TRUE(matcher.match(request));
  17280. std::unordered_map<std::string, std::string> expected_params = {};
  17281. EXPECT_EQ(request.path_params, expected_params);
  17282. }
  17283. TEST(PathParamsTest, StaticMismatch) {
  17284. const auto pattern = "/users/all";
  17285. detail::PathParamsMatcher matcher(pattern);
  17286. Request request;
  17287. request.path = "/users/1";
  17288. ASSERT_FALSE(matcher.match(request));
  17289. }
  17290. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17291. const auto pattern = "/users/:id/subscriptions";
  17292. detail::PathParamsMatcher matcher(pattern);
  17293. Request request;
  17294. request.path = "/users/42/subscriptions";
  17295. ASSERT_TRUE(matcher.match(request));
  17296. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17297. EXPECT_EQ(request.path_params, expected_params);
  17298. }
  17299. TEST(PathParamsTest, SingleParamInTheEnd) {
  17300. const auto pattern = "/users/:id";
  17301. detail::PathParamsMatcher matcher(pattern);
  17302. Request request;
  17303. request.path = "/users/24";
  17304. ASSERT_TRUE(matcher.match(request));
  17305. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17306. EXPECT_EQ(request.path_params, expected_params);
  17307. }
  17308. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17309. const auto pattern = "/users/:id/";
  17310. detail::PathParamsMatcher matcher(pattern);
  17311. Request request;
  17312. request.path = "/users/42/";
  17313. ASSERT_TRUE(matcher.match(request));
  17314. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17315. EXPECT_EQ(request.path_params, expected_params);
  17316. }
  17317. TEST(PathParamsTest, EmptyParam) {
  17318. const auto pattern = "/users/:id/";
  17319. detail::PathParamsMatcher matcher(pattern);
  17320. Request request;
  17321. request.path = "/users//";
  17322. ASSERT_TRUE(matcher.match(request));
  17323. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17324. EXPECT_EQ(request.path_params, expected_params);
  17325. }
  17326. TEST(PathParamsTest, FragmentMismatch) {
  17327. const auto pattern = "/users/:id/";
  17328. detail::PathParamsMatcher matcher(pattern);
  17329. Request request;
  17330. request.path = "/admins/24/";
  17331. ASSERT_FALSE(matcher.match(request));
  17332. }
  17333. TEST(PathParamsTest, ExtraFragments) {
  17334. const auto pattern = "/users/:id";
  17335. detail::PathParamsMatcher matcher(pattern);
  17336. Request request;
  17337. request.path = "/users/42/subscriptions";
  17338. ASSERT_FALSE(matcher.match(request));
  17339. }
  17340. TEST(PathParamsTest, MissingTrailingParam) {
  17341. const auto pattern = "/users/:id";
  17342. detail::PathParamsMatcher matcher(pattern);
  17343. Request request;
  17344. request.path = "/users";
  17345. ASSERT_FALSE(matcher.match(request));
  17346. }
  17347. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17348. const auto pattern = "/users/:id/subscriptions";
  17349. detail::PathParamsMatcher matcher(pattern);
  17350. Request request;
  17351. request.path = "/users/subscriptions";
  17352. ASSERT_FALSE(matcher.match(request));
  17353. }
  17354. TEST(PathParamsTest, MultipleParams) {
  17355. const auto pattern = "/users/:userid/subscriptions/:subid";
  17356. detail::PathParamsMatcher matcher(pattern);
  17357. Request request;
  17358. request.path = "/users/42/subscriptions/2";
  17359. ASSERT_TRUE(matcher.match(request));
  17360. std::unordered_map<std::string, std::string> expected_params = {
  17361. {"userid", "42"}, {"subid", "2"}};
  17362. EXPECT_EQ(request.path_params, expected_params);
  17363. }
  17364. TEST(PathParamsTest, SequenceOfParams) {
  17365. const auto pattern = "/values/:x/:y/:z";
  17366. detail::PathParamsMatcher matcher(pattern);
  17367. Request request;
  17368. request.path = "/values/1/2/3";
  17369. ASSERT_TRUE(matcher.match(request));
  17370. std::unordered_map<std::string, std::string> expected_params = {
  17371. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17372. EXPECT_EQ(request.path_params, expected_params);
  17373. }
  17374. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17375. const auto pattern = "/prefix:suffix";
  17376. detail::PathParamsMatcher matcher(pattern);
  17377. Request request;
  17378. request.path = "/prefix:suffix";
  17379. ASSERT_TRUE(matcher.match(request));
  17380. const std::unordered_map<std::string, std::string> expected_params = {};
  17381. EXPECT_EQ(request.path_params, expected_params);
  17382. }
  17383. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17384. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17385. // calling thread's stack on a long enough path for a quantified pattern;
  17386. // RegexMatcher must refuse to run regex matching on paths beyond
  17387. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17388. detail::RegexMatcher matcher("/files/(.*)");
  17389. Request within_limit;
  17390. within_limit.path = "/files/" + std::string(10, 'A');
  17391. EXPECT_TRUE(matcher.match(within_limit));
  17392. Request over_limit;
  17393. over_limit.path =
  17394. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17395. EXPECT_FALSE(matcher.match(over_limit));
  17396. }
  17397. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17398. Server svr;
  17399. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17400. res.set_content("ok", "text/plain");
  17401. });
  17402. auto port = svr.bind_to_any_port(HOST);
  17403. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17404. auto se = detail::scope_exit([&] {
  17405. svr.stop();
  17406. thread.join();
  17407. ASSERT_FALSE(svr.is_running());
  17408. });
  17409. svr.wait_until_ready();
  17410. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17411. // request URI limit; this used to be able to crash the process.
  17412. std::string path =
  17413. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17414. std::string req = "GET " + path +
  17415. " HTTP/1.1\r\n"
  17416. "Host: " +
  17417. std::string(HOST) + ":" + std::to_string(port) +
  17418. "\r\n"
  17419. "Connection: close\r\n"
  17420. "\r\n";
  17421. std::string response;
  17422. ASSERT_TRUE(send_request(5, req, &response, port));
  17423. EXPECT_NE(std::string::npos, response.find("404"));
  17424. }
  17425. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17426. Server svr;
  17427. auto handler = [](const Request & /*req*/, Response &res) {
  17428. res.set_content("hit", "text/plain");
  17429. };
  17430. // No regex metacharacter, so this one is compared literally
  17431. svr.Get("/literal/route", handler);
  17432. // '.' is a regex metacharacter, so this one must keep regex semantics
  17433. svr.Get("/a.c", handler);
  17434. auto port = svr.bind_to_any_port(HOST);
  17435. std::thread t([&]() { svr.listen_after_bind(); });
  17436. auto se = detail::scope_exit([&] {
  17437. svr.stop();
  17438. t.join();
  17439. ASSERT_FALSE(svr.is_running());
  17440. });
  17441. svr.wait_until_ready();
  17442. Client cli(HOST, port);
  17443. struct {
  17444. const char *path;
  17445. int status;
  17446. } cases[] = {
  17447. {"/literal/route", StatusCode::OK_200},
  17448. {"/literal/routes", StatusCode::NotFound_404},
  17449. {"/literal/rout", StatusCode::NotFound_404},
  17450. {"/abc", StatusCode::OK_200},
  17451. {"/a.c", StatusCode::OK_200},
  17452. };
  17453. for (const auto &x : cases) {
  17454. auto res = cli.Get(x.path);
  17455. ASSERT_TRUE(res) << x.path;
  17456. EXPECT_EQ(x.status, res->status) << x.path;
  17457. }
  17458. }
  17459. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17460. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17461. // from exhausting the stack, so it must only constrain routes that actually
  17462. // run a regular expression. A literal route is matched by comparison and
  17463. // stays usable at any length.
  17464. Server svr;
  17465. const std::string pattern =
  17466. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17467. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17468. res.set_content("hit", "text/plain");
  17469. });
  17470. auto port = svr.bind_to_any_port(HOST);
  17471. std::thread t([&]() { svr.listen_after_bind(); });
  17472. auto se = detail::scope_exit([&] {
  17473. svr.stop();
  17474. t.join();
  17475. ASSERT_FALSE(svr.is_running());
  17476. });
  17477. svr.wait_until_ready();
  17478. Client cli(HOST, port);
  17479. auto res = cli.Get(pattern);
  17480. ASSERT_TRUE(res);
  17481. EXPECT_EQ(StatusCode::OK_200, res->status);
  17482. }
  17483. TEST(ParseUrlTest, VariousPatterns) {
  17484. {
  17485. detail::UrlComponents uc;
  17486. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17487. EXPECT_EQ("http", uc.scheme);
  17488. EXPECT_EQ("example.com", uc.host);
  17489. EXPECT_EQ("8080", uc.port);
  17490. EXPECT_EQ("/path", uc.path);
  17491. EXPECT_EQ("?q=1", uc.query);
  17492. }
  17493. {
  17494. detail::UrlComponents uc;
  17495. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17496. EXPECT_EQ("https", uc.scheme);
  17497. EXPECT_EQ("example.com", uc.host);
  17498. EXPECT_TRUE(uc.port.empty());
  17499. EXPECT_EQ("/path", uc.path);
  17500. }
  17501. {
  17502. detail::UrlComponents uc;
  17503. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17504. EXPECT_EQ("::1", uc.host);
  17505. EXPECT_EQ("8080", uc.port);
  17506. EXPECT_EQ("/path", uc.path);
  17507. }
  17508. {
  17509. detail::UrlComponents uc;
  17510. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17511. }
  17512. {
  17513. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17514. // the path while the connection still targets the bracketed host.
  17515. detail::UrlComponents uc;
  17516. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17517. }
  17518. {
  17519. detail::UrlComponents uc;
  17520. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17521. }
  17522. {
  17523. detail::UrlComponents uc;
  17524. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17525. EXPECT_EQ("::1", uc.host);
  17526. EXPECT_TRUE(uc.port.empty());
  17527. EXPECT_EQ("/path", uc.path);
  17528. }
  17529. {
  17530. detail::UrlComponents uc;
  17531. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17532. EXPECT_TRUE(uc.scheme.empty());
  17533. EXPECT_EQ("example.com", uc.host);
  17534. EXPECT_EQ("/path", uc.path);
  17535. EXPECT_EQ("?q=1", uc.query);
  17536. }
  17537. {
  17538. detail::UrlComponents uc;
  17539. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17540. EXPECT_TRUE(uc.host.empty());
  17541. EXPECT_EQ("/path", uc.path);
  17542. EXPECT_EQ("?q=1", uc.query);
  17543. }
  17544. {
  17545. detail::UrlComponents uc;
  17546. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17547. EXPECT_EQ("example.com", uc.host);
  17548. EXPECT_EQ("8080", uc.port);
  17549. }
  17550. {
  17551. // Unix socket path — must not be parsed as host
  17552. detail::UrlComponents uc;
  17553. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17554. EXPECT_TRUE(uc.host.empty());
  17555. }
  17556. {
  17557. detail::UrlComponents uc;
  17558. ASSERT_TRUE(detail::parse_url("", uc));
  17559. EXPECT_TRUE(uc.host.empty());
  17560. EXPECT_TRUE(uc.path.empty());
  17561. }
  17562. {
  17563. detail::UrlComponents uc;
  17564. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17565. }
  17566. {
  17567. detail::UrlComponents uc;
  17568. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17569. }
  17570. {
  17571. // Accepted by parse_url; callers restrict to http/https
  17572. detail::UrlComponents uc;
  17573. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17574. EXPECT_EQ("ftp", uc.scheme);
  17575. }
  17576. {
  17577. detail::UrlComponents uc;
  17578. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17579. }
  17580. {
  17581. detail::UrlComponents uc;
  17582. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17583. }
  17584. }
  17585. TEST(ParseUrlTest, FragmentHandling) {
  17586. {
  17587. detail::UrlComponents uc;
  17588. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17589. EXPECT_EQ("/path", uc.path);
  17590. EXPECT_TRUE(uc.query.empty());
  17591. }
  17592. {
  17593. detail::UrlComponents uc;
  17594. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17595. EXPECT_TRUE(uc.path.empty());
  17596. EXPECT_TRUE(uc.query.empty());
  17597. }
  17598. }
  17599. TEST(ParseUrlTest, UserinfoHandling) {
  17600. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17601. // parsers would see evil.com as the host.
  17602. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17603. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17604. for (auto url : urls) {
  17605. detail::UrlComponents uc;
  17606. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17607. }
  17608. }
  17609. TEST(ParseUrlTest, IPv6EdgeCases) {
  17610. {
  17611. detail::UrlComponents uc;
  17612. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17613. EXPECT_TRUE(uc.scheme.empty());
  17614. EXPECT_EQ("::1", uc.host);
  17615. EXPECT_EQ("8080", uc.port);
  17616. }
  17617. {
  17618. // Zone ID '%25' is not in [a-fA-F0-9:]
  17619. detail::UrlComponents uc;
  17620. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17621. }
  17622. }
  17623. TEST(ParseUrlTest, SchemeEdgeCases) {
  17624. {
  17625. detail::UrlComponents uc;
  17626. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17627. }
  17628. {
  17629. detail::UrlComponents uc;
  17630. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17631. }
  17632. {
  17633. detail::UrlComponents uc;
  17634. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17635. }
  17636. }
  17637. TEST(ParseUrlTest, PortEdgeCases) {
  17638. {
  17639. detail::UrlComponents uc;
  17640. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17641. EXPECT_TRUE(uc.port.empty());
  17642. EXPECT_EQ("/path", uc.path);
  17643. }
  17644. {
  17645. // parse_url accepts any port string; validation is done by parse_port
  17646. detail::UrlComponents uc;
  17647. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17648. EXPECT_EQ("abc", uc.port);
  17649. }
  17650. }
  17651. TEST(ParseUrlTest, WebSocketPatterns) {
  17652. {
  17653. detail::UrlComponents uc;
  17654. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17655. EXPECT_EQ("ws", uc.scheme);
  17656. EXPECT_EQ("echo.example.com", uc.host);
  17657. EXPECT_EQ("8080", uc.port);
  17658. EXPECT_EQ("/ws", uc.path);
  17659. }
  17660. {
  17661. detail::UrlComponents uc;
  17662. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17663. EXPECT_EQ("wss", uc.scheme);
  17664. EXPECT_EQ("echo.example.com", uc.host);
  17665. EXPECT_TRUE(uc.port.empty());
  17666. EXPECT_EQ("/ws", uc.path);
  17667. }
  17668. }
  17669. TEST(ParseUrlTest, QueryOnly) {
  17670. detail::UrlComponents uc;
  17671. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17672. EXPECT_TRUE(uc.host.empty());
  17673. EXPECT_TRUE(uc.path.empty());
  17674. EXPECT_EQ("?q=1&r=2", uc.query);
  17675. }
  17676. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17677. detail::UrlComponents uc;
  17678. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17679. EXPECT_TRUE(uc.scheme.empty());
  17680. EXPECT_EQ("example.com", uc.host);
  17681. EXPECT_EQ("443", uc.port);
  17682. EXPECT_EQ("/path", uc.path);
  17683. }
  17684. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17685. // If ipv6 regex working, regex match codepath is taken.
  17686. // else port will default to 80 in Client impl
  17687. int clientImplMagicPort = 80;
  17688. int port = 4321;
  17689. // above ports must be different to avoid false negative
  17690. EXPECT_NE(clientImplMagicPort, port);
  17691. std::string ipV6TestURL = "http://[ff06::c3]";
  17692. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17693. CLIENT_PRIVATE_KEY_FILE);
  17694. EXPECT_EQ(cli.port(), port);
  17695. }
  17696. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17697. auto file_path = "./www/dir/index.html";
  17698. auto dir_path = "./www/dir";
  17699. detail::FileStat stat_file(file_path);
  17700. EXPECT_TRUE(stat_file.is_file());
  17701. EXPECT_FALSE(stat_file.is_dir());
  17702. detail::FileStat stat_dir(dir_path);
  17703. EXPECT_FALSE(stat_dir.is_file());
  17704. EXPECT_TRUE(stat_dir.is_dir());
  17705. }
  17706. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17707. // IPv4 with default HTTP port (80)
  17708. EXPECT_EQ("example.com",
  17709. detail::make_host_and_port_string("example.com", 80, false));
  17710. // IPv4 with default HTTPS port (443)
  17711. EXPECT_EQ("example.com",
  17712. detail::make_host_and_port_string("example.com", 443, true));
  17713. // IPv4 with non-default HTTP port
  17714. EXPECT_EQ("example.com:8080",
  17715. detail::make_host_and_port_string("example.com", 8080, false));
  17716. // IPv4 with non-default HTTPS port
  17717. EXPECT_EQ("example.com:8443",
  17718. detail::make_host_and_port_string("example.com", 8443, true));
  17719. // IPv6 with default HTTP port (80)
  17720. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17721. // IPv6 with default HTTPS port (443)
  17722. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17723. // IPv6 with non-default HTTP port
  17724. EXPECT_EQ("[::1]:8080",
  17725. detail::make_host_and_port_string("::1", 8080, false));
  17726. // IPv6 with non-default HTTPS port
  17727. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17728. // IPv6 full address with default port
  17729. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17730. detail::make_host_and_port_string(
  17731. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17732. // IPv6 full address with non-default port
  17733. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17734. detail::make_host_and_port_string(
  17735. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17736. // IPv6 localhost with non-default port
  17737. EXPECT_EQ("[::1]:3000",
  17738. detail::make_host_and_port_string("::1", 3000, false));
  17739. // IPv6 with zone ID (link-local address) with default port
  17740. EXPECT_EQ("[fe80::1%eth0]",
  17741. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17742. // IPv6 with zone ID (link-local address) with non-default port
  17743. EXPECT_EQ("[fe80::1%eth0]:8080",
  17744. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17745. // Edge case: Port 443 with is_ssl=false (should add port)
  17746. EXPECT_EQ("example.com:443",
  17747. detail::make_host_and_port_string("example.com", 443, false));
  17748. // Edge case: Port 80 with is_ssl=true (should add port)
  17749. EXPECT_EQ("example.com:80",
  17750. detail::make_host_and_port_string("example.com", 80, true));
  17751. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17752. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17753. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17754. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17755. // Security fix: Already bracketed IPv6 should not get double brackets
  17756. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17757. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17758. EXPECT_EQ("[::1]:8080",
  17759. detail::make_host_and_port_string("[::1]", 8080, false));
  17760. EXPECT_EQ("[2001:db8::1]:8080",
  17761. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17762. EXPECT_EQ("[fe80::1%eth0]",
  17763. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17764. EXPECT_EQ("[fe80::1%eth0]:8080",
  17765. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17766. // Edge case: Empty host (should return as-is)
  17767. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17768. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17769. // This is a known limitation but shouldn't crash
  17770. EXPECT_EQ("[host:name]",
  17771. detail::make_host_and_port_string("host:name", 80, false));
  17772. // Port number edge cases (no validation, but should not crash)
  17773. EXPECT_EQ("example.com:0",
  17774. detail::make_host_and_port_string("example.com", 0, false));
  17775. EXPECT_EQ("example.com:-1",
  17776. detail::make_host_and_port_string("example.com", -1, false));
  17777. EXPECT_EQ("example.com:65535",
  17778. detail::make_host_and_port_string("example.com", 65535, false));
  17779. EXPECT_EQ("example.com:65536",
  17780. detail::make_host_and_port_string("example.com", 65536, false));
  17781. }
  17782. #ifdef CPPHTTPLIB_SSL_ENABLED
  17783. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17784. httplib::SSLClient cli("roblox.com", 443);
  17785. cli.set_follow_location(true);
  17786. auto res = cli.Get("/");
  17787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17788. EXPECT_EQ(StatusCode::OK_200, res->status);
  17789. }
  17790. #endif
  17791. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17792. Server svr;
  17793. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17794. EXPECT_EQ(res.status, 400);
  17795. });
  17796. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17797. auto se = detail::scope_exit([&] {
  17798. svr.stop();
  17799. thread.join();
  17800. ASSERT_FALSE(svr.is_running());
  17801. });
  17802. svr.wait_until_ready();
  17803. Client cli(HOST, PORT);
  17804. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17805. }
  17806. TEST(InvalidHeaderCharsTest, is_field_name) {
  17807. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17808. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17809. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17810. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17811. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17812. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17813. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17814. EXPECT_FALSE(detail::fields::is_field_name(""));
  17815. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17816. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17817. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17818. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17819. }
  17820. TEST(InvalidHeaderCharsTest, is_field_value) {
  17821. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17822. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17823. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17824. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17825. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17826. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17827. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17828. EXPECT_TRUE(detail::fields::is_field_value(""));
  17829. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17830. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17831. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17832. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17833. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17834. }
  17835. TEST(InvalidHeaderCharsTest, OnServer) {
  17836. Server svr;
  17837. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17838. std::string header = "Not Set";
  17839. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17840. res.set_header(header, "value");
  17841. res.set_content("Page Content Page Content", "text/plain");
  17842. });
  17843. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17844. std::string header = "Not Set";
  17845. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17846. res.set_header("X-Test", header);
  17847. res.set_content("Page Content Page Content", "text/plain");
  17848. });
  17849. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17850. auto se = detail::scope_exit([&] {
  17851. svr.stop();
  17852. thread.join();
  17853. ASSERT_FALSE(svr.is_running());
  17854. });
  17855. svr.wait_until_ready();
  17856. Client cli(HOST, PORT);
  17857. {
  17858. auto res = cli.Get(
  17859. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17861. EXPECT_EQ("Page Content Page Content", res->body);
  17862. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17863. }
  17864. {
  17865. auto res = cli.Get(
  17866. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17868. EXPECT_EQ("Page Content Page Content", res->body);
  17869. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17870. }
  17871. }
  17872. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17873. auto handled = false;
  17874. Server svr;
  17875. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17876. thread t = thread([&] { svr.listen(HOST, PORT); });
  17877. auto se = detail::scope_exit([&] {
  17878. svr.stop();
  17879. t.join();
  17880. ASSERT_FALSE(svr.is_running());
  17881. ASSERT_FALSE(handled);
  17882. });
  17883. svr.wait_until_ready();
  17884. auto req = "POST /test HTTP/1.1\r\n"
  17885. "Content-Length: x\r\n"
  17886. "\r\n";
  17887. std::string response;
  17888. ASSERT_TRUE(send_request(1, req, &response));
  17889. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17890. response.substr(0, response.find("\r\n")));
  17891. }
  17892. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17893. // case-insensitive, and a server that receives a 100-continue expectation in
  17894. // an HTTP/1.0 request MUST ignore it.
  17895. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17896. std::string response;
  17897. ASSERT_TRUE(send_request(1, req, &response, port));
  17898. *got_100 = response.find("100 Continue") != std::string::npos;
  17899. }
  17900. class ExpectTokenTest : public ::testing::Test {
  17901. protected:
  17902. void SetUp() override {
  17903. svr_.Post("/p", [](const Request &, Response &res) {
  17904. res.set_content("ok", "text/plain");
  17905. });
  17906. port_ = svr_.bind_to_any_port(HOST);
  17907. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17908. svr_.wait_until_ready();
  17909. }
  17910. void TearDown() override {
  17911. svr_.stop();
  17912. if (thread_.joinable()) { thread_.join(); }
  17913. }
  17914. std::string request(const char *version, const char *expect_value) const {
  17915. return std::string("POST /p ") + version +
  17916. "\r\n"
  17917. "Host: localhost\r\n"
  17918. "Content-Length: 2\r\n"
  17919. "Connection: close\r\n"
  17920. "Expect: " +
  17921. expect_value +
  17922. "\r\n"
  17923. "\r\n"
  17924. "hi";
  17925. }
  17926. Server svr_;
  17927. int port_ = 0;
  17928. thread thread_;
  17929. };
  17930. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17931. bool got_100 = false;
  17932. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17933. EXPECT_TRUE(got_100);
  17934. }
  17935. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17936. bool got_100 = true;
  17937. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17938. EXPECT_FALSE(got_100);
  17939. }
  17940. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17941. bool got_100 = false;
  17942. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17943. EXPECT_TRUE(got_100);
  17944. }
  17945. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17946. bool got_100 = false;
  17947. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17948. EXPECT_TRUE(got_100);
  17949. }
  17950. // `100 Continue` is sent only when the server starts reading the body, so a
  17951. // request rejected before that never invites the client to send it. The
  17952. // requests below carry the expectation but withhold the body, as a client
  17953. // waiting for `100 Continue` would.
  17954. // A POST that expects `100 Continue` and withholds its two-byte body.
  17955. static std::string expect_headers_only(const std::string &path) {
  17956. return "POST " + path +
  17957. " HTTP/1.1\r\n"
  17958. "Host: localhost\r\n"
  17959. "Content-Length: 2\r\n"
  17960. "Expect: 100-continue\r\n"
  17961. "\r\n";
  17962. }
  17963. class ExpectLazyContinueTest : public ::testing::Test {
  17964. protected:
  17965. void SetUp() override {
  17966. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17967. if (req.path == "/pre-routing") {
  17968. res.status = StatusCode::Unauthorized_401;
  17969. return Server::HandlerResponse::Handled;
  17970. }
  17971. return Server::HandlerResponse::Unhandled;
  17972. });
  17973. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17974. if (req.matched_route == "/pre-request") {
  17975. res.status = StatusCode::Forbidden_403;
  17976. return Server::HandlerResponse::Handled;
  17977. }
  17978. return Server::HandlerResponse::Unhandled;
  17979. });
  17980. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17981. res.set_content("ok", "text/plain");
  17982. });
  17983. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17984. res.set_content("ok", "text/plain");
  17985. });
  17986. svr_.Post("/reader-used", [](const Request &, Response &res,
  17987. const ContentReader &content_reader) {
  17988. std::string body;
  17989. content_reader([&](const char *data, size_t len) {
  17990. body.append(data, len);
  17991. return true;
  17992. });
  17993. res.set_content(body, "text/plain");
  17994. });
  17995. svr_.Post("/reader-unused",
  17996. [](const Request &, Response &res, const ContentReader &) {
  17997. res.set_content("ignored", "text/plain");
  17998. });
  17999. port_ = svr_.bind_to_any_port(HOST);
  18000. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18001. svr_.wait_until_ready();
  18002. }
  18003. void TearDown() override {
  18004. svr_.stop();
  18005. if (thread_.joinable()) { thread_.join(); }
  18006. }
  18007. // Sends `req` and reads until the server closes the connection. Returns
  18008. // false if the read had to wait for the client-side timeout instead.
  18009. bool send_until_closed(const std::string &req, std::string *resp) const {
  18010. auto start = std::chrono::steady_clock::now();
  18011. if (!send_request(3, req, resp, port_)) { return false; }
  18012. auto elapsed = std::chrono::steady_clock::now() - start;
  18013. return elapsed < std::chrono::seconds(2);
  18014. }
  18015. // The final response comes without `100 Continue`, and the server closes
  18016. // the connection since the body may or may not follow.
  18017. void expect_final_without_interim(const std::string &path,
  18018. const char *status_line) const {
  18019. std::string resp;
  18020. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18021. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18022. EXPECT_EQ(0u, resp.find(status_line));
  18023. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18024. }
  18025. Server svr_;
  18026. int port_ = 0;
  18027. thread thread_;
  18028. };
  18029. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18030. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18031. }
  18032. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18033. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18034. }
  18035. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18036. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18037. }
  18038. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18039. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18040. }
  18041. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18042. // The body follows once `100 Continue` has had time to arrive.
  18043. auto req = expect_headers_only("/reader-used");
  18044. req.insert(req.size() - 2, "Connection: close\r\n");
  18045. std::string resp;
  18046. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18047. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18048. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18049. EXPECT_NE(std::string::npos, resp.find("hi"));
  18050. }
  18051. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18052. // Large enough for the client to add `Expect: 100-continue` itself.
  18053. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18054. std::atomic<bool> body_sent{false};
  18055. Client cli(HOST, port_);
  18056. auto res = cli.Post(
  18057. "/pre-request", length,
  18058. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18059. body_sent = true;
  18060. std::string chunk(len, 'x');
  18061. sink.write(chunk.data(), chunk.size());
  18062. return true;
  18063. },
  18064. "application/octet-stream");
  18065. ASSERT_TRUE(res);
  18066. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18067. EXPECT_FALSE(body_sent);
  18068. }
  18069. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18070. Server svr;
  18071. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18072. return StatusCode::ExpectationFailed_417;
  18073. });
  18074. svr.Post("/p", [](const Request &, Response &res) {
  18075. res.set_content("ok", "text/plain");
  18076. });
  18077. auto port = svr.bind_to_any_port(HOST);
  18078. thread t = thread([&] { svr.listen_after_bind(); });
  18079. auto se = detail::scope_exit([&] {
  18080. svr.stop();
  18081. t.join();
  18082. });
  18083. svr.wait_until_ready();
  18084. std::string resp;
  18085. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18086. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18087. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18088. // Exactly one response: the route handler must not run after the 417.
  18089. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18090. }
  18091. #ifndef _WIN32
  18092. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18093. static constexpr char reject[] = "Unauthorized";
  18094. static constexpr char accept[] = "Upload accepted";
  18095. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18096. Server svr;
  18097. svr.set_expect_100_continue_handler(
  18098. [](const Request & /*req*/, Response &res) {
  18099. res.status = StatusCode::Unauthorized_401;
  18100. res.set_content(reject, "text/plain");
  18101. return res.status;
  18102. });
  18103. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18104. res.set_content(accept, "text/plain");
  18105. });
  18106. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18107. auto se = detail::scope_exit([&] {
  18108. svr.stop();
  18109. thread.join();
  18110. ASSERT_FALSE(svr.is_running());
  18111. });
  18112. svr.wait_until_ready();
  18113. {
  18114. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18115. curl_easy_init(), &curl_easy_cleanup};
  18116. ASSERT_NE(curl, nullptr);
  18117. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18118. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18119. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18120. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18121. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18122. &curl_slist_free_all};
  18123. ASSERT_NE(list, nullptr);
  18124. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18125. struct read_data {
  18126. uint64_t read_size;
  18127. uint64_t total_size;
  18128. } data = {0, total_size};
  18129. using read_callback_t =
  18130. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18131. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18132. void *userdata) -> size_t {
  18133. read_data *d = (read_data *)userdata;
  18134. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18135. std::fill_n(ptr, size * nmemb, 'A');
  18136. d->read_size += size * nmemb;
  18137. return size * nmemb;
  18138. };
  18139. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18140. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18141. std::vector<char> buffer;
  18142. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18143. using write_callback_t =
  18144. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18145. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18146. void *userdata) -> size_t {
  18147. std::vector<char> *buf = (std::vector<char> *)userdata;
  18148. buf->reserve(buf->size() + size * nmemb + 1);
  18149. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18150. return size * nmemb;
  18151. };
  18152. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18153. {
  18154. const auto res = curl_easy_perform(curl.get());
  18155. ASSERT_EQ(res, CURLE_OK);
  18156. }
  18157. {
  18158. auto response_code = long{};
  18159. const auto res =
  18160. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18161. ASSERT_EQ(res, CURLE_OK);
  18162. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18163. }
  18164. {
  18165. auto dl = curl_off_t{};
  18166. const auto res =
  18167. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18168. ASSERT_EQ(res, CURLE_OK);
  18169. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18170. }
  18171. {
  18172. buffer.push_back('\0');
  18173. ASSERT_STRCASEEQ(buffer.data(), reject);
  18174. }
  18175. }
  18176. }
  18177. #endif
  18178. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18179. // Regression test for #2458.
  18180. //
  18181. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18182. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18183. // ticket can make the client socket spuriously readable during the
  18184. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18185. // the client withholds the body and then blocks reading a response that never
  18186. // comes, failing with `Failed to read connection`.
  18187. //
  18188. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18189. // within the timeout. This raw OpenSSL server deliberately never sends
  18190. // `100 Continue`; the client must still deliver the body and receive 200.
  18191. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18192. signal(SIGPIPE, SIG_IGN);
  18193. const auto port = PORT + 4;
  18194. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18195. ASSERT_NE(srv, INVALID_SOCKET);
  18196. int opt = 1;
  18197. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18198. sockaddr_in addr{};
  18199. addr.sin_family = AF_INET;
  18200. addr.sin_port = htons(static_cast<uint16_t>(port));
  18201. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18202. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18203. ASSERT_EQ(0, ::listen(srv, 1));
  18204. std::atomic<size_t> server_body_bytes{0};
  18205. auto server_thread = std::thread([&] {
  18206. sockaddr_in cli_addr{};
  18207. socklen_t cli_len = sizeof(cli_addr);
  18208. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18209. if (cli == INVALID_SOCKET) { return; }
  18210. // Bound the lifetime of the server side so a buggy client (which never
  18211. // sends the body) cannot make this thread block forever on join.
  18212. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18213. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18214. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18215. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18216. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18217. SSL *ssl = SSL_new(ctx);
  18218. SSL_set_fd(ssl, static_cast<int>(cli));
  18219. if (SSL_accept(ssl) > 0) {
  18220. // Read the request headers. Reading here also flushes the TLS 1.3
  18221. // session tickets to the client. Deliberately do NOT send
  18222. // `100 Continue`.
  18223. std::string buf;
  18224. char tmp[1024];
  18225. while (buf.find("\r\n\r\n") == std::string::npos) {
  18226. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18227. if (n <= 0) { break; }
  18228. buf.append(tmp, static_cast<size_t>(n));
  18229. }
  18230. // A correct client sends the body now; count what arrives.
  18231. auto pos = buf.find("\r\n\r\n");
  18232. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18233. while (body < 4096) {
  18234. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18235. if (n <= 0) { break; }
  18236. body += static_cast<size_t>(n);
  18237. }
  18238. server_body_bytes = body;
  18239. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18240. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18241. SSL_shutdown(ssl);
  18242. }
  18243. SSL_free(ssl);
  18244. detail::close_socket(cli);
  18245. SSL_CTX_free(ctx);
  18246. });
  18247. auto se = detail::scope_exit([&] {
  18248. server_thread.join();
  18249. detail::close_socket(srv);
  18250. });
  18251. SSLClient cli("127.0.0.1", port);
  18252. cli.enable_server_certificate_verification(false);
  18253. cli.set_connection_timeout(5, 0);
  18254. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18255. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18256. std::string body(4096, 'A');
  18257. auto res = cli.Put("/api/test", body, "application/json");
  18258. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18259. EXPECT_EQ(StatusCode::OK_200, res->status);
  18260. EXPECT_EQ(body.size(), server_body_bytes.load());
  18261. }
  18262. #endif
  18263. template <typename S, typename C>
  18264. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18265. svr.Get("/stream", [&](const Request &, Response &res) {
  18266. auto data = new std::string("01234567890123456789");
  18267. res.set_content_provider(
  18268. data->size(), "text/plain",
  18269. [&, data](size_t offset, size_t length, DataSink &sink) {
  18270. const size_t DATA_CHUNK_SIZE = 4;
  18271. const auto &d = *data;
  18272. std::this_thread::sleep_for(std::chrono::seconds(1));
  18273. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18274. return true;
  18275. },
  18276. [data](bool success) {
  18277. EXPECT_FALSE(success);
  18278. delete data;
  18279. });
  18280. });
  18281. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18282. auto i = new size_t(0);
  18283. res.set_content_provider(
  18284. "text/plain",
  18285. [i](size_t, DataSink &sink) {
  18286. if (*i < 5) {
  18287. std::this_thread::sleep_for(std::chrono::seconds(1));
  18288. sink.write("abcd", 4);
  18289. (*i)++;
  18290. } else {
  18291. sink.done();
  18292. }
  18293. return true;
  18294. },
  18295. [i](bool success) {
  18296. EXPECT_FALSE(success);
  18297. delete i;
  18298. });
  18299. });
  18300. svr.Get("/chunked", [&](const Request &, Response &res) {
  18301. auto i = new size_t(0);
  18302. res.set_chunked_content_provider(
  18303. "text/plain",
  18304. [i](size_t, DataSink &sink) {
  18305. if (*i < 5) {
  18306. std::this_thread::sleep_for(std::chrono::seconds(1));
  18307. sink.os << "abcd";
  18308. (*i)++;
  18309. } else {
  18310. sink.done();
  18311. }
  18312. return true;
  18313. },
  18314. [i](bool success) {
  18315. EXPECT_FALSE(success);
  18316. delete i;
  18317. });
  18318. });
  18319. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18320. auto se = detail::scope_exit([&] {
  18321. svr.stop();
  18322. listen_thread.join();
  18323. ASSERT_FALSE(svr.is_running());
  18324. });
  18325. svr.wait_until_ready();
  18326. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18327. {
  18328. auto start = std::chrono::steady_clock::now();
  18329. auto res = cli.Get("/stream");
  18330. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18331. std::chrono::steady_clock::now() - start)
  18332. .count();
  18333. ASSERT_FALSE(res);
  18334. EXPECT_EQ(Error::Read, res.error());
  18335. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18336. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18337. }
  18338. {
  18339. auto start = std::chrono::steady_clock::now();
  18340. auto res = cli.Get("/stream_without_length");
  18341. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18342. std::chrono::steady_clock::now() - start)
  18343. .count();
  18344. ASSERT_FALSE(res);
  18345. EXPECT_EQ(Error::Read, res.error());
  18346. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18347. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18348. }
  18349. {
  18350. auto start = std::chrono::steady_clock::now();
  18351. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18352. EXPECT_EQ("abcd", string(data, data_length));
  18353. return true;
  18354. });
  18355. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18356. std::chrono::steady_clock::now() - start)
  18357. .count();
  18358. ASSERT_FALSE(res);
  18359. EXPECT_EQ(Error::Read, res.error());
  18360. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18361. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18362. }
  18363. }
  18364. TEST(MaxTimeoutTest, ContentStream) {
  18365. time_t timeout = 2000;
  18366. time_t threshold = 200;
  18367. Server svr;
  18368. Client cli("localhost", PORT);
  18369. max_timeout_test(svr, cli, timeout, threshold);
  18370. }
  18371. #ifdef CPPHTTPLIB_SSL_ENABLED
  18372. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18373. time_t timeout = 2000;
  18374. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18375. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18376. SSLClient cli("localhost", PORT);
  18377. cli.enable_server_certificate_verification(false);
  18378. max_timeout_test(svr, cli, timeout, threshold);
  18379. }
  18380. #endif
  18381. class EventDispatcher {
  18382. public:
  18383. EventDispatcher() {}
  18384. bool wait_event(DataSink *sink) {
  18385. unique_lock<mutex> lk(m_);
  18386. int id = id_;
  18387. // Wait with timeout to prevent hanging if client disconnects
  18388. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18389. [&] { return cid_ == id; })) {
  18390. return false; // Timeout occurred
  18391. }
  18392. sink->write(message_.data(), message_.size());
  18393. return true;
  18394. }
  18395. void send_event(const string &message) {
  18396. lock_guard<mutex> lk(m_);
  18397. cid_ = id_++;
  18398. message_ = message;
  18399. cv_.notify_all();
  18400. }
  18401. private:
  18402. mutex m_;
  18403. condition_variable cv_;
  18404. atomic_int id_{0};
  18405. atomic_int cid_{-1};
  18406. string message_;
  18407. };
  18408. TEST(ClientInThreadTest, Issue2068) {
  18409. EventDispatcher ed;
  18410. Server svr;
  18411. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18412. res.set_chunked_content_provider("text/event-stream",
  18413. [&](size_t /*offset*/, DataSink &sink) {
  18414. return ed.wait_event(&sink);
  18415. });
  18416. });
  18417. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18418. svr.wait_until_ready();
  18419. thread event_thread([&] {
  18420. int id = 0;
  18421. while (svr.is_running()) {
  18422. this_thread::sleep_for(chrono::milliseconds(500));
  18423. std::stringstream ss;
  18424. ss << "data: " << id << "\n\n";
  18425. ed.send_event(ss.str());
  18426. id++;
  18427. }
  18428. });
  18429. auto se = detail::scope_exit([&] {
  18430. svr.stop();
  18431. listen_thread.join();
  18432. event_thread.join();
  18433. ASSERT_FALSE(svr.is_running());
  18434. });
  18435. {
  18436. auto client = detail::make_unique<Client>(HOST, PORT);
  18437. client->set_read_timeout(std::chrono::minutes(10));
  18438. std::atomic<bool> stop{false};
  18439. std::thread t([&] {
  18440. client->Get("/event1",
  18441. [&](const char *, size_t) -> bool { return !stop; });
  18442. });
  18443. std::this_thread::sleep_for(std::chrono::seconds(2));
  18444. stop = true;
  18445. client->stop();
  18446. t.join();
  18447. // Reset client after thread has finished
  18448. client.reset();
  18449. }
  18450. }
  18451. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18452. auto handled = false;
  18453. Server svr;
  18454. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18455. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18456. auto se = detail::scope_exit([&] {
  18457. svr.stop();
  18458. t.join();
  18459. ASSERT_FALSE(svr.is_running());
  18460. ASSERT_FALSE(handled);
  18461. });
  18462. svr.wait_until_ready();
  18463. // Two Content-Length headers with different values — must be rejected
  18464. auto req = "POST /test HTTP/1.1\r\n"
  18465. "Content-Length: 5\r\n"
  18466. "Content-Length: 10\r\n"
  18467. "\r\n"
  18468. "hello";
  18469. std::string response;
  18470. ASSERT_TRUE(send_request(1, req, &response));
  18471. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18472. response.substr(0, response.find("\r\n")));
  18473. }
  18474. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18475. auto handled = false;
  18476. Server svr;
  18477. svr.Post("/test", [&](const Request &, Response &res) {
  18478. handled = true;
  18479. res.set_content("ok", "text/plain");
  18480. });
  18481. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18482. auto se = detail::scope_exit([&] {
  18483. svr.stop();
  18484. t.join();
  18485. ASSERT_FALSE(svr.is_running());
  18486. ASSERT_TRUE(handled);
  18487. });
  18488. svr.wait_until_ready();
  18489. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18490. auto req = "POST /test HTTP/1.1\r\n"
  18491. "Host: localhost\r\n"
  18492. "Content-Length: 5\r\n"
  18493. "Content-Length: 5\r\n"
  18494. "\r\n"
  18495. "hello";
  18496. std::string response;
  18497. ASSERT_TRUE(send_request(1, req, &response));
  18498. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18499. }
  18500. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18501. Server svr;
  18502. svr.Get("/test", [](const Request &, Response &res) {
  18503. res.set_content("ok", "text/plain");
  18504. });
  18505. auto port = svr.bind_to_any_port(HOST);
  18506. thread t = thread([&] { svr.listen_after_bind(); });
  18507. auto se = detail::scope_exit([&] {
  18508. svr.stop();
  18509. t.join();
  18510. ASSERT_FALSE(svr.is_running());
  18511. });
  18512. svr.wait_until_ready();
  18513. auto status_line = [&](const std::string &host_lines) {
  18514. std::string res;
  18515. send_request(
  18516. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18517. &res, port);
  18518. return res.substr(0, res.find("\r\n"));
  18519. };
  18520. const char *accepted[] = {
  18521. "Host: localhost\r\n",
  18522. "Host: a.example:8080\r\n",
  18523. "Host: my_service\r\n",
  18524. "Host: [::1]:8080\r\n",
  18525. "Host: [fe80::1%25eth0]\r\n",
  18526. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18527. };
  18528. for (auto host_lines : accepted) {
  18529. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18530. }
  18531. const char *rejected[] = {
  18532. "Host: a.example\r\nHost: b.example\r\n",
  18533. "Host: a.example\r\nHost: a.example\r\n",
  18534. "Host: a@b.example\r\n",
  18535. "Host: a.example/b\r\n",
  18536. "Host: a.example\\b\r\n",
  18537. "Host: a.example?b\r\n",
  18538. "Host: a.example#b\r\n",
  18539. "Host: a.example b.example\r\n",
  18540. };
  18541. for (auto host_lines : rejected) {
  18542. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18543. << host_lines;
  18544. }
  18545. }
  18546. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18547. Server svr;
  18548. svr.Get("/", [](const Request &req, Response &res) {
  18549. EXPECT_EQ(2U, req.trailers.size());
  18550. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18551. // Denied
  18552. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18553. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18554. // Accepted
  18555. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18556. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18557. EXPECT_TRUE(req.has_trailer("X-World"));
  18558. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18559. res.set_content("ok", "text/plain");
  18560. });
  18561. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18562. auto se = detail::scope_exit([&] {
  18563. svr.stop();
  18564. t.join();
  18565. ASSERT_FALSE(svr.is_running());
  18566. });
  18567. svr.wait_until_ready();
  18568. const std::string req = "GET / HTTP/1.1\r\n"
  18569. "Transfer-Encoding: chunked\r\n"
  18570. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18571. "\r\n"
  18572. "0\r\n"
  18573. "Content-Length: 10\r\n"
  18574. "Host: internal.local\r\n"
  18575. "Content-Type: malicious/content\r\n"
  18576. "Cookie: any\r\n"
  18577. "Set-Cookie: any\r\n"
  18578. "X-Forwarded-For: attacker.com\r\n"
  18579. "X-Real-Ip: 1.1.1.1\r\n"
  18580. "X-Hello: hello\r\n"
  18581. "X-World: world\r\n"
  18582. "\r\n";
  18583. std::string res;
  18584. ASSERT_TRUE(send_request(1, req, &res));
  18585. }
  18586. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18587. // several field lines, and the combined value is what has to be parsed. A
  18588. // Trailer field split across lines therefore declares every name it lists;
  18589. // reading only the first line silently drops the trailers the later lines
  18590. // declare. The prohibited-trailer filter still applies to every line.
  18591. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18592. Server svr;
  18593. size_t observed_trailer_count = 0;
  18594. std::string observed_hello;
  18595. std::string observed_world;
  18596. bool observed_content_length = true;
  18597. svr.Get("/", [&](const Request &req, Response &res) {
  18598. observed_trailer_count = req.trailers.size();
  18599. observed_hello = req.get_trailer_value("X-Hello");
  18600. observed_world = req.get_trailer_value("X-World");
  18601. observed_content_length = req.has_trailer("Content-Length");
  18602. res.set_content("ok", "text/plain");
  18603. });
  18604. auto port = svr.bind_to_any_port(HOST);
  18605. thread t = thread([&]() { svr.listen_after_bind(); });
  18606. auto se = detail::scope_exit([&] {
  18607. svr.stop();
  18608. t.join();
  18609. ASSERT_FALSE(svr.is_running());
  18610. });
  18611. svr.wait_until_ready();
  18612. const std::string req = "GET / HTTP/1.1\r\n"
  18613. "Host: localhost\r\n"
  18614. "Transfer-Encoding: chunked\r\n"
  18615. "Trailer: X-Hello\r\n"
  18616. "Trailer: X-World, Content-Length\r\n"
  18617. "\r\n"
  18618. "0\r\n"
  18619. "X-Hello: hello\r\n"
  18620. "X-World: world\r\n"
  18621. "Content-Length: 10\r\n"
  18622. "\r\n";
  18623. std::string res;
  18624. ASSERT_TRUE(send_request(1, req, &res, port));
  18625. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18626. // Accepted: both field lines contribute to the declared set
  18627. EXPECT_EQ(2U, observed_trailer_count);
  18628. EXPECT_EQ(observed_hello, "hello");
  18629. EXPECT_EQ(observed_world, "world");
  18630. // Denied: a prohibited name stays prohibited on a later field line
  18631. EXPECT_FALSE(observed_content_length);
  18632. }
  18633. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18634. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18635. // unbounded run of fields that are never declared, because the counter would
  18636. // only advance for declared fields.
  18637. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18638. Server svr;
  18639. bool handler_called = false;
  18640. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18641. handler_called = true;
  18642. res.set_content("ok", "text/plain");
  18643. });
  18644. auto port = svr.bind_to_any_port(HOST);
  18645. thread t = thread([&]() { svr.listen_after_bind(); });
  18646. auto se = detail::scope_exit([&] {
  18647. svr.stop();
  18648. t.join();
  18649. ASSERT_FALSE(svr.is_running());
  18650. });
  18651. svr.wait_until_ready();
  18652. // Declare nothing, then send far more undeclared trailer fields than the
  18653. // header-count limit. Parsing must stop and reject the request rather than
  18654. // read every line.
  18655. std::string req = "GET / HTTP/1.1\r\n"
  18656. "Transfer-Encoding: chunked\r\n"
  18657. "\r\n"
  18658. "0\r\n";
  18659. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18660. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18661. }
  18662. req += "\r\n";
  18663. std::string res;
  18664. ASSERT_TRUE(send_request(1, req, &res, port));
  18665. // The request is rejected before the handler runs.
  18666. EXPECT_FALSE(handler_called);
  18667. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18668. }
  18669. // The set of declared trailer names is capped so a peer cannot grow it without
  18670. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18671. // declared past the cap is not honored, even if the field is actually sent.
  18672. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18673. Server svr;
  18674. // One name inside the cap and one past it, so the test tracks the cap rather
  18675. // than a fixed count.
  18676. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18677. const std::string within_cap_name = "X-T-0";
  18678. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18679. bool observed_within_cap = false;
  18680. bool observed_past_cap = false;
  18681. svr.Get("/", [&](const Request &req, Response &res) {
  18682. observed_within_cap = req.has_trailer(within_cap_name);
  18683. observed_past_cap = req.has_trailer(past_cap_name);
  18684. res.set_content("ok", "text/plain");
  18685. });
  18686. auto port = svr.bind_to_any_port(HOST);
  18687. thread t = thread([&]() { svr.listen_after_bind(); });
  18688. auto se = detail::scope_exit([&] {
  18689. svr.stop();
  18690. t.join();
  18691. ASSERT_FALSE(svr.is_running());
  18692. });
  18693. svr.wait_until_ready();
  18694. // Declare more trailer names than the cap in a single Trailer field, then
  18695. // actually send the first (within the cap) and the last (past it).
  18696. std::string trailer_decl = "Trailer: ";
  18697. for (int i = 0; i < declared_count; i++) {
  18698. if (i != 0) { trailer_decl += ", "; }
  18699. trailer_decl += "X-T-" + std::to_string(i);
  18700. }
  18701. trailer_decl += "\r\n";
  18702. const std::string req = "GET / HTTP/1.1\r\n"
  18703. "Host: localhost\r\n"
  18704. "Transfer-Encoding: chunked\r\n" +
  18705. trailer_decl +
  18706. "\r\n"
  18707. "0\r\n" +
  18708. within_cap_name + ": a\r\n" + past_cap_name +
  18709. ": b\r\n"
  18710. "\r\n";
  18711. std::string res;
  18712. ASSERT_TRUE(send_request(1, req, &res, port));
  18713. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18714. // A name within the cap is honored; one declared past the cap is dropped.
  18715. EXPECT_TRUE(observed_within_cap);
  18716. EXPECT_FALSE(observed_past_cap);
  18717. }
  18718. // A direct client that is not listed in trusted_proxies must not be able to
  18719. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18720. // the peer address on the actual TCP connection determines whether the
  18721. // header is honored.
  18722. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18723. Server svr;
  18724. // Deliberately does NOT include the loopback address the test client
  18725. // actually connects from, so the direct connection is not a trusted proxy.
  18726. svr.set_trusted_proxies({"203.0.113.66"});
  18727. std::string observed_remote_addr;
  18728. svr.Get("/ip", [&](const Request &req, Response &res) {
  18729. observed_remote_addr = req.remote_addr;
  18730. res.set_content("ok", "text/plain");
  18731. });
  18732. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18733. auto se = detail::scope_exit([&] {
  18734. svr.stop();
  18735. t.join();
  18736. ASSERT_FALSE(svr.is_running());
  18737. });
  18738. svr.wait_until_ready();
  18739. Client cli(HOST, PORT);
  18740. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18742. EXPECT_EQ(StatusCode::OK_200, res->status);
  18743. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18744. // ignored entirely and the real connection-level address retained.
  18745. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18746. observed_remote_addr == "127.0.0.1");
  18747. }
  18748. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18749. Server svr;
  18750. std::string observed_remote_addr;
  18751. std::string observed_xff;
  18752. svr.Get("/ip", [&](const Request &req, Response &res) {
  18753. observed_remote_addr = req.remote_addr;
  18754. observed_xff = req.get_header_value("X-Forwarded-For");
  18755. res.set_content("ok", "text/plain");
  18756. });
  18757. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18758. auto se = detail::scope_exit([&] {
  18759. svr.stop();
  18760. t.join();
  18761. ASSERT_FALSE(svr.is_running());
  18762. });
  18763. svr.wait_until_ready();
  18764. Client cli(HOST, PORT);
  18765. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18767. EXPECT_EQ(StatusCode::OK_200, res->status);
  18768. EXPECT_EQ(observed_xff, "203.0.113.66");
  18769. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18770. observed_remote_addr == "127.0.0.1");
  18771. }
  18772. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18773. Server svr;
  18774. svr.set_trusted_proxies({"203.0.113.66"});
  18775. std::string observed_remote_addr;
  18776. std::string observed_xff;
  18777. svr.Get("/ip", [&](const Request &req, Response &res) {
  18778. observed_remote_addr = req.remote_addr;
  18779. observed_xff = req.get_header_value("X-Forwarded-For");
  18780. res.set_content("ok", "text/plain");
  18781. });
  18782. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18783. auto se = detail::scope_exit([&] {
  18784. svr.stop();
  18785. t.join();
  18786. ASSERT_FALSE(svr.is_running());
  18787. });
  18788. svr.wait_until_ready();
  18789. Client cli(HOST, PORT);
  18790. auto res = cli.Get("/ip");
  18791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18792. EXPECT_EQ(StatusCode::OK_200, res->status);
  18793. EXPECT_EQ(observed_xff, "");
  18794. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18795. observed_remote_addr == "127.0.0.1");
  18796. }
  18797. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18798. Server svr;
  18799. // Include the loopback address the test client actually connects from, so
  18800. // the direct connection itself is recognized as the trusted proxy hop.
  18801. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18802. std::string observed_remote_addr;
  18803. std::string observed_xff;
  18804. svr.Get("/ip", [&](const Request &req, Response &res) {
  18805. observed_remote_addr = req.remote_addr;
  18806. observed_xff = req.get_header_value("X-Forwarded-For");
  18807. res.set_content("ok", "text/plain");
  18808. });
  18809. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18810. auto se = detail::scope_exit([&] {
  18811. svr.stop();
  18812. t.join();
  18813. ASSERT_FALSE(svr.is_running());
  18814. });
  18815. svr.wait_until_ready();
  18816. Client cli(HOST, PORT);
  18817. auto res = cli.Get(
  18818. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18820. EXPECT_EQ(StatusCode::OK_200, res->status);
  18821. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18822. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18823. }
  18824. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18825. Server svr;
  18826. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18827. std::string observed_remote_addr;
  18828. std::string observed_xff;
  18829. svr.Get("/ip", [&](const Request &req, Response &res) {
  18830. observed_remote_addr = req.remote_addr;
  18831. observed_xff = req.get_header_value("X-Forwarded-For");
  18832. res.set_content("ok", "text/plain");
  18833. });
  18834. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18835. auto se = detail::scope_exit([&] {
  18836. svr.stop();
  18837. t.join();
  18838. ASSERT_FALSE(svr.is_running());
  18839. });
  18840. svr.wait_until_ready();
  18841. Client cli(HOST, PORT);
  18842. auto res = cli.Get(
  18843. "/ip",
  18844. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18846. EXPECT_EQ(StatusCode::OK_200, res->status);
  18847. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18848. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18849. }
  18850. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18851. Server svr;
  18852. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18853. std::string observed_remote_addr;
  18854. std::string observed_xff;
  18855. svr.Get("/ip", [&](const Request &req, Response &res) {
  18856. observed_remote_addr = req.remote_addr;
  18857. observed_xff = req.get_header_value("X-Forwarded-For");
  18858. res.set_content("ok", "text/plain");
  18859. });
  18860. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18861. auto se = detail::scope_exit([&] {
  18862. svr.stop();
  18863. t.join();
  18864. ASSERT_FALSE(svr.is_running());
  18865. });
  18866. svr.wait_until_ready();
  18867. Client cli(HOST, PORT);
  18868. auto res = cli.Get(
  18869. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18871. EXPECT_EQ(StatusCode::OK_200, res->status);
  18872. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18873. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18874. // and must not be selected.
  18875. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18876. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18877. }
  18878. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18879. Server svr;
  18880. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18881. std::string observed_remote_addr;
  18882. svr.Get("/ip", [&](const Request &req, Response &res) {
  18883. observed_remote_addr = req.remote_addr;
  18884. res.set_content("ok", "text/plain");
  18885. });
  18886. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18887. auto se = detail::scope_exit([&] {
  18888. svr.stop();
  18889. t.join();
  18890. ASSERT_FALSE(svr.is_running());
  18891. });
  18892. svr.wait_until_ready();
  18893. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18894. // a forged address and the trusted proxy's own address; the forged value must
  18895. // not win over the address the trusted proxy actually recorded.
  18896. Client cli(HOST, PORT);
  18897. auto res = cli.Get(
  18898. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18900. EXPECT_EQ(StatusCode::OK_200, res->status);
  18901. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18902. }
  18903. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18904. Server svr;
  18905. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18906. std::string observed_remote_addr;
  18907. std::string observed_xff;
  18908. svr.Get("/ip", [&](const Request &req, Response &res) {
  18909. observed_remote_addr = req.remote_addr;
  18910. observed_xff = req.get_header_value("X-Forwarded-For");
  18911. res.set_content("ok", "text/plain");
  18912. });
  18913. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18914. auto se = detail::scope_exit([&] {
  18915. svr.stop();
  18916. t.join();
  18917. ASSERT_FALSE(svr.is_running());
  18918. });
  18919. svr.wait_until_ready();
  18920. Client cli(HOST, PORT);
  18921. auto res = cli.Get(
  18922. "/ip",
  18923. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18925. EXPECT_EQ(StatusCode::OK_200, res->status);
  18926. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18927. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18928. }
  18929. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18930. Server svr;
  18931. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18932. std::string observed_remote_addr;
  18933. std::string observed_xff;
  18934. svr.Get("/ip", [&](const Request &req, Response &res) {
  18935. observed_remote_addr = req.remote_addr;
  18936. observed_xff = req.get_header_value("X-Forwarded-For");
  18937. res.set_content("ok", "text/plain");
  18938. });
  18939. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18940. auto se = detail::scope_exit([&] {
  18941. svr.stop();
  18942. t.join();
  18943. ASSERT_FALSE(svr.is_running());
  18944. });
  18945. svr.wait_until_ready();
  18946. std::string raw_req =
  18947. "GET /ip HTTP/1.1\r\n"
  18948. "Host: localhost\r\n"
  18949. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18950. "Connection: close\r\n"
  18951. "\r\n";
  18952. std::string out;
  18953. ASSERT_TRUE(send_request(5, raw_req, &out));
  18954. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18955. // Header parser trims surrounding whitespace of the header value
  18956. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18957. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18958. }
  18959. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18960. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18961. // their own X-Forwarded-For as a separate field line rather than extending the
  18962. // one the client sent, so every occurrence has to be taken into account.
  18963. // Reading only the first one hands back the address the client chose.
  18964. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18965. Server svr;
  18966. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18967. std::string observed_remote_addr;
  18968. size_t observed_xff_count = 0;
  18969. svr.Get("/ip", [&](const Request &req, Response &res) {
  18970. observed_remote_addr = req.remote_addr;
  18971. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18972. res.set_content("ok", "text/plain");
  18973. });
  18974. auto port = svr.bind_to_any_port(HOST);
  18975. thread t = thread([&]() { svr.listen_after_bind(); });
  18976. auto se = detail::scope_exit([&] {
  18977. svr.stop();
  18978. t.join();
  18979. ASSERT_FALSE(svr.is_running());
  18980. });
  18981. svr.wait_until_ready();
  18982. // The client supplies the first field line; the trusted proxy appends the
  18983. // address it observed as a second one.
  18984. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18985. "Host: localhost\r\n"
  18986. "X-Forwarded-For: 1.2.3.4\r\n"
  18987. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18988. "Connection: close\r\n"
  18989. "\r\n";
  18990. std::string out;
  18991. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18992. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18993. EXPECT_EQ(observed_xff_count, 2U);
  18994. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18995. // The same chain spread over one field line per hop derives the same client
  18996. // address, i.e. the split and the comma-joined representations agree.
  18997. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18998. "Host: localhost\r\n"
  18999. "X-Forwarded-For: 1.2.3.4\r\n"
  19000. "X-Forwarded-For: 198.51.100.23\r\n"
  19001. "X-Forwarded-For: 192.0.2.45\r\n"
  19002. "Connection: close\r\n"
  19003. "\r\n";
  19004. out.clear();
  19005. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19006. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19007. EXPECT_EQ(observed_xff_count, 3U);
  19008. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19009. }
  19010. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19011. // crash the server (it used to call front() on an empty vector inside
  19012. // get_client_ip). The connection-level remote address must be retained instead.
  19013. static void run_malformed_xff_test(const std::string &xff_value) {
  19014. Server svr;
  19015. svr.set_trusted_proxies({"192.0.2.45"});
  19016. std::string observed_remote_addr;
  19017. svr.Get("/ip", [&](const Request &req, Response &res) {
  19018. observed_remote_addr = req.remote_addr;
  19019. res.set_content("ok", "text/plain");
  19020. });
  19021. int port = 0;
  19022. thread t = thread([&]() {
  19023. port = svr.bind_to_any_port(HOST);
  19024. svr.listen_after_bind();
  19025. });
  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("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19035. EXPECT_EQ(StatusCode::OK_200, res->status);
  19036. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19037. observed_remote_addr == "127.0.0.1");
  19038. }
  19039. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19040. run_malformed_xff_test("");
  19041. }
  19042. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19043. run_malformed_xff_test(",");
  19044. }
  19045. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19046. run_malformed_xff_test(", , ,");
  19047. }
  19048. // The same rule applies to Accept: a request whose acceptable types are spread
  19049. // over several field lines must be negotiated against all of them.
  19050. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19051. // case-insensitive connection options. Comparing the whole field value against
  19052. // one option misses a client that sends several of them, and misses every
  19053. // casing but the one written in the comparison.
  19054. //
  19055. // Sends req, reads the response, then reuses the same socket for a second
  19056. // request to find out whether the server kept the connection.
  19057. static void probe_connection_reuse(int port, const std::string &req,
  19058. bool *announced_close, bool *reusable) {
  19059. auto error = Error::Success;
  19060. auto sock = detail::create_client_socket(
  19061. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19062. /*connection_timeout_sec=*/5, 0,
  19063. /*read_timeout_sec=*/1, 0,
  19064. /*write_timeout_sec=*/5, 0, std::string(), error);
  19065. ASSERT_NE(sock, INVALID_SOCKET);
  19066. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19067. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19068. "Host: localhost\r\n"
  19069. "Connection: close\r\n"
  19070. "\r\n";
  19071. std::string first_response;
  19072. std::string second_response;
  19073. detail::process_client_socket(
  19074. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19075. [&](Stream &strm) {
  19076. if (strm.write(req.data(), req.size()) !=
  19077. static_cast<ssize_t>(req.size())) {
  19078. return false;
  19079. }
  19080. char buf[512];
  19081. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19082. // Headers plus the two-byte body of the handler below
  19083. while (reader.getline()) {
  19084. first_response += reader.ptr();
  19085. if (first_response.find("ok") != std::string::npos) { break; }
  19086. }
  19087. if (strm.write(second.data(), second.size()) !=
  19088. static_cast<ssize_t>(second.size())) {
  19089. return true;
  19090. }
  19091. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19092. while (reader2.getline()) {
  19093. second_response += reader2.ptr();
  19094. if (second_response.find("ok") != std::string::npos) { break; }
  19095. }
  19096. return true;
  19097. });
  19098. *announced_close =
  19099. first_response.find("Connection: close") != std::string::npos;
  19100. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19101. }
  19102. class ConnectionTokenTest : public ::testing::Test {
  19103. protected:
  19104. void SetUp() override {
  19105. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19106. res.set_content("ok", "text/plain");
  19107. });
  19108. port_ = svr_.bind_to_any_port(HOST);
  19109. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19110. svr_.wait_until_ready();
  19111. }
  19112. void TearDown() override {
  19113. svr_.stop();
  19114. if (thread_.joinable()) { thread_.join(); }
  19115. }
  19116. Server svr_;
  19117. int port_ = 0;
  19118. thread thread_;
  19119. };
  19120. // "close" alongside another option still closes the connection, and the
  19121. // response says so rather than leaving the peer to discover it.
  19122. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19123. bool announced_close = false;
  19124. bool reusable = true;
  19125. probe_connection_reuse(port_,
  19126. "GET /keepalive HTTP/1.1\r\n"
  19127. "Host: localhost\r\n"
  19128. "Connection: keep-alive, close\r\n"
  19129. "\r\n",
  19130. &announced_close, &reusable);
  19131. EXPECT_TRUE(announced_close);
  19132. EXPECT_FALSE(reusable);
  19133. }
  19134. // "close" split over two field lines is the same list, so it is honored too.
  19135. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19136. bool announced_close = false;
  19137. bool reusable = true;
  19138. probe_connection_reuse(port_,
  19139. "GET /keepalive HTTP/1.1\r\n"
  19140. "Host: localhost\r\n"
  19141. "Connection: keep-alive\r\n"
  19142. "Connection: close\r\n"
  19143. "\r\n",
  19144. &announced_close, &reusable);
  19145. EXPECT_TRUE(announced_close);
  19146. EXPECT_FALSE(reusable);
  19147. }
  19148. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19149. // keep-alive in the spelling everyone actually sends keeps its connection.
  19150. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19151. bool announced_close = false;
  19152. bool reusable = false;
  19153. probe_connection_reuse(port_,
  19154. "GET /keepalive HTTP/1.0\r\n"
  19155. "Host: localhost\r\n"
  19156. "Connection: keep-alive\r\n"
  19157. "\r\n",
  19158. &announced_close, &reusable);
  19159. EXPECT_FALSE(announced_close);
  19160. EXPECT_TRUE(reusable);
  19161. }
  19162. // A token the value merely contains is not the token itself.
  19163. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19164. bool announced_close = false;
  19165. bool reusable = false;
  19166. probe_connection_reuse(port_,
  19167. "GET /keepalive HTTP/1.1\r\n"
  19168. "Host: localhost\r\n"
  19169. "Connection: notclose\r\n"
  19170. "\r\n",
  19171. &announced_close, &reusable);
  19172. EXPECT_FALSE(announced_close);
  19173. EXPECT_TRUE(reusable);
  19174. }
  19175. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19176. Server svr;
  19177. std::vector<std::string> observed_types;
  19178. svr.Get("/", [&](const Request &req, Response &res) {
  19179. observed_types = req.accept_content_types;
  19180. res.set_content("ok", "text/plain");
  19181. });
  19182. auto port = svr.bind_to_any_port(HOST);
  19183. thread t = thread([&]() { svr.listen_after_bind(); });
  19184. auto se = detail::scope_exit([&] {
  19185. svr.stop();
  19186. t.join();
  19187. ASSERT_FALSE(svr.is_running());
  19188. });
  19189. svr.wait_until_ready();
  19190. Client cli(HOST, port);
  19191. Headers headers;
  19192. headers.emplace("Accept", "text/plain;q=0.5");
  19193. headers.emplace("Accept", "application/json");
  19194. auto res = cli.Get("/", headers);
  19195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19196. EXPECT_EQ(StatusCode::OK_200, res->status);
  19197. // Sorted by q-value, so the second field line's type comes first
  19198. ASSERT_EQ(2U, observed_types.size());
  19199. EXPECT_EQ("application/json", observed_types[0]);
  19200. EXPECT_EQ("text/plain", observed_types[1]);
  19201. }
  19202. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19203. // empty field line must not contribute a bare comma to the combined value.
  19204. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19205. Server svr;
  19206. std::vector<std::string> observed_types;
  19207. svr.Get("/", [&](const Request &req, Response &res) {
  19208. observed_types = req.accept_content_types;
  19209. res.set_content("ok", "text/plain");
  19210. });
  19211. auto port = svr.bind_to_any_port(HOST);
  19212. thread t = thread([&]() { svr.listen_after_bind(); });
  19213. auto se = detail::scope_exit([&] {
  19214. svr.stop();
  19215. t.join();
  19216. ASSERT_FALSE(svr.is_running());
  19217. });
  19218. svr.wait_until_ready();
  19219. // Empty first field line, then a real one
  19220. std::string raw_req = "GET / HTTP/1.1\r\n"
  19221. "Host: localhost\r\n"
  19222. "Accept:\r\n"
  19223. "Accept: application/json\r\n"
  19224. "Connection: close\r\n"
  19225. "\r\n";
  19226. std::string out;
  19227. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19228. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19229. ASSERT_EQ(1U, observed_types.size());
  19230. EXPECT_EQ("application/json", observed_types[0]);
  19231. }
  19232. // The skip in get_combined_header_value() is what keeps an empty field line
  19233. // from contributing a bare comma. Only a trailing empty field line exercises
  19234. // it: a leading one is already covered by the "combined is still empty" check,
  19235. // and parse_accept_header() now ignores the empty element either way, so the
  19236. // request-level test above can no longer tell the two apart.
  19237. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19238. Headers headers;
  19239. headers.emplace("Accept", "text/html");
  19240. headers.emplace("Accept", "");
  19241. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19242. headers.clear();
  19243. headers.emplace("Accept", "");
  19244. headers.emplace("Accept", "application/json");
  19245. EXPECT_EQ("application/json",
  19246. detail::get_combined_header_value(headers, "Accept"));
  19247. }
  19248. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19249. // An encoding offered on a later Accept-Encoding field line is still offered.
  19250. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19251. Server svr;
  19252. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19253. res.set_content(std::string(1024, 'x'), "text/plain");
  19254. });
  19255. auto port = svr.bind_to_any_port(HOST);
  19256. thread t = thread([&]() { svr.listen_after_bind(); });
  19257. auto se = detail::scope_exit([&] {
  19258. svr.stop();
  19259. t.join();
  19260. ASSERT_FALSE(svr.is_running());
  19261. });
  19262. svr.wait_until_ready();
  19263. Client cli(HOST, port);
  19264. cli.set_decompress(false);
  19265. Headers headers;
  19266. headers.emplace("Accept-Encoding", "identity");
  19267. headers.emplace("Accept-Encoding", "gzip");
  19268. auto res = cli.Get("/", headers);
  19269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19270. EXPECT_EQ(StatusCode::OK_200, res->status);
  19271. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19272. }
  19273. #endif
  19274. #ifndef _WIN32
  19275. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19276. Server svr;
  19277. svr.Post("/post", [&](const Request &req, Response &res) {
  19278. res.set_content(req.body, "text/plain");
  19279. });
  19280. svr.Put("/put", [&](const Request &req, Response &res) {
  19281. res.set_content(req.body, "text/plain");
  19282. });
  19283. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19284. res.set_content(req.body, "text/plain");
  19285. });
  19286. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19287. res.set_content(req.body, "text/plain");
  19288. });
  19289. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19290. auto se = detail::scope_exit([&] {
  19291. svr.stop();
  19292. t.join();
  19293. ASSERT_FALSE(svr.is_running());
  19294. });
  19295. svr.wait_until_ready();
  19296. std::string resp;
  19297. // POST without Content-Length
  19298. ASSERT_TRUE(send_request(5,
  19299. "POST /post HTTP/1.1\r\n"
  19300. "Host: localhost\r\n"
  19301. "Connection: close\r\n"
  19302. "\r\n",
  19303. &resp));
  19304. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19305. // PUT without Content-Length
  19306. resp.clear();
  19307. ASSERT_TRUE(send_request(5,
  19308. "PUT /put HTTP/1.1\r\n"
  19309. "Host: localhost\r\n"
  19310. "Connection: close\r\n"
  19311. "\r\n",
  19312. &resp));
  19313. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19314. // PATCH without Content-Length
  19315. resp.clear();
  19316. ASSERT_TRUE(send_request(5,
  19317. "PATCH /patch HTTP/1.1\r\n"
  19318. "Host: localhost\r\n"
  19319. "Connection: close\r\n"
  19320. "\r\n",
  19321. &resp));
  19322. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19323. // DELETE without Content-Length
  19324. resp.clear();
  19325. ASSERT_TRUE(send_request(5,
  19326. "DELETE /delete HTTP/1.1\r\n"
  19327. "Host: localhost\r\n"
  19328. "Connection: close\r\n"
  19329. "\r\n",
  19330. &resp));
  19331. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19332. }
  19333. #endif
  19334. //==============================================================================
  19335. // open_stream() Tests
  19336. //==============================================================================
  19337. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19338. std::string result;
  19339. char buf[8192];
  19340. ssize_t n;
  19341. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19342. result.append(buf, static_cast<size_t>(n));
  19343. }
  19344. return result;
  19345. }
  19346. // Mock stream for unit tests
  19347. class MockStream : public Stream {
  19348. public:
  19349. std::string data;
  19350. size_t pos = 0;
  19351. ssize_t error_after = -1; // -1 = no error
  19352. explicit MockStream(const std::string &d, ssize_t err = -1)
  19353. : data(d), error_after(err) {}
  19354. bool is_readable() const override { return true; }
  19355. bool wait_readable() const override { return true; }
  19356. bool wait_writable() const override { return true; }
  19357. ssize_t read(char *ptr, size_t size) override {
  19358. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19359. if (pos >= data.size()) return 0;
  19360. size_t limit =
  19361. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19362. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19363. std::memcpy(ptr, data.data() + pos, to_read);
  19364. pos += to_read;
  19365. return static_cast<ssize_t>(to_read);
  19366. }
  19367. ssize_t write(const char *, size_t) override { return -1; }
  19368. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19369. ip = "127.0.0.1";
  19370. port = 0;
  19371. }
  19372. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19373. ip = "127.0.0.1";
  19374. port = 0;
  19375. }
  19376. socket_t socket() const override { return INVALID_SOCKET; }
  19377. time_t duration() const override { return 0; }
  19378. };
  19379. TEST(StreamHandleTest, Basic) {
  19380. ClientImpl::StreamHandle handle;
  19381. EXPECT_FALSE(handle.is_valid());
  19382. handle.response = detail::make_unique<Response>();
  19383. handle.error = Error::Connection;
  19384. EXPECT_FALSE(handle.is_valid());
  19385. handle.error = Error::Success;
  19386. EXPECT_TRUE(handle.is_valid());
  19387. }
  19388. TEST(BodyReaderTest, Basic) {
  19389. MockStream stream("Hello, World!");
  19390. detail::BodyReader reader;
  19391. reader.stream = &stream;
  19392. reader.content_length = 13;
  19393. char buf[32];
  19394. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19395. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19396. EXPECT_TRUE(reader.eof);
  19397. }
  19398. TEST(BodyReaderTest, NoStream) {
  19399. detail::BodyReader reader;
  19400. char buf[32];
  19401. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19402. EXPECT_EQ(Error::Connection, reader.last_error);
  19403. }
  19404. TEST(BodyReaderTest, Error) {
  19405. MockStream stream("Hello, World!", 5);
  19406. detail::BodyReader reader;
  19407. reader.stream = &stream;
  19408. reader.content_length = 13;
  19409. char buf[32];
  19410. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19411. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19412. EXPECT_EQ(Error::Read, reader.last_error);
  19413. }
  19414. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19415. // Mock-based StreamHandle tests relying on private internals are removed.
  19416. class OpenStreamTest : public ::testing::Test {
  19417. protected:
  19418. void SetUp() override {
  19419. svr_.Get("/hello", [](const Request &, Response &res) {
  19420. res.set_content("Hello World!", "text/plain");
  19421. });
  19422. svr_.Get("/large", [](const Request &, Response &res) {
  19423. res.set_content(std::string(10000, 'X'), "text/plain");
  19424. });
  19425. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19426. res.set_content("Hello World!", "image/jpeg");
  19427. res.set_header("Content-Encoding", "UTF-8");
  19428. });
  19429. svr_.Get("/chunked", [](const Request &, Response &res) {
  19430. res.set_chunked_content_provider("text/plain",
  19431. [](size_t offset, DataSink &sink) {
  19432. if (offset < 15) {
  19433. sink.write("chunk", 5);
  19434. return true;
  19435. }
  19436. sink.done();
  19437. return true;
  19438. });
  19439. });
  19440. svr_.Get("/compressible", [](const Request &, Response &res) {
  19441. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19442. DataSink &sink) {
  19443. if (offset < 100 * 1024) {
  19444. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19445. sink.write(chunk.data(), chunk.size());
  19446. return true;
  19447. }
  19448. sink.done();
  19449. return true;
  19450. });
  19451. });
  19452. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19453. [](const Request & /*req*/, Response &res) {
  19454. auto i = new int(0);
  19455. res.set_header("Trailer", "Content-Length, X-Allowed");
  19456. res.set_chunked_content_provider(
  19457. "text/plain",
  19458. [i](size_t /*offset*/, DataSink &sink) {
  19459. switch (*i) {
  19460. case 0: sink.os << "123"; break;
  19461. case 1: sink.os << "456"; break;
  19462. case 2: sink.os << "789"; break;
  19463. case 3: {
  19464. sink.done_with_trailer(
  19465. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19466. } break;
  19467. }
  19468. (*i)++;
  19469. return true;
  19470. },
  19471. [i](bool success) {
  19472. EXPECT_TRUE(success);
  19473. delete i;
  19474. });
  19475. });
  19476. // Echo headers endpoint for header-related tests
  19477. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19478. std::string body;
  19479. for (const auto &h : req.headers) {
  19480. body.append(h.first);
  19481. body.push_back(':');
  19482. body.append(h.second);
  19483. body.push_back('\n');
  19484. }
  19485. res.set_content(body, "text/plain");
  19486. });
  19487. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19488. std::string body;
  19489. for (const auto &h : req.headers) {
  19490. body.append(h.first);
  19491. body.push_back(':');
  19492. body.append(h.second);
  19493. body.push_back('\n');
  19494. }
  19495. res.set_content(body, "text/plain");
  19496. });
  19497. port_ = svr_.bind_to_any_port("127.0.0.1");
  19498. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19499. svr_.wait_until_ready();
  19500. }
  19501. void TearDown() override {
  19502. svr_.stop();
  19503. if (thread_.joinable()) thread_.join();
  19504. }
  19505. Server svr_;
  19506. std::thread thread_;
  19507. int port_ = 0;
  19508. };
  19509. TEST_F(OpenStreamTest, Basic) {
  19510. Client cli("127.0.0.1", port_);
  19511. auto handle = cli.open_stream("GET", "/hello");
  19512. EXPECT_TRUE(handle.is_valid());
  19513. EXPECT_EQ("Hello World!", read_all(handle));
  19514. }
  19515. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19516. Client cli("127.0.0.1", port_);
  19517. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19518. ASSERT_TRUE(handle.is_valid());
  19519. EXPECT_EQ("Hello World!", read_all(handle));
  19520. }
  19521. TEST_F(OpenStreamTest, SmallBuffer) {
  19522. Client cli("127.0.0.1", port_);
  19523. auto handle = cli.open_stream("GET", "/hello");
  19524. std::string result;
  19525. char buf[4];
  19526. ssize_t n;
  19527. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19528. result.append(buf, static_cast<size_t>(n));
  19529. EXPECT_EQ("Hello World!", result);
  19530. }
  19531. TEST_F(OpenStreamTest, DefaultHeaders) {
  19532. Client cli("127.0.0.1", port_);
  19533. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19534. {
  19535. auto handle = cli.open_stream("GET", "/echo-headers");
  19536. ASSERT_TRUE(handle.is_valid());
  19537. auto body = read_all(handle);
  19538. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19539. std::string::npos);
  19540. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19541. std::string::npos);
  19542. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19543. }
  19544. // open_stream POST with body and no explicit content_type should NOT add
  19545. // text/plain Content-Type (behavior differs from non-streaming path), but
  19546. // should include Content-Length
  19547. {
  19548. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19549. ASSERT_TRUE(handle.is_valid());
  19550. auto body = read_all(handle);
  19551. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19552. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19553. }
  19554. // open_stream POST with explicit Content-Type should preserve it
  19555. {
  19556. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19557. {{"Content-Type", "application/custom"}},
  19558. "{}", "application/custom");
  19559. ASSERT_TRUE(handle.is_valid());
  19560. auto body = read_all(handle);
  19561. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19562. }
  19563. // User-specified User-Agent must not be overwritten for stream API
  19564. {
  19565. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19566. {{"User-Agent", "MyAgent/1.2"}});
  19567. ASSERT_TRUE(handle.is_valid());
  19568. auto body = read_all(handle);
  19569. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19570. }
  19571. }
  19572. TEST_F(OpenStreamTest, Large) {
  19573. Client cli("127.0.0.1", port_);
  19574. auto handle = cli.open_stream("GET", "/large");
  19575. EXPECT_EQ(10000u, read_all(handle).size());
  19576. }
  19577. TEST_F(OpenStreamTest, ConnectionError) {
  19578. Client cli("127.0.0.1", 9999);
  19579. auto handle = cli.open_stream("GET", "/hello");
  19580. EXPECT_FALSE(handle.is_valid());
  19581. }
  19582. TEST_F(OpenStreamTest, Chunked) {
  19583. Client cli("127.0.0.1", port_);
  19584. auto handle = cli.open_stream("GET", "/chunked");
  19585. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19586. "Transfer-Encoding") == "chunked");
  19587. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19588. }
  19589. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19590. Client cli("127.0.0.1", port_);
  19591. auto handle =
  19592. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19593. ASSERT_TRUE(handle.is_valid());
  19594. // Consume body to allow trailers to be received/parsed
  19595. auto body = read_all(handle);
  19596. // Explicitly parse trailers (ensure trailers are available for assertion)
  19597. handle.parse_trailers_if_needed();
  19598. EXPECT_EQ(std::string("123456789"), body);
  19599. // The response should include a Trailer header declaring both names
  19600. ASSERT_TRUE(handle.response);
  19601. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19602. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19603. handle.response->get_header_value("Trailer"));
  19604. // Prohibited trailer must not be present
  19605. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19606. // Allowed trailer should be present
  19607. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19608. EXPECT_EQ(std::string("yes"),
  19609. handle.response->get_trailer_value("X-Allowed"));
  19610. // Verify trailers are NOT present as regular headers
  19611. EXPECT_EQ(std::string(""),
  19612. handle.response->get_header_value("Content-Length"));
  19613. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19614. }
  19615. // Accepts one connection on an OS-assigned port, which it hands over through
  19616. // port_promise, reads the request head and sends back response. after_send,
  19617. // if given, runs on the connection before it is closed.
  19618. static std::thread
  19619. serve_single_response(std::promise<int> &port_promise,
  19620. const std::string &response,
  19621. std::function<void(socket_t)> after_send = nullptr) {
  19622. return std::thread([&port_promise, response, after_send] {
  19623. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19624. default_socket_options(srv);
  19625. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19626. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19627. sockaddr_in addr{};
  19628. addr.sin_family = AF_INET;
  19629. addr.sin_port = htons(0); // Let OS assign a free port
  19630. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19631. int opt = 1;
  19632. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19633. #ifdef _WIN32
  19634. reinterpret_cast<const char *>(&opt),
  19635. #else
  19636. &opt,
  19637. #endif
  19638. sizeof(opt));
  19639. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19640. ::listen(srv, 1) != 0) {
  19641. port_promise.set_value(-1);
  19642. detail::close_socket(srv);
  19643. return;
  19644. }
  19645. socklen_t addr_len = sizeof(addr);
  19646. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19647. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19648. sockaddr_in cli_addr{};
  19649. socklen_t cli_len = sizeof(cli_addr);
  19650. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19651. if (cli != INVALID_SOCKET) {
  19652. // Read the complete HTTP request (until the blank line that terminates
  19653. // headers) before sending the response. If the server closes the socket
  19654. // while the client's request data is still unread in the kernel receive
  19655. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19656. // connection on both sides: it discards the client's receive buffer
  19657. // (which already holds our response) and causes any in-progress write on
  19658. // the client to fail with ECONNRESET. Reading all request data first
  19659. // ensures close() emits a graceful FIN.
  19660. {
  19661. char rbuf[256];
  19662. std::string req;
  19663. while (req.find("\r\n\r\n") == std::string::npos) {
  19664. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19665. if (n <= 0) { break; }
  19666. req.append(rbuf, static_cast<size_t>(n));
  19667. }
  19668. }
  19669. ::send(cli,
  19670. #ifdef _WIN32
  19671. static_cast<const char *>(response.c_str()),
  19672. static_cast<int>(response.size()),
  19673. #else
  19674. response.c_str(), response.size(),
  19675. #endif
  19676. 0);
  19677. if (after_send) { after_send(cli); }
  19678. detail::close_socket(cli);
  19679. }
  19680. detail::close_socket(srv);
  19681. });
  19682. }
  19683. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19684. #ifndef _WIN32
  19685. signal(SIGPIPE, SIG_IGN);
  19686. #endif
  19687. std::promise<int> port_promise;
  19688. auto port_future = port_promise.get_future();
  19689. auto server_thread =
  19690. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19691. "Content-Type: text/plain\r\n"
  19692. "Content-Length: not-a-number\r\n"
  19693. "Connection: close\r\n"
  19694. "\r\n"
  19695. "hello");
  19696. auto port = port_future.get();
  19697. ASSERT_GT(port, 0);
  19698. Client cli("127.0.0.1", port);
  19699. auto handle = cli.open_stream("GET", "/");
  19700. EXPECT_FALSE(handle.is_valid());
  19701. server_thread.join();
  19702. }
  19703. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19704. #ifndef _WIN32
  19705. signal(SIGPIPE, SIG_IGN);
  19706. #endif
  19707. std::promise<int> port_promise;
  19708. auto port_future = port_promise.get_future();
  19709. auto server_thread = serve_single_response(
  19710. port_promise, "HTTP/1.1 200 OK\r\n"
  19711. "Content-Type: text/plain\r\n"
  19712. "Content-Length: 99999999999999999999999999\r\n"
  19713. "Connection: close\r\n"
  19714. "\r\n"
  19715. "hello");
  19716. auto port = port_future.get();
  19717. ASSERT_GT(port, 0);
  19718. // Historically std::stoull would throw std::out_of_range here and crash
  19719. // the process, then parsing silently clamped to a bogus framing length and
  19720. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19721. // so the stream fails to open, matching the not-a-number case above. The
  19722. // process still must NOT terminate.
  19723. Client cli("127.0.0.1", port);
  19724. auto handle = cli.open_stream("GET", "/");
  19725. EXPECT_FALSE(handle.is_valid());
  19726. server_thread.join();
  19727. }
  19728. // Serves `response` to the single request `fn` makes with a fresh client.
  19729. template <typename Fn>
  19730. static void with_single_response(const std::string &response, Fn fn) {
  19731. #ifndef _WIN32
  19732. signal(SIGPIPE, SIG_IGN);
  19733. #endif
  19734. std::promise<int> port_promise;
  19735. auto port_future = port_promise.get_future();
  19736. auto server_thread = serve_single_response(port_promise, response);
  19737. auto se = detail::scope_exit([&] { server_thread.join(); });
  19738. auto port = port_future.get();
  19739. ASSERT_GT(port, 0);
  19740. Client cli("127.0.0.1", port);
  19741. fn(cli);
  19742. }
  19743. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19744. // Neither Content-Length nor chunked: the body ends at the close
  19745. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19746. "Connection: close\r\n"
  19747. "\r\n"
  19748. "hello";
  19749. with_single_response(close_delimited, [](Client &cli) {
  19750. auto handle = cli.open_stream("GET", "/");
  19751. ASSERT_TRUE(handle.is_valid());
  19752. EXPECT_EQ("hello", read_all(handle));
  19753. EXPECT_FALSE(handle.has_read_error());
  19754. });
  19755. // A close before the end of the Content-Length is still an error
  19756. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19757. "Content-Length: 10\r\n"
  19758. "\r\n"
  19759. "hello";
  19760. with_single_response(short_content_length, [](Client &cli) {
  19761. auto handle = cli.open_stream("GET", "/");
  19762. ASSERT_TRUE(handle.is_valid());
  19763. read_all(handle);
  19764. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19765. });
  19766. // So is a close before the last chunk
  19767. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19768. "Transfer-Encoding: chunked\r\n"
  19769. "\r\n"
  19770. "5\r\nhello\r\n";
  19771. with_single_response(short_chunked, [](Client &cli) {
  19772. auto handle = cli.open_stream("GET", "/");
  19773. ASSERT_TRUE(handle.is_valid());
  19774. read_all(handle);
  19775. EXPECT_TRUE(handle.has_read_error());
  19776. });
  19777. }
  19778. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19779. const char *responses[] = {
  19780. "HTTP/1.1 103 Early Hints\r\n"
  19781. "Link: </style.css>; rel=preload\r\n"
  19782. "\r\n"
  19783. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19784. "HTTP/1.1 100 Continue\r\n"
  19785. "X-Note: interim\r\n"
  19786. "\r\n"
  19787. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19788. };
  19789. for (auto response : responses) {
  19790. with_single_response(response, [](Client &cli) {
  19791. auto res = cli.Get("/");
  19792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19793. EXPECT_EQ(StatusCode::OK_200, res->status);
  19794. EXPECT_EQ("ok", res->body);
  19795. });
  19796. }
  19797. }
  19798. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19799. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19800. const std::string final_response =
  19801. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19802. std::string interims;
  19803. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19804. interims += interim;
  19805. }
  19806. with_single_response(interims + final_response, [](Client &cli) {
  19807. auto res = cli.Get("/");
  19808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19809. EXPECT_EQ("ok", res->body);
  19810. });
  19811. with_single_response(interims + interim + final_response, [](Client &cli) {
  19812. auto res = cli.Get("/");
  19813. ASSERT_FALSE(res);
  19814. EXPECT_EQ(Error::Read, res.error());
  19815. });
  19816. }
  19817. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19818. #ifndef _WIN32
  19819. signal(SIGPIPE, SIG_IGN);
  19820. #endif
  19821. // The server answers the head without asking for the body. Bytes it then
  19822. // reads on the connection would be taken for the body the request declared.
  19823. auto closed_by_client = false;
  19824. std::promise<int> port_promise;
  19825. auto server_thread = serve_single_response(
  19826. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19827. [&](socket_t sock) {
  19828. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19829. char buf[256];
  19830. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19831. });
  19832. Client cli("127.0.0.1", port_promise.get_future().get());
  19833. cli.set_keep_alive(true);
  19834. cli.set_read_timeout(1, 0);
  19835. // Long enough for the client to send Expect: 100-continue.
  19836. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19838. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19839. cli.Get("/second");
  19840. server_thread.join();
  19841. EXPECT_TRUE(closed_by_client);
  19842. }
  19843. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19844. // Long enough for the client to send Expect: 100-continue
  19845. with_single_response(
  19846. "HTTP/1.1 103 Early Hints\r\n"
  19847. "Link: </style.css>; rel=preload\r\n"
  19848. "\r\n"
  19849. "HTTP/1.1 401 Unauthorized\r\n"
  19850. "Content-Length: 0\r\n\r\n",
  19851. [](Client &cli) {
  19852. cli.set_read_timeout(2, 0);
  19853. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19855. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19856. });
  19857. }
  19858. #ifdef CPPHTTPLIB_SSL_ENABLED
  19859. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19860. #ifndef _WIN32
  19861. signal(SIGPIPE, SIG_IGN);
  19862. #endif
  19863. auto reused = false;
  19864. std::promise<int> port_promise;
  19865. auto server_thread = serve_single_response(
  19866. port_promise,
  19867. "HTTP/1.1 401 Unauthorized\r\n"
  19868. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19869. "Content-Length: 0\r\n\r\n",
  19870. [&](socket_t sock) {
  19871. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19872. char buf[256];
  19873. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19874. });
  19875. Client cli("127.0.0.1", port_promise.get_future().get());
  19876. cli.set_keep_alive(true);
  19877. cli.set_digest_auth("user", "pass");
  19878. cli.set_read_timeout(1, 0);
  19879. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19880. server_thread.join();
  19881. EXPECT_FALSE(reused);
  19882. }
  19883. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19884. // Any other answer to CONNECT would read as the origin's response.
  19885. struct {
  19886. const char *response;
  19887. bool passed_on;
  19888. } cases[] = {
  19889. {"HTTP/1.1 201 Created\r\n"
  19890. "Set-Cookie: session=from-proxy\r\n"
  19891. "Content-Length: 0\r\n\r\n",
  19892. false},
  19893. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19894. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19895. "Content-Length: 0\r\n\r\n",
  19896. true},
  19897. };
  19898. for (const auto &c : cases) {
  19899. std::promise<int> port_promise;
  19900. auto server_thread = serve_single_response(port_promise, c.response);
  19901. SSLClient cli("example.com", 443);
  19902. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19903. auto res = cli.Get("/");
  19904. server_thread.join();
  19905. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19906. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19907. if (res) {
  19908. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19909. }
  19910. }
  19911. }
  19912. #endif
  19913. // Records the client's error logger calls as "error METHOD path", or
  19914. // "error null" for a call without a request
  19915. static ErrorLogger record_errors(std::vector<std::string> &log) {
  19916. return [&log](const Error &err, const Request *req) {
  19917. log.push_back(to_string(err) + " " +
  19918. (req ? req->method + " " + req->path : "null"));
  19919. };
  19920. }
  19921. // A failed request is reported once, with the request the caller made
  19922. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  19923. Server svr;
  19924. svr.Get("/big", [](const Request &, Response &res) {
  19925. res.set_content(std::string(100000, 'b'), "text/plain");
  19926. });
  19927. auto port = svr.bind_to_any_port(HOST);
  19928. std::thread t([&]() { svr.listen_after_bind(); });
  19929. auto se = detail::scope_exit([&] {
  19930. svr.stop();
  19931. t.join();
  19932. });
  19933. svr.wait_until_ready();
  19934. Client cli(HOST, port);
  19935. std::vector<std::string> log;
  19936. cli.set_error_logger(record_errors(log));
  19937. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  19938. cli.Get("/big", [](const char *, size_t) { return false; });
  19939. EXPECT_EQ(expected, log);
  19940. log.clear();
  19941. cli.Get("/big", [](size_t, size_t) { return false; });
  19942. EXPECT_EQ(expected, log);
  19943. }
  19944. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  19945. // Fails while the body is read
  19946. auto broken = [](const Request &, Response &res) {
  19947. res.set_content_provider(10, "text/plain",
  19948. [](size_t, size_t, DataSink &) { return false; });
  19949. };
  19950. Server other;
  19951. other.Get("/broken", broken);
  19952. auto other_port = other.bind_to_any_port(HOST);
  19953. std::thread other_t([&]() { other.listen_after_bind(); });
  19954. auto other_se = detail::scope_exit([&] {
  19955. other.stop();
  19956. other_t.join();
  19957. });
  19958. other.wait_until_ready();
  19959. Server svr;
  19960. svr.Get("/broken", broken);
  19961. svr.Get("/same-origin",
  19962. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  19963. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  19964. res.set_redirect("http://" + std::string(HOST) + ":" +
  19965. std::to_string(other_port) + "/broken");
  19966. });
  19967. auto port = svr.bind_to_any_port(HOST);
  19968. std::thread t([&]() { svr.listen_after_bind(); });
  19969. auto se = detail::scope_exit([&] {
  19970. svr.stop();
  19971. t.join();
  19972. });
  19973. svr.wait_until_ready();
  19974. Client cli(HOST, port);
  19975. cli.set_follow_location(true);
  19976. std::vector<std::string> log;
  19977. cli.set_error_logger(record_errors(log));
  19978. for (auto path : {"/same-origin", "/cross-origin"}) {
  19979. log.clear();
  19980. auto res = cli.Get(path);
  19981. ASSERT_FALSE(res);
  19982. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  19983. log);
  19984. }
  19985. }
  19986. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  19987. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  19988. std::vector<std::string> log;
  19989. cli.set_error_logger(record_errors(log));
  19990. auto handle = cli.open_stream("GET", "/x");
  19991. EXPECT_FALSE(handle.is_valid());
  19992. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  19993. log);
  19994. });
  19995. }
  19996. #ifdef CPPHTTPLIB_SSL_ENABLED
  19997. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  19998. // Not a TLS server, so the handshake fails. It waits for a request line in
  19999. // the handshake bytes, so a short read timeout lets it close quickly.
  20000. Server svr;
  20001. svr.set_read_timeout(0, 100000);
  20002. svr.Get("/x", [](const Request &, Response &res) {
  20003. res.set_content("x", "text/plain");
  20004. });
  20005. auto port = svr.bind_to_any_port(HOST);
  20006. std::thread t([&]() { svr.listen_after_bind(); });
  20007. auto se = detail::scope_exit([&] {
  20008. svr.stop();
  20009. t.join();
  20010. });
  20011. svr.wait_until_ready();
  20012. std::vector<std::string> log;
  20013. SSLClient cli(HOST, port);
  20014. cli.enable_server_certificate_verification(false);
  20015. cli.set_error_logger(record_errors(log));
  20016. auto res = cli.Get("/x");
  20017. ASSERT_FALSE(res);
  20018. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20019. log.clear();
  20020. auto handle = cli.open_stream("GET", "/x");
  20021. EXPECT_FALSE(handle.is_valid());
  20022. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20023. log.clear();
  20024. SSLClient no_ca(HOST, port);
  20025. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20026. no_ca.set_error_logger(record_errors(log));
  20027. res = no_ca.Get("/x");
  20028. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20029. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20030. }
  20031. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20032. #ifndef _WIN32
  20033. signal(SIGPIPE, SIG_IGN);
  20034. #endif
  20035. // Refused, answered with a challenge, or closed without an answer
  20036. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20037. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20038. "Content-Length: 0\r\n\r\n",
  20039. ""}) {
  20040. std::promise<int> port_promise;
  20041. auto server_thread = serve_single_response(port_promise, response);
  20042. SSLClient cli("example.com", 443);
  20043. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20044. std::vector<std::string> log;
  20045. cli.set_error_logger(record_errors(log));
  20046. auto res = cli.Get("/");
  20047. server_thread.join();
  20048. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20049. << response;
  20050. }
  20051. }
  20052. #endif
  20053. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20054. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20055. // the chunked coding and drop Content-Length, so a front-end that trusts
  20056. // Content-Length would disagree about where the body ends (response
  20057. // smuggling). The client must reject such a response.
  20058. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20059. for (const char *te : {"chunked", "gzip, chunked"}) {
  20060. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20061. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20062. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20063. "5\r\nhello\r\n0\r\n\r\n";
  20064. with_single_response(response, [&](Client &cli) {
  20065. auto res = cli.Get("/");
  20066. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20067. EXPECT_EQ(Error::Read, res.error()) << te;
  20068. });
  20069. with_single_response(response, [&](Client &cli) {
  20070. auto handle = cli.open_stream("GET", "/");
  20071. EXPECT_FALSE(handle.is_valid()) << te;
  20072. EXPECT_EQ(Error::Read, handle.error) << te;
  20073. });
  20074. }
  20075. }
  20076. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20077. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20078. // closing the connection (unlike a request, which must be rejected).
  20079. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20080. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20081. "Transfer-Encoding: chunked\r\n"
  20082. "Connection: close\r\n"
  20083. "\r\n"
  20084. "5\r\nhello\r\n0\r\n\r\n",
  20085. "HTTP/1.1 200 OK\r\n"
  20086. "Transfer-Encoding: gzip\r\n"
  20087. "Connection: close\r\n"
  20088. "\r\n"
  20089. "hello"}) {
  20090. with_single_response(response, [&](Client &cli) {
  20091. auto res = cli.Get("/");
  20092. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20093. EXPECT_EQ("hello", res->body);
  20094. });
  20095. with_single_response(response, [&](Client &cli) {
  20096. auto handle = cli.open_stream("GET", "/");
  20097. ASSERT_TRUE(handle.is_valid()) << response;
  20098. EXPECT_EQ("hello", read_all(handle));
  20099. });
  20100. }
  20101. }
  20102. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20103. // framing headers describe nothing to read and must not be rejected.
  20104. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20105. const std::string framing = "Content-Length: 5\r\n"
  20106. "Transfer-Encoding: chunked\r\n"
  20107. "Connection: close\r\n"
  20108. "\r\n";
  20109. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20110. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20111. });
  20112. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20113. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20114. });
  20115. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20116. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20117. with_single_response(response, [&](Client &cli) {
  20118. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20119. });
  20120. with_single_response(response, [&](Client &cli) {
  20121. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20122. });
  20123. }
  20124. }
  20125. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20126. // header section, so a stream opened on one has nothing to read, whatever
  20127. // framing or coding headers it carries.
  20128. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20129. struct Case {
  20130. const char *method;
  20131. const char *status;
  20132. };
  20133. // A reader of the declared body reports an early close when nothing
  20134. // follows, and hands back what does.
  20135. struct Framing {
  20136. const char *headers;
  20137. const char *after;
  20138. };
  20139. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20140. Case{"GET", "304 Not Modified"}}) {
  20141. for (const auto &f :
  20142. {Framing{"Content-Length: 5\r\n", ""},
  20143. Framing{"Content-Length: 5\r\n", "hello"},
  20144. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20145. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20146. // Not decoded, so a build without Brotli opens it too
  20147. Framing{"Content-Encoding: br\r\n", ""}}) {
  20148. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20149. "Connection: close\r\n"
  20150. "\r\n" +
  20151. f.after;
  20152. with_single_response(response, [&](Client &cli) {
  20153. auto handle = cli.open_stream(c.method, "/");
  20154. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20155. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20156. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20157. });
  20158. }
  20159. }
  20160. }
  20161. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20162. // response, is faulty framing, so the connection is not reused after it.
  20163. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20164. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20165. "Content-Length: 0\r\n"
  20166. "Transfer-Encoding: chunked\r\n"
  20167. "\r\n"
  20168. "5\r\nhello\r\n0\r\n\r\n",
  20169. "HTTP/1.0 200 Connection established\r\n"
  20170. "Connection: keep-alive\r\n"
  20171. "Transfer-Encoding: chunked\r\n"
  20172. "\r\n"
  20173. "5\r\nhello\r\n0\r\n\r\n"}) {
  20174. with_single_response(response, [&](Client &cli) {
  20175. cli.set_keep_alive(true);
  20176. auto res = cli.Get("/");
  20177. ASSERT_TRUE(res) << response;
  20178. EXPECT_EQ("hello", res->body);
  20179. EXPECT_FALSE(cli.is_socket_open()) << response;
  20180. });
  20181. }
  20182. }
  20183. // A payload max length of 0 means no limit, however the body is framed.
  20184. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20185. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20186. "Transfer-Encoding: chunked\r\n"
  20187. "\r\n"
  20188. "5\r\nhello\r\n0\r\n\r\n",
  20189. "HTTP/1.1 200 OK\r\n"
  20190. "Connection: close\r\n"
  20191. "\r\n"
  20192. "hello"}) {
  20193. with_single_response(response, [&](Client &cli) {
  20194. cli.set_payload_max_length(0);
  20195. auto res = cli.Get("/");
  20196. ASSERT_TRUE(res) << response;
  20197. EXPECT_EQ("hello", res->body) << response;
  20198. });
  20199. }
  20200. }
  20201. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20202. Server svr;
  20203. svr.set_payload_max_length(0);
  20204. svr.Post("/echo", [](const Request &req, Response &res) {
  20205. res.set_content(req.body, "text/plain");
  20206. });
  20207. auto port = svr.bind_to_any_port(HOST);
  20208. thread t = thread([&] { svr.listen_after_bind(); });
  20209. auto se = detail::scope_exit([&] {
  20210. svr.stop();
  20211. t.join();
  20212. ASSERT_FALSE(svr.is_running());
  20213. });
  20214. svr.wait_until_ready();
  20215. Client cli(HOST, port);
  20216. auto res = cli.Post(
  20217. "/echo",
  20218. [](size_t /*offset*/, DataSink &sink) {
  20219. sink.write("hello", 5);
  20220. sink.done();
  20221. return true;
  20222. },
  20223. "text/plain");
  20224. ASSERT_TRUE(res);
  20225. EXPECT_EQ(StatusCode::OK_200, res->status);
  20226. EXPECT_EQ("hello", res->body);
  20227. }
  20228. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20229. TEST_F(OpenStreamTest, Gzip) {
  20230. Client cli("127.0.0.1", port_);
  20231. auto handle = cli.open_stream("GET", "/compressible", {},
  20232. {{"Accept-Encoding", "gzip"}});
  20233. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20234. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20235. }
  20236. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20237. Client cli("127.0.0.1", port_);
  20238. auto handle =
  20239. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20240. {{"Accept-Encoding", "gzip"}});
  20241. ASSERT_TRUE(handle.is_valid());
  20242. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20243. EXPECT_EQ("123456789", read_all(handle));
  20244. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20245. }
  20246. #endif
  20247. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20248. TEST_F(OpenStreamTest, Brotli) {
  20249. Client cli("127.0.0.1", port_);
  20250. auto handle =
  20251. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20252. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20253. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20254. }
  20255. #endif
  20256. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20257. TEST_F(OpenStreamTest, Zstd) {
  20258. Client cli("127.0.0.1", port_);
  20259. auto handle = cli.open_stream("GET", "/compressible", {},
  20260. {{"Accept-Encoding", "zstd"}});
  20261. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20262. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20263. }
  20264. #endif
  20265. #ifdef CPPHTTPLIB_SSL_ENABLED
  20266. class SSLOpenStreamTest : public ::testing::Test {
  20267. protected:
  20268. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20269. void SetUp() override {
  20270. svr_.Get("/hello", [](const Request &, Response &res) {
  20271. res.set_content("Hello SSL World!", "text/plain");
  20272. });
  20273. svr_.Get("/chunked", [](const Request &, Response &res) {
  20274. res.set_chunked_content_provider("text/plain",
  20275. [](size_t offset, DataSink &sink) {
  20276. if (offset < 15) {
  20277. sink.write("chunk", 5);
  20278. return true;
  20279. }
  20280. sink.done();
  20281. return true;
  20282. });
  20283. });
  20284. svr_.Post("/echo", [](const Request &req, Response &res) {
  20285. res.set_content(req.body, req.get_header_value("Content-Type"));
  20286. });
  20287. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20288. std::string body = req.body;
  20289. res.set_chunked_content_provider(
  20290. "text/plain", [body](size_t offset, DataSink &sink) {
  20291. if (offset < body.size()) {
  20292. sink.write(body.data() + offset, body.size() - offset);
  20293. }
  20294. sink.done();
  20295. return true;
  20296. });
  20297. });
  20298. port_ = svr_.bind_to_any_port("127.0.0.1");
  20299. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20300. svr_.wait_until_ready();
  20301. }
  20302. void TearDown() override {
  20303. svr_.stop();
  20304. if (thread_.joinable()) thread_.join();
  20305. }
  20306. SSLServer svr_;
  20307. std::thread thread_;
  20308. int port_ = 0;
  20309. };
  20310. TEST_F(SSLOpenStreamTest, Basic) {
  20311. SSLClient cli("127.0.0.1", port_);
  20312. cli.enable_server_certificate_verification(false);
  20313. auto handle = cli.open_stream("GET", "/hello");
  20314. ASSERT_TRUE(handle.is_valid());
  20315. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20316. }
  20317. TEST_F(SSLOpenStreamTest, Chunked) {
  20318. SSLClient cli("127.0.0.1", port_);
  20319. cli.enable_server_certificate_verification(false);
  20320. auto handle = cli.open_stream("GET", "/chunked");
  20321. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20322. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20323. "Transfer-Encoding") == "chunked");
  20324. auto body = read_all(handle);
  20325. EXPECT_EQ("chunkchunkchunk", body);
  20326. }
  20327. TEST_F(SSLOpenStreamTest, Post) {
  20328. SSLClient cli("127.0.0.1", port_);
  20329. cli.enable_server_certificate_verification(false);
  20330. auto handle =
  20331. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20332. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20333. EXPECT_EQ(200, handle.response->status);
  20334. auto body = read_all(handle);
  20335. EXPECT_EQ("Hello SSL POST", body);
  20336. }
  20337. TEST_F(SSLOpenStreamTest, PostChunked) {
  20338. SSLClient cli("127.0.0.1", port_);
  20339. cli.enable_server_certificate_verification(false);
  20340. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20341. "Chunked SSL Data", "text/plain");
  20342. ASSERT_TRUE(handle.is_valid());
  20343. EXPECT_EQ(200, handle.response->status);
  20344. auto body = read_all(handle);
  20345. EXPECT_EQ("Chunked SSL Data", body);
  20346. }
  20347. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20348. // Content-Length is terminated by the server closing the connection. When the
  20349. // SSL peer sends a close_notify after the body, the client must treat it as a
  20350. // clean EOF and return a successful response rather than an error.
  20351. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20352. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20353. ASSERT_TRUE(svr.is_valid());
  20354. svr.set_keep_alive_max_count(1);
  20355. const std::string expected_body = "Hello from connection-close response!";
  20356. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20357. res.set_content_provider("text/plain",
  20358. [&](size_t offset, DataSink &sink) -> bool {
  20359. if (offset < expected_body.size()) {
  20360. sink.write(expected_body.data() + offset,
  20361. expected_body.size() - offset);
  20362. }
  20363. sink.done();
  20364. return true;
  20365. });
  20366. });
  20367. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20368. auto se = detail::scope_exit([&] {
  20369. svr.stop();
  20370. listen_thread.join();
  20371. ASSERT_FALSE(svr.is_running());
  20372. });
  20373. svr.wait_until_ready();
  20374. SSLClient cli(HOST, PORT);
  20375. cli.enable_server_certificate_verification(false);
  20376. auto res = cli.Get("/no-content-length");
  20377. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20378. EXPECT_EQ(StatusCode::OK_200, res->status);
  20379. EXPECT_EQ(expected_body, res->body);
  20380. }
  20381. #endif // CPPHTTPLIB_SSL_ENABLED
  20382. //==============================================================================
  20383. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20384. // results for various scenarios.
  20385. //==============================================================================
  20386. TEST(ParityTest, GetVsOpenStream) {
  20387. Server svr;
  20388. const std::string path = "/parity";
  20389. const std::string content = "Parity test content: hello world";
  20390. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20391. res.set_content(content, "text/plain");
  20392. });
  20393. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20394. auto se = detail::scope_exit([&] {
  20395. svr.stop();
  20396. t.join();
  20397. ASSERT_FALSE(svr.is_running());
  20398. });
  20399. svr.wait_until_ready();
  20400. Client cli(HOST, PORT);
  20401. // Non-stream path
  20402. auto r1 = cli.Get(path);
  20403. ASSERT_TRUE(r1);
  20404. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20405. // Stream path
  20406. auto h = cli.open_stream("GET", path);
  20407. ASSERT_TRUE(h.is_valid());
  20408. EXPECT_EQ(r1->body, read_all(h));
  20409. }
  20410. // Helper to compress data with provided compressor type T
  20411. template <typename Compressor>
  20412. static std::string compress_payload_for_parity(const std::string &in) {
  20413. std::string out;
  20414. Compressor compressor;
  20415. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20416. [&](const char *data, size_t n) {
  20417. out.append(data, n);
  20418. return true;
  20419. });
  20420. EXPECT_TRUE(ok);
  20421. return out;
  20422. }
  20423. // Helper function for compression parity tests
  20424. template <typename Compressor>
  20425. static void test_compression_parity(const std::string &original,
  20426. const std::string &path,
  20427. const std::string &encoding) {
  20428. const std::string compressed =
  20429. compress_payload_for_parity<Compressor>(original);
  20430. Server svr;
  20431. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20432. res.set_content(compressed, "application/octet-stream");
  20433. res.set_header("Content-Encoding", encoding);
  20434. });
  20435. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20436. auto se = detail::scope_exit([&] {
  20437. svr.stop();
  20438. t.join();
  20439. ASSERT_FALSE(svr.is_running());
  20440. });
  20441. svr.wait_until_ready();
  20442. Client cli(HOST, PORT);
  20443. // Non-streaming
  20444. {
  20445. auto res = cli.Get(path);
  20446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20447. EXPECT_EQ(StatusCode::OK_200, res->status);
  20448. EXPECT_EQ(original, res->body);
  20449. }
  20450. // Streaming
  20451. {
  20452. auto h = cli.open_stream("GET", path);
  20453. ASSERT_TRUE(h.is_valid());
  20454. EXPECT_EQ(original, read_all(h));
  20455. }
  20456. }
  20457. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20458. TEST(ParityTest, Gzip) {
  20459. test_compression_parity<detail::gzip_compressor>(
  20460. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20461. }
  20462. #endif
  20463. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20464. TEST(ParityTest, Brotli) {
  20465. test_compression_parity<detail::brotli_compressor>(
  20466. "Hello, brotli parity test payload", "/parity-br", "br");
  20467. }
  20468. #endif
  20469. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20470. TEST(ParityTest, Zstd) {
  20471. test_compression_parity<detail::zstd_compressor>(
  20472. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20473. }
  20474. #endif
  20475. //==============================================================================
  20476. // New Stream API Tests
  20477. //==============================================================================
  20478. inline std::string read_body(httplib::stream::Result &result) {
  20479. std::string body;
  20480. while (result.next()) {
  20481. body.append(result.data(), result.size());
  20482. }
  20483. return body;
  20484. }
  20485. TEST(ClientConnectionTest, Basic) {
  20486. httplib::ClientConnection conn;
  20487. EXPECT_FALSE(conn.is_open());
  20488. conn.sock = 1;
  20489. EXPECT_TRUE(conn.is_open());
  20490. httplib::ClientConnection conn2(std::move(conn));
  20491. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20492. conn2.sock = INVALID_SOCKET;
  20493. }
  20494. // Unified test server for all stream::* tests
  20495. class StreamApiTest : public ::testing::Test {
  20496. protected:
  20497. void SetUp() override {
  20498. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20499. res.set_content("Hello World!", "text/plain");
  20500. });
  20501. svr_.Get("/echo-params",
  20502. [](const httplib::Request &req, httplib::Response &res) {
  20503. std::string r;
  20504. for (const auto &p : req.params) {
  20505. if (!r.empty()) r += "&";
  20506. r += p.first + "=" + p.second;
  20507. }
  20508. res.set_content(r, "text/plain");
  20509. });
  20510. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20511. res.set_content(req.body, req.get_header_value("Content-Type"));
  20512. });
  20513. svr_.Post("/echo-headers",
  20514. [](const httplib::Request &req, httplib::Response &res) {
  20515. std::string r;
  20516. for (const auto &h : req.headers)
  20517. r += h.first + ": " + h.second + "\n";
  20518. res.set_content(r, "text/plain");
  20519. });
  20520. svr_.Post("/echo-params",
  20521. [](const httplib::Request &req, httplib::Response &res) {
  20522. std::string r = "params:";
  20523. for (const auto &p : req.params)
  20524. r += p.first + "=" + p.second + ";";
  20525. res.set_content(r + " body:" + req.body, "text/plain");
  20526. });
  20527. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20528. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20529. });
  20530. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20531. res.set_content("PUT:" + req.body, "text/plain");
  20532. });
  20533. svr_.Patch("/echo",
  20534. [](const httplib::Request &req, httplib::Response &res) {
  20535. res.set_content("PATCH:" + req.body, "text/plain");
  20536. });
  20537. svr_.Delete(
  20538. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20539. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20540. "text/plain");
  20541. });
  20542. svr_.Get("/head-test",
  20543. [](const httplib::Request &, httplib::Response &res) {
  20544. res.set_content("body for HEAD", "text/plain");
  20545. });
  20546. svr_.Options("/options",
  20547. [](const httplib::Request &, httplib::Response &res) {
  20548. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20549. });
  20550. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20551. svr_.wait_until_ready();
  20552. }
  20553. void TearDown() override {
  20554. svr_.stop();
  20555. if (thread_.joinable()) thread_.join();
  20556. }
  20557. httplib::Server svr_;
  20558. std::thread thread_;
  20559. };
  20560. // stream::Get tests
  20561. TEST_F(StreamApiTest, GetBasic) {
  20562. httplib::Client cli(HOST, PORT);
  20563. auto result = httplib::stream::Get(cli, "/hello");
  20564. ASSERT_TRUE(result.is_valid());
  20565. EXPECT_EQ(200, result.status());
  20566. EXPECT_EQ("Hello World!", read_body(result));
  20567. }
  20568. TEST_F(StreamApiTest, GetWithParams) {
  20569. httplib::Client cli(HOST, PORT);
  20570. httplib::Params params{{"foo", "bar"}};
  20571. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20572. ASSERT_TRUE(result.is_valid());
  20573. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20574. }
  20575. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20576. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20577. httplib::Client cli(HOST, PORT);
  20578. cli.set_payload_max_length(0);
  20579. auto result = httplib::stream::Get(cli, "/hello");
  20580. ASSERT_TRUE(result.is_valid());
  20581. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20582. EXPECT_EQ("Hello World!", read_body(result));
  20583. }
  20584. #endif
  20585. TEST_F(StreamApiTest, GetConnectionError) {
  20586. httplib::Client cli(HOST, 9999);
  20587. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20588. }
  20589. TEST_F(StreamApiTest, Get404) {
  20590. httplib::Client cli(HOST, PORT);
  20591. auto result = httplib::stream::Get(cli, "/nonexistent");
  20592. EXPECT_TRUE(result.is_valid());
  20593. EXPECT_EQ(404, result.status());
  20594. }
  20595. // stream::Post tests
  20596. TEST_F(StreamApiTest, PostBasic) {
  20597. httplib::Client cli(HOST, PORT);
  20598. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20599. "application/json");
  20600. ASSERT_TRUE(result.is_valid());
  20601. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20602. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20603. }
  20604. TEST_F(StreamApiTest, PostWithHeaders) {
  20605. httplib::Client cli(HOST, PORT);
  20606. httplib::Headers headers{{"X-Custom", "value"}};
  20607. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20608. "text/plain");
  20609. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20610. }
  20611. TEST_F(StreamApiTest, PostWithParams) {
  20612. httplib::Client cli(HOST, PORT);
  20613. httplib::Params params{{"k", "v"}};
  20614. auto result =
  20615. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20616. auto body = read_body(result);
  20617. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20618. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20619. }
  20620. TEST_F(StreamApiTest, PostLarge) {
  20621. httplib::Client cli(HOST, PORT);
  20622. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20623. size_t total = 0;
  20624. while (result.next()) {
  20625. total += result.size();
  20626. }
  20627. EXPECT_EQ(100u * 1024u, total);
  20628. }
  20629. // stream::Put/Patch tests
  20630. TEST_F(StreamApiTest, PutAndPatch) {
  20631. httplib::Client cli(HOST, PORT);
  20632. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20633. EXPECT_EQ("PUT:test", read_body(put));
  20634. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20635. EXPECT_EQ("PATCH:test", read_body(patch));
  20636. }
  20637. // stream::Delete tests
  20638. TEST_F(StreamApiTest, Delete) {
  20639. httplib::Client cli(HOST, PORT);
  20640. auto del1 = httplib::stream::Delete(cli, "/resource");
  20641. EXPECT_EQ("Deleted", read_body(del1));
  20642. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20643. EXPECT_EQ("Deleted:data", read_body(del2));
  20644. }
  20645. // stream::Head/Options tests
  20646. TEST_F(StreamApiTest, HeadAndOptions) {
  20647. httplib::Client cli(HOST, PORT);
  20648. auto head = httplib::stream::Head(cli, "/head-test");
  20649. EXPECT_TRUE(head.is_valid());
  20650. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20651. auto opts = httplib::stream::Options(cli, "/options");
  20652. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20653. }
  20654. // SSL stream::* tests
  20655. #ifdef CPPHTTPLIB_SSL_ENABLED
  20656. class SSLStreamApiTest : public ::testing::Test {
  20657. protected:
  20658. void SetUp() override {
  20659. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20660. res.set_content("Hello SSL!", "text/plain");
  20661. });
  20662. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20663. res.set_content(req.body, "text/plain");
  20664. });
  20665. port_ = svr_.bind_to_any_port("127.0.0.1");
  20666. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20667. svr_.wait_until_ready();
  20668. }
  20669. void TearDown() override {
  20670. svr_.stop();
  20671. if (thread_.joinable()) thread_.join();
  20672. }
  20673. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20674. std::thread thread_;
  20675. int port_ = 0;
  20676. };
  20677. TEST_F(SSLStreamApiTest, GetAndPost) {
  20678. httplib::SSLClient cli("127.0.0.1", port_);
  20679. cli.enable_server_certificate_verification(false);
  20680. auto get = httplib::stream::Get(cli, "/hello");
  20681. EXPECT_EQ("Hello SSL!", read_body(get));
  20682. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20683. EXPECT_EQ("test", read_body(post));
  20684. }
  20685. #endif
  20686. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20687. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20688. // BodyReader
  20689. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20690. // Test that read timeout during streaming is detected
  20691. // Use a large content-length response where server delays mid-stream
  20692. Server svr;
  20693. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20694. // Send a large response with delay in the middle
  20695. res.set_content_provider(
  20696. 1000, // content_length
  20697. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20698. if (offset < 100) {
  20699. // Send first 100 bytes immediately
  20700. std::string data(100, 'A');
  20701. sink.write(data.c_str(), data.size());
  20702. return true;
  20703. }
  20704. // Then delay longer than client timeout
  20705. std::this_thread::sleep_for(std::chrono::seconds(3));
  20706. std::string data(900, 'B');
  20707. sink.write(data.c_str(), data.size());
  20708. return true;
  20709. });
  20710. });
  20711. auto port = 8091;
  20712. std::thread t([&]() { svr.listen("localhost", port); });
  20713. svr.wait_until_ready();
  20714. Client cli("localhost", port);
  20715. cli.set_read_timeout(1, 0); // 1 second timeout
  20716. auto handle = cli.open_stream("GET", "/slow-stream");
  20717. ASSERT_TRUE(handle.is_valid());
  20718. char buf[256];
  20719. ssize_t total = 0;
  20720. ssize_t n;
  20721. bool got_error = false;
  20722. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20723. total += n;
  20724. }
  20725. if (n < 0) {
  20726. got_error = true;
  20727. // Should be timeout or read error
  20728. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20729. handle.get_read_error() == Error::Read)
  20730. << "Actual error: " << to_string(handle.get_read_error());
  20731. }
  20732. // Either we got an error, or we got less data than expected
  20733. EXPECT_TRUE(got_error || total < 1000)
  20734. << "Expected timeout but got all " << total << " bytes";
  20735. svr.stop();
  20736. t.join();
  20737. }
  20738. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20739. // Test connection closed detection via BodyReader
  20740. Server svr;
  20741. std::atomic<bool> close_now{false};
  20742. svr.Get("/will-close", [&](const Request &, Response &res) {
  20743. res.set_content_provider(
  20744. 10000, // Large content_length that we won't fully send
  20745. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20746. if (offset < 100) {
  20747. std::string data(100, 'X');
  20748. sink.write(data.c_str(), data.size());
  20749. return true;
  20750. }
  20751. // Wait for signal then abort
  20752. while (!close_now) {
  20753. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20754. }
  20755. return false; // Abort - server will close connection
  20756. });
  20757. });
  20758. auto port = 8092;
  20759. std::thread t([&]() { svr.listen("localhost", port); });
  20760. svr.wait_until_ready();
  20761. Client cli("localhost", port);
  20762. auto handle = cli.open_stream("GET", "/will-close");
  20763. ASSERT_TRUE(handle.is_valid());
  20764. char buf[256];
  20765. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20766. EXPECT_GT(n, 0) << "First read should succeed";
  20767. // Signal server to close
  20768. close_now = true;
  20769. // Keep reading until error or EOF
  20770. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20771. // Keep reading
  20772. }
  20773. // Should get an error since content_length wasn't satisfied
  20774. if (n < 0) {
  20775. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20776. handle.get_read_error() == Error::Read)
  20777. << "Actual error: " << to_string(handle.get_read_error());
  20778. }
  20779. svr.stop();
  20780. t.join();
  20781. }
  20782. #ifdef CPPHTTPLIB_SSL_ENABLED
  20783. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20784. // Test that read timeout during SSL streaming is detected
  20785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20786. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20787. res.set_content_provider(
  20788. 1000, "text/plain",
  20789. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20790. if (offset < 100) {
  20791. std::string data(100, 'A');
  20792. sink.write(data.c_str(), data.size());
  20793. return true;
  20794. }
  20795. std::this_thread::sleep_for(std::chrono::seconds(3));
  20796. std::string data(900, 'B');
  20797. sink.write(data.c_str(), data.size());
  20798. return true;
  20799. });
  20800. });
  20801. auto port = 8093;
  20802. std::thread t([&]() { svr.listen("localhost", port); });
  20803. svr.wait_until_ready();
  20804. SSLClient cli("localhost", port);
  20805. cli.enable_server_certificate_verification(false);
  20806. cli.set_read_timeout(1, 0); // 1 second timeout
  20807. auto handle = cli.open_stream("GET", "/slow-stream");
  20808. ASSERT_TRUE(handle.is_valid());
  20809. char buf[256];
  20810. ssize_t total = 0;
  20811. ssize_t n;
  20812. bool got_error = false;
  20813. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20814. total += n;
  20815. }
  20816. if (n < 0) {
  20817. got_error = true;
  20818. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20819. handle.get_read_error() == Error::Read)
  20820. << "Actual error: " << to_string(handle.get_read_error());
  20821. }
  20822. EXPECT_TRUE(got_error || total < 1000)
  20823. << "Expected timeout but got all " << total << " bytes";
  20824. svr.stop();
  20825. t.join();
  20826. }
  20827. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20828. // Test SSL connection closed detection
  20829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20830. std::atomic<bool> close_now{false};
  20831. svr.Get("/will-close", [&](const Request &, Response &res) {
  20832. res.set_content_provider(
  20833. 10000, "text/plain",
  20834. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20835. if (offset < 100) {
  20836. std::string data(100, 'X');
  20837. sink.write(data.c_str(), data.size());
  20838. return true;
  20839. }
  20840. while (!close_now) {
  20841. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20842. }
  20843. return false;
  20844. });
  20845. });
  20846. auto port = 8094;
  20847. std::thread t([&]() { svr.listen("localhost", port); });
  20848. svr.wait_until_ready();
  20849. SSLClient cli("localhost", port);
  20850. cli.enable_server_certificate_verification(false);
  20851. auto handle = cli.open_stream("GET", "/will-close");
  20852. ASSERT_TRUE(handle.is_valid());
  20853. char buf[256];
  20854. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20855. EXPECT_GT(n, 0);
  20856. // Signal server to close
  20857. close_now = true;
  20858. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20859. // Keep reading
  20860. }
  20861. if (n < 0) {
  20862. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20863. handle.get_read_error() == Error::Read)
  20864. << "Actual error: " << to_string(handle.get_read_error());
  20865. }
  20866. svr.stop();
  20867. t.join();
  20868. }
  20869. #endif
  20870. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20871. using namespace httplib;
  20872. // Create a test file
  20873. const char *fname = "etag_testfile.txt";
  20874. const char *content = "etag-content";
  20875. {
  20876. std::ofstream ofs(fname);
  20877. ofs << content;
  20878. ASSERT_TRUE(ofs.good());
  20879. }
  20880. Server svr;
  20881. svr.set_mount_point("/static", ".");
  20882. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20883. svr.wait_until_ready();
  20884. Client cli(HOST, PORT);
  20885. // First request: should get 200 with ETag header
  20886. auto res1 = cli.Get("/static/etag_testfile.txt");
  20887. ASSERT_TRUE(res1);
  20888. ASSERT_EQ(200, res1->status);
  20889. ASSERT_TRUE(res1->has_header("ETag"));
  20890. std::string etag = res1->get_header_value("ETag");
  20891. EXPECT_FALSE(etag.empty());
  20892. // Verify ETag format: W/"hex-hex"
  20893. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20894. EXPECT_EQ('W', etag[0]);
  20895. EXPECT_EQ('/', etag[1]);
  20896. EXPECT_EQ('"', etag[2]);
  20897. EXPECT_EQ('"', etag.back());
  20898. // Exact match: expect 304 Not Modified
  20899. Headers h2 = {{"If-None-Match", etag}};
  20900. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20901. ASSERT_TRUE(res2);
  20902. EXPECT_EQ(304, res2->status);
  20903. // Wildcard match: expect 304 Not Modified
  20904. Headers h3 = {{"If-None-Match", "*"}};
  20905. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20906. ASSERT_TRUE(res3);
  20907. EXPECT_EQ(304, res3->status);
  20908. // Non-matching ETag: expect 200
  20909. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20910. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20911. ASSERT_TRUE(res4);
  20912. EXPECT_EQ(200, res4->status);
  20913. // Multiple ETags with one matching: expect 304
  20914. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20915. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20916. ASSERT_TRUE(res5);
  20917. EXPECT_EQ(304, res5->status);
  20918. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20919. // that equivalent to the single comma-separated list above, so the match on
  20920. // the second line must still be found.
  20921. Headers h6;
  20922. h6.emplace("If-None-Match", "W/\"other\"");
  20923. h6.emplace("If-None-Match", etag);
  20924. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20925. ASSERT_TRUE(res6);
  20926. EXPECT_EQ(304, res6->status);
  20927. svr.stop();
  20928. t.join();
  20929. std::remove(fname);
  20930. }
  20931. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20932. using namespace httplib;
  20933. Server svr;
  20934. svr.set_mount_point("/static", ".");
  20935. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20936. svr.wait_until_ready();
  20937. Client cli(HOST, PORT);
  20938. // Send If-None-Match: * to a non-existent file
  20939. Headers h = {{"If-None-Match", "*"}};
  20940. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20942. EXPECT_EQ(404, res->status);
  20943. svr.stop();
  20944. t.join();
  20945. }
  20946. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20947. using namespace httplib;
  20948. // Create a test file
  20949. const char *fname = "etag_boundary_testfile.txt";
  20950. const char *content = "boundary-test";
  20951. {
  20952. std::ofstream ofs(fname);
  20953. ofs << content;
  20954. ASSERT_TRUE(ofs.good());
  20955. }
  20956. Server svr;
  20957. svr.set_mount_point("/static", ".");
  20958. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20959. svr.wait_until_ready();
  20960. Client cli(HOST, PORT);
  20961. // Get the actual ETag
  20962. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20963. ASSERT_TRUE(res1);
  20964. ASSERT_EQ(200, res1->status);
  20965. ASSERT_TRUE(res1->has_header("ETag"));
  20966. std::string etag = res1->get_header_value("ETag");
  20967. // Test 1: Very long ETag value (longer than actual ETag)
  20968. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20969. Headers h1 = {{"If-None-Match", "W/"
  20970. "\"very-long-etag-value-that-is-much-longer-"
  20971. "than-the-actual-etag-value\""}};
  20972. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20973. ASSERT_TRUE(res2);
  20974. EXPECT_EQ(200, res2->status); // Should not match
  20975. // Test 2: Long string followed by wildcard
  20976. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20977. // string)
  20978. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20979. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20980. ASSERT_TRUE(res3);
  20981. EXPECT_EQ(304, res3->status); // Should match on "*"
  20982. // Test 3: Wildcard followed by long string
  20983. // Should match on "*" immediately and return 304
  20984. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20985. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20986. ASSERT_TRUE(res4);
  20987. EXPECT_EQ(304, res4->status); // Should match on "*"
  20988. // Test 4: Multiple long non-matching values
  20989. // Should NOT match and return 200 (test that all comparisons are safe)
  20990. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20991. "W/\"second-long-non-matching-value\", "
  20992. "W/\"third-long-non-matching-value\""}};
  20993. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20994. ASSERT_TRUE(res5);
  20995. EXPECT_EQ(200, res5->status); // Should not match
  20996. // Test 5: Single character that is not "*" (edge case)
  20997. Headers h5 = {{"If-None-Match", "X"}};
  20998. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20999. ASSERT_TRUE(res6);
  21000. EXPECT_EQ(200, res6->status); // Should not match
  21001. svr.stop();
  21002. t.join();
  21003. std::remove(fname);
  21004. }
  21005. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21006. using namespace httplib;
  21007. // Create a test file
  21008. const char *fname = "ims_testfile.txt";
  21009. const char *content = "if-modified-since-test";
  21010. {
  21011. std::ofstream ofs(fname);
  21012. ofs << content;
  21013. ASSERT_TRUE(ofs.good());
  21014. }
  21015. Server svr;
  21016. svr.set_mount_point("/static", ".");
  21017. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21018. svr.wait_until_ready();
  21019. Client cli(HOST, PORT);
  21020. // First request: should get 200 with Last-Modified header
  21021. auto res1 = cli.Get("/static/ims_testfile.txt");
  21022. ASSERT_TRUE(res1);
  21023. ASSERT_EQ(200, res1->status);
  21024. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21025. std::string last_modified = res1->get_header_value("Last-Modified");
  21026. EXPECT_FALSE(last_modified.empty());
  21027. // If-Modified-Since with same time: expect 304
  21028. Headers h2 = {{"If-Modified-Since", last_modified}};
  21029. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21030. ASSERT_TRUE(res2);
  21031. EXPECT_EQ(304, res2->status);
  21032. // If-Modified-Since with future time: expect 304
  21033. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21034. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21035. ASSERT_TRUE(res3);
  21036. EXPECT_EQ(304, res3->status);
  21037. // If-Modified-Since with past time: expect 200
  21038. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21039. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21040. ASSERT_TRUE(res4);
  21041. EXPECT_EQ(200, res4->status);
  21042. // If-None-Match takes precedence over If-Modified-Since
  21043. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21044. ASSERT_TRUE(res1->has_header("ETag"));
  21045. std::string etag = res1->get_header_value("ETag");
  21046. Headers h5 = {{"If-None-Match", etag},
  21047. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21048. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21049. ASSERT_TRUE(res5);
  21050. EXPECT_EQ(304, res5->status);
  21051. svr.stop();
  21052. t.join();
  21053. std::remove(fname);
  21054. }
  21055. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21056. using namespace httplib;
  21057. Server svr;
  21058. // Endpoint that returns compressible content
  21059. svr.Get("/compressible", [](const Request &, Response &res) {
  21060. // Return a large enough body to trigger compression
  21061. std::string body(1000, 'a');
  21062. res.set_content(body, "text/plain");
  21063. });
  21064. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21065. svr.wait_until_ready();
  21066. Client cli(HOST, PORT);
  21067. // Request with gzip support: should get Vary header when compressed
  21068. cli.set_compress(true);
  21069. auto res1 = cli.Get("/compressible");
  21070. ASSERT_TRUE(res1);
  21071. EXPECT_EQ(200, res1->status);
  21072. // If Content-Encoding is set, Vary should also be set
  21073. if (res1->has_header("Content-Encoding")) {
  21074. EXPECT_TRUE(res1->has_header("Vary"));
  21075. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21076. }
  21077. // Request without Accept-Encoding header: should not have compression
  21078. Headers h_no_compress;
  21079. auto res2 = cli.Get("/compressible", h_no_compress);
  21080. ASSERT_TRUE(res2);
  21081. EXPECT_EQ(200, res2->status);
  21082. // Verify Vary header is present when compression is applied
  21083. // (the exact behavior depends on server configuration)
  21084. svr.stop();
  21085. t.join();
  21086. }
  21087. TEST(ETagTest, IfRangeWithETag) {
  21088. using namespace httplib;
  21089. // Create a test file with known content
  21090. const char *fname = "if_range_testfile.txt";
  21091. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21092. {
  21093. std::ofstream ofs(fname);
  21094. ofs << content;
  21095. ASSERT_TRUE(ofs.good());
  21096. }
  21097. Server svr;
  21098. svr.set_mount_point("/static", ".");
  21099. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21100. svr.wait_until_ready();
  21101. Client cli(HOST, PORT);
  21102. // First request: get ETag
  21103. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21104. ASSERT_TRUE(res1);
  21105. ASSERT_EQ(200, res1->status);
  21106. ASSERT_TRUE(res1->has_header("ETag"));
  21107. std::string etag = res1->get_header_value("ETag");
  21108. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21109. // Since our server generates weak ETags (W/"..."), If-Range with our
  21110. // ETag should NOT result in partial content - it should return full content.
  21111. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21112. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21113. ASSERT_TRUE(res2);
  21114. // Weak ETag in If-Range -> full content (200), not partial (206)
  21115. EXPECT_EQ(200, res2->status);
  21116. EXPECT_EQ(content, res2->body);
  21117. EXPECT_FALSE(res2->has_header("Content-Range"));
  21118. // Range request with non-matching If-Range (ETag): should get 200 (full
  21119. // content)
  21120. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21121. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21122. ASSERT_TRUE(res3);
  21123. EXPECT_EQ(200, res3->status);
  21124. EXPECT_EQ(content, res3->body);
  21125. EXPECT_FALSE(res3->has_header("Content-Range"));
  21126. // Range request with strong ETag (hypothetical - our server doesn't generate
  21127. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21128. // should return full content)
  21129. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21130. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21131. ASSERT_TRUE(res4);
  21132. EXPECT_EQ(200, res4->status);
  21133. EXPECT_EQ(content, res4->body);
  21134. EXPECT_FALSE(res4->has_header("Content-Range"));
  21135. svr.stop();
  21136. t.join();
  21137. std::remove(fname);
  21138. }
  21139. TEST(ETagTest, IfRangeWithDate) {
  21140. using namespace httplib;
  21141. // Create a test file
  21142. const char *fname = "if_range_date_testfile.txt";
  21143. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21144. {
  21145. std::ofstream ofs(fname);
  21146. ofs << content;
  21147. ASSERT_TRUE(ofs.good());
  21148. }
  21149. Server svr;
  21150. svr.set_mount_point("/static", ".");
  21151. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21152. svr.wait_until_ready();
  21153. Client cli(HOST, PORT);
  21154. // First request: get Last-Modified
  21155. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21156. ASSERT_TRUE(res1);
  21157. ASSERT_EQ(200, res1->status);
  21158. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21159. std::string last_modified = res1->get_header_value("Last-Modified");
  21160. // Range request with matching If-Range (date): should get 206
  21161. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21162. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21163. ASSERT_TRUE(res2);
  21164. EXPECT_EQ(206, res2->status);
  21165. EXPECT_EQ("FGHIJ", res2->body);
  21166. // Range request with old If-Range date: should get 200 (full content)
  21167. Headers h3 = {{"Range", "bytes=5-9"},
  21168. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21169. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21170. ASSERT_TRUE(res3);
  21171. EXPECT_EQ(200, res3->status);
  21172. EXPECT_EQ(content, res3->body);
  21173. // Range request with future If-Range date: should get 206
  21174. Headers h4 = {{"Range", "bytes=0-4"},
  21175. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21176. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21177. ASSERT_TRUE(res4);
  21178. EXPECT_EQ(206, res4->status);
  21179. EXPECT_EQ("ABCDE", res4->body);
  21180. svr.stop();
  21181. t.join();
  21182. std::remove(fname);
  21183. }
  21184. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21185. using namespace httplib;
  21186. const char *fname = "etag_malformed.txt";
  21187. const char *content = "malformed-etag";
  21188. {
  21189. std::ofstream ofs(fname);
  21190. ofs << content;
  21191. ASSERT_TRUE(ofs.good());
  21192. }
  21193. Server svr;
  21194. svr.set_mount_point("/static", ".");
  21195. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21196. svr.wait_until_ready();
  21197. Client cli(HOST, PORT);
  21198. // baseline: should get 200 and an ETag
  21199. auto res1 = cli.Get("/static/etag_malformed.txt");
  21200. ASSERT_TRUE(res1);
  21201. ASSERT_EQ(200, res1->status);
  21202. ASSERT_TRUE(res1->has_header("ETag"));
  21203. // Malformed ETag value (missing quotes) should be treated as non-matching
  21204. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21205. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21206. ASSERT_TRUE(res_bad);
  21207. EXPECT_EQ(200, res_bad->status);
  21208. // Whitespace-only header value should be considered invalid / non-matching
  21209. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21210. "Host: localhost\r\n"
  21211. "If-None-Match: \r\n"
  21212. "Connection: close\r\n"
  21213. "\r\n";
  21214. std::string out;
  21215. ASSERT_TRUE(send_request(5, raw_req, &out));
  21216. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21217. svr.stop();
  21218. t.join();
  21219. std::remove(fname);
  21220. }
  21221. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21222. using namespace httplib;
  21223. const char *fname = "ims_invalid_format.txt";
  21224. const char *content = "ims-bad-format";
  21225. {
  21226. std::ofstream ofs(fname);
  21227. ofs << content;
  21228. ASSERT_TRUE(ofs.good());
  21229. }
  21230. Server svr;
  21231. svr.set_mount_point("/static", ".");
  21232. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21233. svr.wait_until_ready();
  21234. Client cli(HOST, PORT);
  21235. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21236. ASSERT_TRUE(res1);
  21237. ASSERT_EQ(200, res1->status);
  21238. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21239. // If-Modified-Since with invalid format should not result in 304
  21240. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21241. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21242. ASSERT_TRUE(res_bad);
  21243. EXPECT_EQ(200, res_bad->status);
  21244. // If-Range with invalid date format should be treated as mismatch -> full
  21245. // content (200)
  21246. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21247. {"If-Range", "invalid-date"}};
  21248. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21249. ASSERT_TRUE(res_ifrange);
  21250. EXPECT_EQ(200, res_ifrange->status);
  21251. svr.stop();
  21252. t.join();
  21253. std::remove(fname);
  21254. }
  21255. TEST(ETagTest, IfRangeWithMalformedETag) {
  21256. using namespace httplib;
  21257. const char *fname = "ifrange_malformed.txt";
  21258. const std::string content = "0123456789";
  21259. {
  21260. std::ofstream ofs(fname);
  21261. ofs << content;
  21262. ASSERT_TRUE(ofs.good());
  21263. }
  21264. Server svr;
  21265. svr.set_mount_point("/static", ".");
  21266. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21267. svr.wait_until_ready();
  21268. Client cli(HOST, PORT);
  21269. // First request: get ETag
  21270. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21271. ASSERT_TRUE(res1);
  21272. ASSERT_EQ(200, res1->status);
  21273. ASSERT_TRUE(res1->has_header("ETag"));
  21274. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21275. // full content (200)
  21276. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21277. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21278. ASSERT_TRUE(res2);
  21279. EXPECT_EQ(200, res2->status);
  21280. EXPECT_EQ(content, res2->body);
  21281. svr.stop();
  21282. t.join();
  21283. std::remove(fname);
  21284. }
  21285. TEST(ETagTest, ExtremeLargeDateValues) {
  21286. using namespace httplib;
  21287. const char *fname = "ims_extreme_date.txt";
  21288. const char *content = "ims-extreme-date";
  21289. {
  21290. std::ofstream ofs(fname);
  21291. ofs << content;
  21292. ASSERT_TRUE(ofs.good());
  21293. }
  21294. Server svr;
  21295. svr.set_mount_point("/static", ".");
  21296. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21297. svr.wait_until_ready();
  21298. Client cli(HOST, PORT);
  21299. auto res1 = cli.Get(std::string("/static/") + fname);
  21300. ASSERT_TRUE(res1);
  21301. ASSERT_EQ(200, res1->status);
  21302. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21303. // Extremely large year that may overflow date parsing routines.
  21304. Headers h_large_date = {
  21305. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21306. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21307. ASSERT_TRUE(res_bad);
  21308. // Expect server to treat this as invalid/mismatch and return full content
  21309. EXPECT_EQ(200, res_bad->status);
  21310. // If-Range with extremely large date should be treated as mismatch -> full
  21311. // content (200)
  21312. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21313. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21314. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21315. ASSERT_TRUE(res_ifrange);
  21316. EXPECT_EQ(200, res_ifrange->status);
  21317. svr.stop();
  21318. t.join();
  21319. std::remove(fname);
  21320. }
  21321. TEST(ETagTest, NegativeFileModificationTime) {
  21322. using namespace httplib;
  21323. const char *fname = "ims_negative_mtime.txt";
  21324. const std::string content = "negative-mtime";
  21325. {
  21326. std::ofstream ofs(fname);
  21327. ofs << content;
  21328. ASSERT_TRUE(ofs.good());
  21329. }
  21330. // Try to set file mtime to a negative value. This may fail on some
  21331. // platforms/filesystems; if it fails, the test will still verify server
  21332. // behaves safely by performing a regular conditional request.
  21333. #if defined(__APPLE__) || defined(__linux__)
  21334. bool set_negative = false;
  21335. do {
  21336. struct timeval times[2];
  21337. // access time: now
  21338. times[0].tv_sec = time(nullptr);
  21339. times[0].tv_usec = 0;
  21340. // modification time: negative (e.g., -1)
  21341. times[1].tv_sec = -1;
  21342. times[1].tv_usec = 0;
  21343. if (utimes(fname, times) == 0) { set_negative = true; }
  21344. } while (0);
  21345. #else
  21346. bool set_negative = false;
  21347. #endif
  21348. Server svr;
  21349. svr.set_mount_point("/static", ".");
  21350. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21351. svr.wait_until_ready();
  21352. Client cli(HOST, PORT);
  21353. auto res1 = cli.Get(std::string("/static/") + fname);
  21354. ASSERT_TRUE(res1);
  21355. ASSERT_EQ(200, res1->status);
  21356. bool has_last_modified = res1->has_header("Last-Modified");
  21357. std::string last_modified;
  21358. if (has_last_modified) {
  21359. last_modified = res1->get_header_value("Last-Modified");
  21360. }
  21361. if (set_negative) {
  21362. // If we successfully set a negative mtime, ensure server returns a
  21363. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21364. // with an old date and ensure server handles it without crash.
  21365. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21366. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21367. ASSERT_TRUE(res2);
  21368. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21369. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21370. } else {
  21371. // Could not set negative mtime on this platform; fall back to verifying
  21372. // that normal invalid/malformed dates are treated safely (non-304).
  21373. Headers h_bad_date = {
  21374. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21375. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21376. ASSERT_TRUE(res_bad);
  21377. EXPECT_EQ(200, res_bad->status);
  21378. }
  21379. svr.stop();
  21380. t.join();
  21381. std::remove(fname);
  21382. }
  21383. //==============================================================================
  21384. // Integration Tests with Server
  21385. //==============================================================================
  21386. class SSEIntegrationTest : public ::testing::Test {
  21387. protected:
  21388. void SetUp() override {
  21389. stop_server_.store(false);
  21390. events_.clear();
  21391. server_ = httplib::detail::make_unique<Server>();
  21392. setup_server();
  21393. start_server();
  21394. }
  21395. void TearDown() override {
  21396. stop_server_.store(true);
  21397. event_cv_.notify_all();
  21398. server_->stop();
  21399. if (server_thread_.joinable()) { server_thread_.join(); }
  21400. }
  21401. void setup_server() {
  21402. // Simple SSE endpoint
  21403. server_->Get("/events", [this](const Request &req, Response &res) {
  21404. auto last_id = req.get_header_value("Last-Event-ID");
  21405. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21406. res.set_chunked_content_provider(
  21407. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21408. std::unique_lock<std::mutex> lock(event_mutex_);
  21409. if (event_cv_.wait_for(
  21410. lock, std::chrono::milliseconds(200), [this] {
  21411. return !events_.empty() || stop_server_.load();
  21412. })) {
  21413. if (stop_server_.load()) { return false; }
  21414. if (!events_.empty()) {
  21415. std::string event = events_.front();
  21416. events_.erase(events_.begin());
  21417. sink.write(event.data(), event.size());
  21418. return true;
  21419. }
  21420. }
  21421. return !stop_server_.load();
  21422. });
  21423. });
  21424. // Endpoint that returns error
  21425. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21426. res.status = 500;
  21427. res.set_content("Internal Server Error", "text/plain");
  21428. });
  21429. // Endpoint for custom event types
  21430. server_->Get("/custom-events", [](const Request &, Response &res) {
  21431. res.set_chunked_content_provider(
  21432. "text/event-stream", [](size_t offset, DataSink &sink) {
  21433. if (offset == 0) {
  21434. std::string event = "event: update\ndata: updated\n\n"
  21435. "event: delete\ndata: deleted\n\n";
  21436. sink.write(event.data(), event.size());
  21437. }
  21438. return false; // End stream after sending
  21439. });
  21440. });
  21441. }
  21442. void start_server() {
  21443. port_ = server_->bind_to_any_port(HOST);
  21444. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21445. // Wait for server to start
  21446. while (!server_->is_running()) {
  21447. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21448. }
  21449. }
  21450. int get_port() const { return port_; }
  21451. void send_event(const std::string &event) {
  21452. std::lock_guard<std::mutex> lock(event_mutex_);
  21453. events_.push_back(event);
  21454. event_cv_.notify_all();
  21455. }
  21456. std::unique_ptr<Server> server_;
  21457. std::thread server_thread_;
  21458. std::mutex event_mutex_;
  21459. std::condition_variable event_cv_;
  21460. std::vector<std::string> events_;
  21461. std::atomic<bool> stop_server_{false};
  21462. std::string last_received_event_id_;
  21463. int port_ = 0;
  21464. };
  21465. //==============================================================================
  21466. // SSE Parsing Tests
  21467. //==============================================================================
  21468. class SSEParsingTest : public SSEIntegrationTest {
  21469. protected:
  21470. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21471. // A trailing sentinel event tells when the whole stream has been parsed.
  21472. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21473. auto body = stream + "event: end\ndata: end\n\n";
  21474. server_->Get("/parse", [body](const Request &, Response &res) {
  21475. res.set_content(body, "text/event-stream");
  21476. });
  21477. return collect("/parse");
  21478. }
  21479. // Runs SSEClient against path until an "end" event arrives and returns the
  21480. // messages dispatched before it
  21481. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21482. Client client(HOST, get_port());
  21483. sse::SSEClient sse(client, path);
  21484. std::mutex mutex;
  21485. std::condition_variable cv;
  21486. std::vector<sse::SSEMessage> messages;
  21487. auto done = false;
  21488. sse.on_message([&](const sse::SSEMessage &msg) {
  21489. std::lock_guard<std::mutex> lock(mutex);
  21490. // Ignore a replay from a reconnect that races with stop()
  21491. if (!done) { messages.push_back(msg); }
  21492. });
  21493. sse.on_event("end", [&](const sse::SSEMessage &) {
  21494. std::lock_guard<std::mutex> lock(mutex);
  21495. done = true;
  21496. cv.notify_all();
  21497. });
  21498. sse.set_reconnect_interval(100);
  21499. sse.start_async();
  21500. {
  21501. std::unique_lock<std::mutex> lock(mutex);
  21502. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21503. }
  21504. sse.stop();
  21505. EXPECT_TRUE(done);
  21506. return messages;
  21507. }
  21508. };
  21509. TEST_F(SSEParsingTest, SingleLineData) {
  21510. auto msgs = parse("data: hello\n\n");
  21511. ASSERT_EQ(msgs.size(), 1u);
  21512. EXPECT_EQ(msgs[0].data, "hello");
  21513. EXPECT_EQ(msgs[0].event, "message");
  21514. }
  21515. TEST_F(SSEParsingTest, MultiLineData) {
  21516. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21517. ASSERT_EQ(msgs.size(), 1u);
  21518. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21519. }
  21520. TEST_F(SSEParsingTest, CustomEventType) {
  21521. auto msgs = parse("event: update\ndata: payload\n\n");
  21522. ASSERT_EQ(msgs.size(), 1u);
  21523. EXPECT_EQ(msgs[0].event, "update");
  21524. EXPECT_EQ(msgs[0].data, "payload");
  21525. }
  21526. TEST_F(SSEParsingTest, EventIdHandling) {
  21527. auto msgs = parse("id: 12345\ndata: test\n\n");
  21528. ASSERT_EQ(msgs.size(), 1u);
  21529. EXPECT_EQ(msgs[0].id, "12345");
  21530. }
  21531. TEST_F(SSEParsingTest, EmptyEventId) {
  21532. auto msgs = parse("id:\ndata: test\n\n");
  21533. ASSERT_EQ(msgs.size(), 1u);
  21534. EXPECT_EQ(msgs[0].id, "");
  21535. }
  21536. TEST_F(SSEParsingTest, CommentsIgnored) {
  21537. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21538. ASSERT_EQ(msgs.size(), 1u);
  21539. EXPECT_EQ(msgs[0].data, "hello");
  21540. EXPECT_EQ(msgs[0].event, "message");
  21541. }
  21542. TEST_F(SSEParsingTest, ColonInValue) {
  21543. auto msgs = parse("data: hello:world:test\n\n");
  21544. ASSERT_EQ(msgs.size(), 1u);
  21545. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21546. }
  21547. TEST_F(SSEParsingTest, FieldNameOnly) {
  21548. // A line without a colon is a field name with an empty value
  21549. auto msgs = parse("data\n\n");
  21550. ASSERT_EQ(msgs.size(), 1u);
  21551. EXPECT_EQ(msgs[0].data, "");
  21552. }
  21553. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21554. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21555. ASSERT_EQ(msgs.size(), 1u);
  21556. EXPECT_EQ(msgs[0].event, "update");
  21557. EXPECT_EQ(msgs[0].data, "hello");
  21558. }
  21559. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21560. auto msgs = parse("data\r\n\r\n");
  21561. ASSERT_EQ(msgs.size(), 1u);
  21562. EXPECT_EQ(msgs[0].data, "");
  21563. }
  21564. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21565. auto msgs = parse("event: update\rdata: hello\r\r");
  21566. ASSERT_EQ(msgs.size(), 1u);
  21567. EXPECT_EQ(msgs[0].event, "update");
  21568. EXPECT_EQ(msgs[0].data, "hello");
  21569. }
  21570. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21571. // Chunk boundaries fall inside every \r\n and right before the first one
  21572. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21573. "\n\r", "\nevent: end\ndata: end\n\n"};
  21574. server_->Get("/split", [chunks](const Request &, Response &res) {
  21575. auto i = std::make_shared<size_t>(0);
  21576. res.set_chunked_content_provider(
  21577. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21578. if (*i == chunks.size()) {
  21579. sink.done();
  21580. } else {
  21581. sink.write(chunks[*i].data(), chunks[*i].size());
  21582. (*i)++;
  21583. }
  21584. return true;
  21585. });
  21586. });
  21587. auto msgs = collect("/split");
  21588. ASSERT_EQ(msgs.size(), 1u);
  21589. EXPECT_EQ(msgs[0].event, "update");
  21590. EXPECT_EQ(msgs[0].data, "hello");
  21591. }
  21592. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21593. // Only a BOM at the start of the stream is ignored
  21594. auto msgs = parse("\xEF\xBB\xBF"
  21595. "data: first\n\n"
  21596. "\xEF\xBB\xBF"
  21597. "data: second\n\n");
  21598. ASSERT_EQ(msgs.size(), 1u);
  21599. EXPECT_EQ(msgs[0].data, "first");
  21600. }
  21601. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21602. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21603. ASSERT_EQ(msgs.size(), 1u);
  21604. EXPECT_EQ(msgs[0].data, "hello");
  21605. EXPECT_EQ(msgs[0].event, "message");
  21606. }
  21607. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21608. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21609. ASSERT_EQ(msgs.size(), 2u);
  21610. EXPECT_EQ(msgs[0].data, "hello");
  21611. EXPECT_EQ(msgs[1].data, "hello");
  21612. }
  21613. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21614. // An event without data is not dispatched, and its type must not leak
  21615. // into the next event
  21616. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21617. ASSERT_EQ(msgs.size(), 1u);
  21618. EXPECT_EQ(msgs[0].event, "message");
  21619. EXPECT_EQ(msgs[0].data, "hello");
  21620. }
  21621. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21622. // Also when the empty field replaces an earlier type
  21623. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21624. ASSERT_EQ(msgs.size(), 2u);
  21625. EXPECT_EQ(msgs[0].event, "message");
  21626. EXPECT_EQ(msgs[1].event, "message");
  21627. }
  21628. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21629. // The first connection sends only an id; the second echoes back the
  21630. // Last-Event-ID it was reconnected with
  21631. std::atomic<int> connection_count{0};
  21632. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21633. if (connection_count++ == 0) {
  21634. res.set_content("id: 42\n\n", "text/event-stream");
  21635. } else {
  21636. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21637. "\n\nevent: end\ndata: end\n\n",
  21638. "text/event-stream");
  21639. }
  21640. });
  21641. auto msgs = collect("/id-only");
  21642. ASSERT_EQ(msgs.size(), 1u);
  21643. EXPECT_EQ(msgs[0].data, "42");
  21644. }
  21645. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21646. // The first connection sets an id and then clears it with an empty one; the
  21647. // second reports whether it was reconnected with a Last-Event-ID
  21648. std::atomic<int> connection_count{0};
  21649. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21650. if (connection_count++ == 0) {
  21651. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21652. "text/event-stream");
  21653. } else {
  21654. res.set_content(
  21655. std::string("data: ") +
  21656. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21657. "\n\nevent: end\ndata: end\n\n",
  21658. "text/event-stream");
  21659. }
  21660. });
  21661. auto msgs = collect("/id-clear");
  21662. ASSERT_EQ(msgs.size(), 3u);
  21663. EXPECT_EQ(msgs[0].id, "1");
  21664. EXPECT_EQ(msgs[1].id, "");
  21665. EXPECT_EQ(msgs[2].data, "not sent");
  21666. }
  21667. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21668. // The first connection sets an id and then sends ids that cannot be carried
  21669. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21670. // with
  21671. std::atomic<int> connection_count{0};
  21672. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21673. if (connection_count++ == 0) {
  21674. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21675. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21676. "text/event-stream");
  21677. } else {
  21678. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21679. "\n\nevent: end\ndata: end\n\n",
  21680. "text/event-stream");
  21681. }
  21682. });
  21683. auto msgs = collect("/id-unsendable");
  21684. ASSERT_EQ(msgs.size(), 1u);
  21685. EXPECT_EQ(msgs[0].data, "42");
  21686. }
  21687. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21688. auto msgs = parse("event: notification\nid: evt-42\n"
  21689. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21690. ASSERT_EQ(msgs.size(), 1u);
  21691. EXPECT_EQ(msgs[0].event, "notification");
  21692. EXPECT_EQ(msgs[0].id, "evt-42");
  21693. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21694. }
  21695. TEST(SSEMessageTest, Clear) {
  21696. sse::SSEMessage msg;
  21697. msg.event = "custom";
  21698. msg.data = "some data";
  21699. msg.id = "123";
  21700. msg.clear();
  21701. EXPECT_EQ(msg.event, "message");
  21702. EXPECT_EQ(msg.data, "");
  21703. EXPECT_EQ(msg.id, "");
  21704. }
  21705. //==============================================================================
  21706. // SSE Integration Tests
  21707. //==============================================================================
  21708. // Test: Successful connection and on_open callback
  21709. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21710. // Add a simple endpoint that sends one event and closes
  21711. server_->Get("/simple-event", [](const Request &, Response &res) {
  21712. res.set_chunked_content_provider(
  21713. "text/event-stream", [](size_t offset, DataSink &sink) {
  21714. if (offset == 0) {
  21715. std::string event = "data: hello\n\n";
  21716. sink.write(event.data(), event.size());
  21717. }
  21718. return false; // Close stream after sending
  21719. });
  21720. });
  21721. Client client("localhost", get_port());
  21722. sse::SSEClient sse(client, "/simple-event");
  21723. std::atomic<bool> open_called{false};
  21724. std::atomic<bool> message_received{false};
  21725. sse.on_open([&open_called]() { open_called.store(true); });
  21726. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21727. if (msg.data == "hello") { message_received.store(true); }
  21728. });
  21729. sse.set_reconnect_interval(100);
  21730. sse.set_max_reconnect_attempts(1);
  21731. // Start async
  21732. sse.start_async();
  21733. // Wait for message to be processed
  21734. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21735. sse.stop();
  21736. EXPECT_TRUE(open_called.load());
  21737. EXPECT_TRUE(message_received.load());
  21738. }
  21739. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21740. // A data line that never ends.
  21741. server_->Get("/endless-line", [](const Request &, Response &res) {
  21742. res.set_chunked_content_provider(
  21743. "text/event-stream", [](size_t offset, DataSink &sink) {
  21744. if (offset == 0) { sink.write("data: ", 6); }
  21745. std::string chunk(64 * 1024, 'A');
  21746. return sink.write(chunk.data(), chunk.size());
  21747. });
  21748. });
  21749. Client client("localhost", get_port());
  21750. sse::SSEClient sse(client, "/endless-line");
  21751. std::atomic<bool> too_long{false};
  21752. sse.on_error([&](Error err) {
  21753. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21754. });
  21755. sse.set_max_reconnect_attempts(1);
  21756. sse.start_async();
  21757. for (int i = 0; i < 500 && !too_long; i++) {
  21758. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21759. }
  21760. sse.stop();
  21761. EXPECT_TRUE(too_long);
  21762. }
  21763. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21764. // Far more in all than the client's payload limit below.
  21765. server_->Get("/many-events", [](const Request &, Response &res) {
  21766. res.set_chunked_content_provider(
  21767. "text/event-stream", [](size_t offset, DataSink &sink) {
  21768. if (offset == 0) {
  21769. std::string events;
  21770. for (int i = 0; i < 1000; i++) {
  21771. events += "data: message\n\n";
  21772. }
  21773. sink.write(events.data(), events.size());
  21774. }
  21775. return false;
  21776. });
  21777. });
  21778. Client client("localhost", get_port());
  21779. client.set_payload_max_length(1024);
  21780. sse::SSEClient sse(client, "/many-events");
  21781. std::atomic<int> messages{0};
  21782. std::atomic<bool> too_large{false};
  21783. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21784. sse.on_error([&](Error err) {
  21785. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21786. });
  21787. sse.set_max_reconnect_attempts(1);
  21788. sse.start_async();
  21789. for (int i = 0; i < 500 && messages < 1000; i++) {
  21790. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21791. }
  21792. sse.stop();
  21793. EXPECT_GE(messages.load(), 1000);
  21794. EXPECT_FALSE(too_large);
  21795. }
  21796. // Test: on_message callback
  21797. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21798. // Endpoint that sends multiple events then closes
  21799. server_->Get("/multi-event", [](const Request &, Response &res) {
  21800. res.set_chunked_content_provider(
  21801. "text/event-stream", [](size_t offset, DataSink &sink) {
  21802. if (offset == 0) {
  21803. std::string events = "data: message1\n\ndata: message2\n\n";
  21804. sink.write(events.data(), events.size());
  21805. }
  21806. return false;
  21807. });
  21808. });
  21809. Client client("localhost", get_port());
  21810. sse::SSEClient sse(client, "/multi-event");
  21811. std::vector<std::string> received_messages;
  21812. std::mutex messages_mutex;
  21813. sse.on_message([&](const sse::SSEMessage &msg) {
  21814. std::lock_guard<std::mutex> lock(messages_mutex);
  21815. received_messages.push_back(msg.data);
  21816. });
  21817. sse.set_reconnect_interval(100);
  21818. sse.set_max_reconnect_attempts(1);
  21819. sse.start_async();
  21820. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21821. sse.stop();
  21822. std::lock_guard<std::mutex> lock(messages_mutex);
  21823. EXPECT_GE(received_messages.size(), 2u);
  21824. if (received_messages.size() >= 2) {
  21825. EXPECT_EQ(received_messages[0], "message1");
  21826. EXPECT_EQ(received_messages[1], "message2");
  21827. }
  21828. }
  21829. // Test: on_event for specific types
  21830. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21831. Client client("localhost", get_port());
  21832. sse::SSEClient sse(client, "/custom-events");
  21833. std::atomic<bool> update_received{false};
  21834. std::atomic<bool> delete_received{false};
  21835. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21836. if (msg.data == "updated") { update_received.store(true); }
  21837. });
  21838. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21839. if (msg.data == "deleted") { delete_received.store(true); }
  21840. });
  21841. sse.set_max_reconnect_attempts(1);
  21842. sse.start_async();
  21843. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21844. sse.stop();
  21845. EXPECT_TRUE(update_received.load());
  21846. EXPECT_TRUE(delete_received.load());
  21847. }
  21848. // Test: on_error callback on connection failure
  21849. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21850. // Connect to a non-existent port
  21851. Client client("localhost", 59999);
  21852. sse::SSEClient sse(client, "/events");
  21853. std::atomic<bool> error_called{false};
  21854. Error received_error = Error::Success;
  21855. sse.on_error([&](Error err) {
  21856. error_called.store(true);
  21857. received_error = err;
  21858. });
  21859. sse.set_reconnect_interval(50);
  21860. sse.set_max_reconnect_attempts(1);
  21861. sse.start_async();
  21862. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21863. sse.stop();
  21864. EXPECT_TRUE(error_called.load());
  21865. EXPECT_NE(received_error, Error::Success);
  21866. }
  21867. // Test: Last-Event-ID header sent on reconnect
  21868. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21869. // Endpoint that sends event with ID
  21870. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21871. res.set_chunked_content_provider(
  21872. "text/event-stream", [](size_t offset, DataSink &sink) {
  21873. if (offset == 0) {
  21874. std::string event = "id: evt-123\ndata: test\n\n";
  21875. sink.write(event.data(), event.size());
  21876. }
  21877. return false;
  21878. });
  21879. });
  21880. Client client("localhost", get_port());
  21881. sse::SSEClient sse(client, "/event-with-id");
  21882. std::atomic<bool> id_received{false};
  21883. sse.on_message([&](const sse::SSEMessage &msg) {
  21884. if (!msg.id.empty()) { id_received.store(true); }
  21885. });
  21886. sse.set_reconnect_interval(100);
  21887. sse.set_max_reconnect_attempts(1);
  21888. sse.start_async();
  21889. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21890. sse.stop();
  21891. EXPECT_TRUE(id_received.load());
  21892. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21893. }
  21894. // Test: Manual stop
  21895. TEST_F(SSEIntegrationTest, ManualStop) {
  21896. // Endpoint that sends one event and stays open briefly. The server outlives
  21897. // this test body, so the provider uses the fixture's flag, not a local.
  21898. server_->Get("/stay-open", [this](const Request &, Response &res) {
  21899. res.set_chunked_content_provider(
  21900. "text/event-stream", [this](size_t offset, DataSink &sink) {
  21901. if (offset == 0) {
  21902. std::string event = "data: connected\n\n";
  21903. sink.write(event.data(), event.size());
  21904. }
  21905. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  21906. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21907. }
  21908. return false;
  21909. });
  21910. });
  21911. Client client("localhost", get_port());
  21912. sse::SSEClient sse(client, "/stay-open");
  21913. std::atomic<bool> connected{false};
  21914. sse.on_open([&connected]() { connected.store(true); });
  21915. sse.set_reconnect_interval(100);
  21916. sse.set_max_reconnect_attempts(1);
  21917. sse.start_async();
  21918. // Wait for connection to establish
  21919. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21920. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21921. }
  21922. EXPECT_TRUE(connected.load());
  21923. EXPECT_TRUE(sse.is_connected());
  21924. // Signal handler to stop
  21925. stop_server_.store(true);
  21926. // Stop SSE client
  21927. sse.stop();
  21928. EXPECT_FALSE(sse.is_connected());
  21929. }
  21930. // Sends one event, then nothing until stop is set
  21931. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  21932. return [&stop](const Request &, Response &res) {
  21933. res.set_chunked_content_provider(
  21934. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  21935. if (offset == 0) {
  21936. std::string event = "data: hello\n\n";
  21937. sink.write(event.data(), event.size());
  21938. }
  21939. while (!stop.load()) {
  21940. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21941. }
  21942. return false;
  21943. });
  21944. };
  21945. }
  21946. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  21947. static void check_stop_interrupts_blocked_read(Client &client) {
  21948. client.set_read_timeout(30, 0);
  21949. for (auto by_destructor : {false, true}) {
  21950. std::atomic<bool> received{false};
  21951. std::chrono::steady_clock::time_point start;
  21952. {
  21953. sse::SSEClient sse(client, "/idle-stream");
  21954. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  21955. sse.start_async();
  21956. for (int i = 0; i < 500 && !received.load(); ++i) {
  21957. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21958. }
  21959. ASSERT_TRUE(received.load());
  21960. // Let the client block in the next read
  21961. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  21962. start = std::chrono::steady_clock::now();
  21963. if (!by_destructor) { sse.stop(); }
  21964. }
  21965. EXPECT_LT(std::chrono::steady_clock::now() - start,
  21966. std::chrono::seconds(2));
  21967. }
  21968. }
  21969. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  21970. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  21971. Client client("localhost", get_port());
  21972. check_stop_interrupts_blocked_read(client);
  21973. }
  21974. #ifdef CPPHTTPLIB_SSL_ENABLED
  21975. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  21976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21977. std::atomic<bool> done{false};
  21978. svr.Get("/idle-stream", idle_event_stream(done));
  21979. auto port = svr.bind_to_any_port(HOST);
  21980. std::thread t([&] { svr.listen_after_bind(); });
  21981. auto se = detail::scope_exit([&] {
  21982. done.store(true);
  21983. svr.stop();
  21984. t.join();
  21985. });
  21986. svr.wait_until_ready();
  21987. Client client("https://localhost:" + std::to_string(port));
  21988. client.enable_server_certificate_verification(false);
  21989. check_stop_interrupts_blocked_read(client);
  21990. }
  21991. #endif
  21992. // Test: SSEClient with custom headers
  21993. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21994. // Setup a server endpoint that checks for custom header
  21995. std::atomic<bool> header_received{false};
  21996. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21997. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21998. header_received.store(true);
  21999. }
  22000. res.set_chunked_content_provider("text/event-stream",
  22001. [](size_t, DataSink &) { return false; });
  22002. });
  22003. Client client("localhost", get_port());
  22004. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22005. sse::SSEClient sse(client, "/header-check", headers);
  22006. sse.set_max_reconnect_attempts(1);
  22007. sse.start_async();
  22008. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22009. sse.stop();
  22010. EXPECT_TRUE(header_received.load());
  22011. }
  22012. // Test: Reconnect interval configuration
  22013. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22014. Client client("localhost", get_port());
  22015. sse::SSEClient sse(client, "/events");
  22016. auto &result = sse.set_reconnect_interval(500);
  22017. // Builder pattern should return reference to self
  22018. EXPECT_EQ(&result, &sse);
  22019. }
  22020. // Test: Max reconnect attempts
  22021. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22022. // Connect to non-existent port to force reconnects
  22023. Client client("localhost", 59998);
  22024. sse::SSEClient sse(client, "/events");
  22025. std::atomic<int> error_count{0};
  22026. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22027. sse.set_reconnect_interval(50);
  22028. sse.set_max_reconnect_attempts(2);
  22029. auto start = std::chrono::steady_clock::now();
  22030. sse.start(); // Blocking call
  22031. auto end = std::chrono::steady_clock::now();
  22032. // Should have stopped after 2 failed attempts
  22033. EXPECT_GE(error_count.load(), 2);
  22034. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22035. auto duration =
  22036. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22037. #ifdef _WIN32
  22038. // Windows is much slower for socket connection failures
  22039. EXPECT_LT(duration.count(), 7000);
  22040. #else
  22041. EXPECT_LT(duration.count(), 1000);
  22042. #endif
  22043. }
  22044. // Test: Multi-line data in integration
  22045. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22046. // Endpoint with multi-line data
  22047. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22048. res.set_chunked_content_provider(
  22049. "text/event-stream", [](size_t offset, DataSink &sink) {
  22050. if (offset == 0) {
  22051. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22052. sink.write(event.data(), event.size());
  22053. }
  22054. return false;
  22055. });
  22056. });
  22057. Client client("localhost", get_port());
  22058. sse::SSEClient sse(client, "/multiline-data");
  22059. std::string received_data;
  22060. std::mutex data_mutex;
  22061. sse.on_message([&](const sse::SSEMessage &msg) {
  22062. std::lock_guard<std::mutex> lock(data_mutex);
  22063. received_data = msg.data;
  22064. });
  22065. sse.set_reconnect_interval(100);
  22066. sse.set_max_reconnect_attempts(1);
  22067. sse.start_async();
  22068. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22069. sse.stop();
  22070. std::lock_guard<std::mutex> lock(data_mutex);
  22071. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22072. }
  22073. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22074. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22075. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22076. DataSink &sink) {
  22077. if (offset == 0) {
  22078. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22079. sink.write(events.data(), events.size());
  22080. }
  22081. return false;
  22082. });
  22083. });
  22084. Client client("localhost", get_port());
  22085. sse::SSEClient sse(client, "/empty-data-lines");
  22086. std::mutex mutex;
  22087. std::condition_variable cv;
  22088. std::vector<std::string> received;
  22089. sse.on_message([&](const sse::SSEMessage &msg) {
  22090. std::lock_guard<std::mutex> lock(mutex);
  22091. received.push_back(msg.data);
  22092. cv.notify_all();
  22093. });
  22094. sse.set_max_reconnect_attempts(1);
  22095. sse.start_async();
  22096. {
  22097. std::unique_lock<std::mutex> lock(mutex);
  22098. cv.wait_for(lock, std::chrono::seconds(2),
  22099. [&] { return received.size() >= 3; });
  22100. }
  22101. sse.stop();
  22102. ASSERT_GE(received.size(), 3u);
  22103. EXPECT_EQ(received[0], "");
  22104. EXPECT_EQ(received[1], "\nhello");
  22105. EXPECT_EQ(received[2], "");
  22106. }
  22107. // Test: Auto-reconnect after server disconnection
  22108. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22109. std::atomic<int> connection_count{0};
  22110. std::atomic<int> message_count{0};
  22111. // Endpoint that sends one event and closes, forcing reconnect
  22112. server_->Get("/reconnect-test",
  22113. [&connection_count](const Request &, Response &res) {
  22114. connection_count.fetch_add(1);
  22115. res.set_chunked_content_provider(
  22116. "text/event-stream", [](size_t offset, DataSink &sink) {
  22117. if (offset == 0) {
  22118. std::string event = "data: hello\n\n";
  22119. sink.write(event.data(), event.size());
  22120. }
  22121. return false; // Close connection after sending
  22122. });
  22123. });
  22124. Client client("localhost", get_port());
  22125. sse::SSEClient sse(client, "/reconnect-test");
  22126. sse.on_message([&message_count](const sse::SSEMessage &) {
  22127. message_count.fetch_add(1);
  22128. });
  22129. sse.set_reconnect_interval(100);
  22130. sse.set_max_reconnect_attempts(3);
  22131. sse.start_async();
  22132. // Wait long enough for multiple reconnects
  22133. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22134. sse.stop();
  22135. // Should have connected multiple times (initial + reconnects)
  22136. EXPECT_GE(connection_count.load(), 2);
  22137. // Should have received messages from multiple connections
  22138. EXPECT_GE(message_count.load(), 2);
  22139. }
  22140. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22141. std::atomic<int> connection_count{0};
  22142. // Neither Content-Length nor chunked: the close ends the stream
  22143. server_->Get("/close-delimited",
  22144. [&connection_count](const Request &, Response &res) {
  22145. connection_count.fetch_add(1);
  22146. res.set_content_provider(
  22147. "text/event-stream", [](size_t offset, DataSink &sink) {
  22148. if (offset == 0) {
  22149. std::string event = "data: hello\n\n";
  22150. sink.write(event.data(), event.size());
  22151. } else {
  22152. sink.done();
  22153. }
  22154. return true;
  22155. });
  22156. });
  22157. Client client("localhost", get_port());
  22158. sse::SSEClient sse(client, "/close-delimited");
  22159. std::atomic<int> error_count{0};
  22160. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22161. sse.set_reconnect_interval(100);
  22162. sse.start_async();
  22163. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22164. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22165. }
  22166. sse.stop();
  22167. // Reconnects as after any end of the stream, but reports no error
  22168. EXPECT_GE(connection_count.load(), 2);
  22169. EXPECT_EQ(0, error_count.load());
  22170. }
  22171. // Test: A retry field that is not all ASCII digits is ignored
  22172. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22173. std::atomic<int> connection_count{0};
  22174. server_->Get("/bad-retry",
  22175. [&connection_count](const Request &, Response &res) {
  22176. connection_count.fetch_add(1);
  22177. res.set_chunked_content_provider(
  22178. "text/event-stream", [](size_t offset, DataSink &sink) {
  22179. if (offset == 0) {
  22180. std::string event = "retry: -1\ndata: hello\n\n";
  22181. sink.write(event.data(), event.size());
  22182. }
  22183. return false;
  22184. });
  22185. });
  22186. Client client("localhost", get_port());
  22187. sse::SSEClient sse(client, "/bad-retry");
  22188. sse.set_reconnect_interval(10000);
  22189. sse.start_async();
  22190. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22191. sse.stop();
  22192. EXPECT_EQ(connection_count.load(), 1);
  22193. }
  22194. // Test: A retry field of all ASCII digits sets the reconnection time
  22195. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22196. std::mutex mutex;
  22197. std::condition_variable cv;
  22198. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22199. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22200. {
  22201. std::lock_guard<std::mutex> lock(mutex);
  22202. connected_at.push_back(std::chrono::steady_clock::now());
  22203. cv.notify_all();
  22204. }
  22205. res.set_chunked_content_provider(
  22206. "text/event-stream", [](size_t offset, DataSink &sink) {
  22207. if (offset == 0) {
  22208. std::string event = "retry: 0\ndata: hello\n\n";
  22209. sink.write(event.data(), event.size());
  22210. }
  22211. return false;
  22212. });
  22213. });
  22214. Client client("localhost", get_port());
  22215. sse::SSEClient sse(client, "/zero-retry");
  22216. sse.set_reconnect_interval(10000);
  22217. sse.start_async();
  22218. {
  22219. std::unique_lock<std::mutex> lock(mutex);
  22220. cv.wait_for(lock, std::chrono::seconds(5),
  22221. [&] { return connected_at.size() >= 2; });
  22222. }
  22223. sse.stop();
  22224. // The server-supplied interval is applied, but never below 100ms, so
  22225. // "retry: 0" does not cause a busy reconnect loop
  22226. std::lock_guard<std::mutex> lock(mutex);
  22227. ASSERT_GE(connected_at.size(), 2u);
  22228. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22229. connected_at[1] - connected_at[0])
  22230. .count();
  22231. EXPECT_GE(interval_ms, 100);
  22232. }
  22233. // Test: Last-Event-ID sent on reconnect
  22234. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22235. std::atomic<int> connection_count{0};
  22236. std::vector<std::string> received_last_event_ids;
  22237. std::mutex id_mutex;
  22238. // Endpoint that checks Last-Event-ID header and sends event with ID
  22239. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22240. int conn = connection_count.fetch_add(1);
  22241. // Capture the Last-Event-ID header from each connection
  22242. {
  22243. std::lock_guard<std::mutex> lock(id_mutex);
  22244. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22245. }
  22246. res.set_chunked_content_provider(
  22247. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22248. if (offset == 0) {
  22249. std::string event =
  22250. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22251. sink.write(event.data(), event.size());
  22252. }
  22253. return false;
  22254. });
  22255. });
  22256. Client client("localhost", get_port());
  22257. sse::SSEClient sse(client, "/reconnect-with-id");
  22258. sse.set_reconnect_interval(100);
  22259. sse.set_max_reconnect_attempts(3);
  22260. sse.start_async();
  22261. // Wait for at least 2 connections
  22262. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22263. sse.stop();
  22264. // Verify behavior
  22265. std::lock_guard<std::mutex> lock(id_mutex);
  22266. EXPECT_GE(received_last_event_ids.size(), 2u);
  22267. // First connection should have no Last-Event-ID
  22268. if (!received_last_event_ids.empty()) {
  22269. EXPECT_EQ(received_last_event_ids[0], "");
  22270. }
  22271. // Second connection should have Last-Event-ID from first connection
  22272. if (received_last_event_ids.size() >= 2) {
  22273. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22274. }
  22275. }
  22276. // Test: set_headers updates headers used on reconnect
  22277. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22278. std::vector<std::string> received_tokens;
  22279. std::mutex token_mutex;
  22280. // Endpoint that captures Authorization header
  22281. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22282. {
  22283. std::lock_guard<std::mutex> lock(token_mutex);
  22284. received_tokens.push_back(req.get_header_value("Authorization"));
  22285. }
  22286. res.set_chunked_content_provider(
  22287. "text/event-stream", [](size_t offset, DataSink &sink) {
  22288. if (offset == 0) {
  22289. std::string event = "data: hello\n\n";
  22290. sink.write(event.data(), event.size());
  22291. }
  22292. return false; // Close connection to trigger reconnect
  22293. });
  22294. });
  22295. Client client("localhost", get_port());
  22296. Headers headers = {{"Authorization", "Bearer old-token"}};
  22297. sse::SSEClient sse(client, "/auth-check", headers);
  22298. // Update headers on each successful connection
  22299. sse.on_open(
  22300. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22301. sse.set_reconnect_interval(100);
  22302. sse.set_max_reconnect_attempts(3);
  22303. sse.start_async();
  22304. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22305. sse.stop();
  22306. std::lock_guard<std::mutex> lock(token_mutex);
  22307. ASSERT_GE(received_tokens.size(), 2u);
  22308. // First connection uses original header
  22309. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22310. // Second connection uses updated header from set_headers
  22311. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22312. }
  22313. // Test: 401 allows reconnection (so on_error can refresh headers)
  22314. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22315. std::atomic<int> connection_count{0};
  22316. // Endpoint: returns 401 on first attempt, 200 on second
  22317. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22318. int conn = connection_count.fetch_add(1);
  22319. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22320. res.status = StatusCode::Unauthorized_401;
  22321. res.set_content("Unauthorized", "text/plain");
  22322. return;
  22323. }
  22324. res.set_chunked_content_provider(
  22325. "text/event-stream", [](size_t offset, DataSink &sink) {
  22326. if (offset == 0) {
  22327. std::string event = "data: authenticated\n\n";
  22328. sink.write(event.data(), event.size());
  22329. }
  22330. return false;
  22331. });
  22332. });
  22333. Client client("localhost", get_port());
  22334. Headers headers = {{"Authorization", "Bearer expired"}};
  22335. sse::SSEClient sse(client, "/auth-retry", headers);
  22336. std::atomic<bool> message_received{false};
  22337. // Refresh token on error
  22338. sse.on_error(
  22339. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22340. sse.on_message([&](const sse::SSEMessage &msg) {
  22341. if (msg.data == "authenticated") { message_received.store(true); }
  22342. });
  22343. sse.set_reconnect_interval(100);
  22344. sse.set_max_reconnect_attempts(3);
  22345. sse.start_async();
  22346. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22347. sse.stop();
  22348. // Should have reconnected after 401 and succeeded with new token
  22349. EXPECT_GE(connection_count.load(), 2);
  22350. EXPECT_TRUE(message_received.load());
  22351. }
  22352. TEST(Issue2318Test, EmptyHostString) {
  22353. {
  22354. httplib::Client cli_empty("", PORT);
  22355. auto res = cli_empty.Get("/");
  22356. ASSERT_FALSE(res);
  22357. EXPECT_EQ(httplib::Error::Connection, res.error());
  22358. }
  22359. {
  22360. httplib::Client cli(" ", PORT);
  22361. auto res = cli.Get("/");
  22362. ASSERT_FALSE(res);
  22363. EXPECT_EQ(httplib::Error::Connection, res.error());
  22364. }
  22365. }
  22366. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22367. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22368. Server svr;
  22369. // Set a small payload limit (1KB)
  22370. svr.set_payload_max_length(1024);
  22371. svr.Post("/test", [&](const Request &req, Response &res) {
  22372. res.set_content("Body size: " + std::to_string(req.body.size()),
  22373. "text/plain");
  22374. });
  22375. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22376. auto se = detail::scope_exit([&] {
  22377. svr.stop();
  22378. listen_thread.join();
  22379. });
  22380. svr.wait_until_ready();
  22381. // Create data that compresses well but exceeds limit when decompressed
  22382. // 8KB of repeated null bytes compresses to a very small size
  22383. std::string original_data(8 * 1024, '\0');
  22384. // Compress the data using gzip
  22385. std::string compressed_data;
  22386. detail::gzip_compressor compressor;
  22387. compressor.compress(original_data.data(), original_data.size(), true,
  22388. [&](const char *data, size_t size) {
  22389. compressed_data.append(data, size);
  22390. return true;
  22391. });
  22392. // Verify compression worked (compressed should be much smaller)
  22393. ASSERT_LT(compressed_data.size(), original_data.size());
  22394. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22395. // Send compressed data with Content-Encoding: gzip
  22396. Client cli(HOST, PORT);
  22397. Headers headers = {{"Content-Encoding", "gzip"}};
  22398. auto res =
  22399. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22400. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22402. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22403. }
  22404. #endif
  22405. // ============================================================================
  22406. // OpenSSL-Specific Tests
  22407. // ============================================================================
  22408. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22409. X509 *readCertificate(const std::string &strFileName) {
  22410. std::ifstream inStream(strFileName);
  22411. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22412. std::istreambuf_iterator<char>());
  22413. if (strCertPEM.empty()) return (nullptr);
  22414. BIO *pbCert = BIO_new(BIO_s_mem());
  22415. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22416. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22417. BIO_free(pbCert);
  22418. return (pCert);
  22419. }
  22420. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22421. std::ifstream inStream(strFileName);
  22422. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22423. std::istreambuf_iterator<char>());
  22424. if (strPrivateKeyPEM.empty()) return (nullptr);
  22425. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22426. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22427. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22428. BIO_free(pbPrivKey);
  22429. return (pPrivateKey);
  22430. }
  22431. TEST(BindServerTest, UpdateCerts) {
  22432. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22433. int port = svr.bind_to_any_port("0.0.0.0");
  22434. ASSERT_TRUE(svr.is_valid());
  22435. ASSERT_TRUE(port > 0);
  22436. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22437. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22438. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22439. ASSERT_TRUE(cert != nullptr);
  22440. ASSERT_TRUE(ca_cert != nullptr);
  22441. ASSERT_TRUE(key != nullptr);
  22442. X509_STORE *cert_store = X509_STORE_new();
  22443. X509_STORE_add_cert(cert_store, ca_cert);
  22444. // svr.update_certs(cert, key, cert_store); // deprecated
  22445. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22446. CLIENT_CA_CERT_FILE);
  22447. ASSERT_TRUE(svr.is_valid());
  22448. svr.stop();
  22449. X509_STORE_free(cert_store);
  22450. X509_free(cert);
  22451. X509_free(ca_cert);
  22452. EVP_PKEY_free(key);
  22453. }
  22454. // Test that update_certs() updates client CA list correctly
  22455. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22456. // Start with file-based constructor
  22457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22458. ASSERT_TRUE(svr.is_valid());
  22459. // Initially no client CA list should be set
  22460. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22461. ASSERT_TRUE(ssl_ctx != nullptr);
  22462. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22463. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22464. // Now update with client CA (PEM string)
  22465. std::string cert_pem, key_pem, ca_pem;
  22466. read_file(SERVER_CERT_FILE, cert_pem);
  22467. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22468. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22469. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22470. ASSERT_TRUE(svr.is_valid());
  22471. // Now client CA list should be set
  22472. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22473. ASSERT_TRUE(ca_list_after != nullptr);
  22474. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22475. }
  22476. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22477. // Test that the file-path SSLServer constructor properly sets the client CA
  22478. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22479. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22480. ASSERT_TRUE(svr.is_valid());
  22481. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22482. ASSERT_TRUE(ssl_ctx != nullptr);
  22483. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22484. ASSERT_TRUE(ca_list != nullptr);
  22485. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22486. }
  22487. #endif
  22488. // ============================================================================
  22489. // MbedTLS-Specific Tests
  22490. // ============================================================================
  22491. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22492. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22493. using namespace httplib::tls;
  22494. // Track if callback was invoked
  22495. bool callback_invoked = false;
  22496. // The callback receives void* ctx which is actually MbedTlsContext*
  22497. // We can access the mbedtls_ssl_config via the context
  22498. auto setup_callback = [&callback_invoked](void *ctx) {
  22499. callback_invoked = true;
  22500. // Cast to MbedTlsContext* to access the ssl config
  22501. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22502. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22503. // Use static variables to hold certificate data (simplified for test)
  22504. static mbedtls_x509_crt own_cert;
  22505. static mbedtls_pk_context own_key;
  22506. static mbedtls_x509_crt ca_chain;
  22507. static bool initialized = false;
  22508. if (!initialized) {
  22509. mbedtls_x509_crt_init(&own_cert);
  22510. mbedtls_pk_init(&own_key);
  22511. mbedtls_x509_crt_init(&ca_chain);
  22512. // Load server certificate
  22513. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22514. return false;
  22515. }
  22516. // Load server private key.
  22517. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22518. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22519. #if MBEDTLS_VERSION_MAJOR == 3
  22520. ,
  22521. mbedtls_ctr_drbg_random, nullptr
  22522. #endif
  22523. ) != 0) {
  22524. return false;
  22525. }
  22526. // Load CA chain for client verification
  22527. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22528. return false;
  22529. }
  22530. initialized = true;
  22531. }
  22532. // Configure the SSL config
  22533. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22534. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22535. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22536. // Set minimum TLS version using mbedTLS native API
  22537. #if MBEDTLS_VERSION_MAJOR >= 3
  22538. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22539. #else
  22540. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22541. MBEDTLS_SSL_MINOR_VERSION_3);
  22542. #endif
  22543. return true;
  22544. };
  22545. SSLServer svr(setup_callback);
  22546. ASSERT_TRUE(svr.is_valid());
  22547. ASSERT_TRUE(callback_invoked);
  22548. svr.Get("/test", [&](const Request &req, Response &res) {
  22549. res.set_content("test", "text/plain");
  22550. auto cert = req.peer_cert();
  22551. ASSERT_TRUE(static_cast<bool>(cert));
  22552. auto common_name = cert.subject_cn();
  22553. EXPECT_EQ("Common Name", common_name);
  22554. });
  22555. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22556. auto se = detail::scope_exit([&] {
  22557. svr.stop();
  22558. t.join();
  22559. ASSERT_FALSE(svr.is_running());
  22560. });
  22561. svr.wait_until_ready();
  22562. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22563. cli.enable_server_certificate_verification(false);
  22564. cli.set_connection_timeout(30);
  22565. auto res = cli.Get("/test");
  22566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22567. ASSERT_EQ(StatusCode::OK_200, res->status);
  22568. }
  22569. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22570. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22571. // keep-alive SSL session, which reads through that config in
  22572. // mbedtls_ssl_close_notify.
  22573. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22575. ASSERT_TRUE(svr.is_valid());
  22576. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22577. res.set_content("test", "text/plain");
  22578. });
  22579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22580. auto se = detail::scope_exit([&] {
  22581. svr.stop();
  22582. t.join();
  22583. ASSERT_FALSE(svr.is_running());
  22584. });
  22585. svr.wait_until_ready();
  22586. {
  22587. SSLClient cli(HOST, PORT);
  22588. cli.enable_server_certificate_verification(false);
  22589. cli.set_keep_alive(true);
  22590. auto res = cli.Get("/test");
  22591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22592. ASSERT_EQ(StatusCode::OK_200, res->status);
  22593. // cli is destructed here with the keep-alive SSL session still open.
  22594. }
  22595. }
  22596. #endif
  22597. // WebSocket Tests
  22598. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22599. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22600. // defining the meaning of these bits has been negotiated.
  22601. auto make_frame = [](uint8_t first_byte) {
  22602. std::string frame;
  22603. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22604. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22605. frame += "Hello";
  22606. return frame;
  22607. };
  22608. // RSV1 set (0x40)
  22609. {
  22610. detail::BufferStream strm;
  22611. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22612. ws::Opcode opcode;
  22613. std::string payload;
  22614. bool fin;
  22615. EXPECT_EQ(
  22616. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22617. ws::impl::FrameRead::Fail);
  22618. }
  22619. // RSV2 set (0x20)
  22620. {
  22621. detail::BufferStream strm;
  22622. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22623. ws::Opcode opcode;
  22624. std::string payload;
  22625. bool fin;
  22626. EXPECT_EQ(
  22627. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22628. ws::impl::FrameRead::Fail);
  22629. }
  22630. // RSV3 set (0x10)
  22631. {
  22632. detail::BufferStream strm;
  22633. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22634. ws::Opcode opcode;
  22635. std::string payload;
  22636. bool fin;
  22637. EXPECT_EQ(
  22638. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22639. ws::impl::FrameRead::Fail);
  22640. }
  22641. // No RSV bits set - should succeed
  22642. {
  22643. detail::BufferStream strm;
  22644. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22645. ws::Opcode opcode;
  22646. std::string payload;
  22647. bool fin;
  22648. EXPECT_EQ(
  22649. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22650. ws::impl::FrameRead::Ok);
  22651. EXPECT_EQ(ws::Opcode::Text, opcode);
  22652. EXPECT_EQ("Hello", payload);
  22653. EXPECT_TRUE(fin);
  22654. }
  22655. }
  22656. TEST(WebSocketTest, ControlFrameValidation) {
  22657. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22658. // payload length <= 125.
  22659. // Ping with FIN=0 - must be rejected
  22660. {
  22661. detail::BufferStream strm;
  22662. std::string frame;
  22663. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22664. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22665. strm.write(frame.data(), frame.size());
  22666. ws::Opcode opcode;
  22667. std::string payload;
  22668. bool fin;
  22669. EXPECT_EQ(
  22670. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22671. ws::impl::FrameRead::Fail);
  22672. }
  22673. // Close with FIN=0 - must be rejected
  22674. {
  22675. detail::BufferStream strm;
  22676. std::string frame;
  22677. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22678. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22679. strm.write(frame.data(), frame.size());
  22680. ws::Opcode opcode;
  22681. std::string payload;
  22682. bool fin;
  22683. EXPECT_EQ(
  22684. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22685. ws::impl::FrameRead::Fail);
  22686. }
  22687. // Ping with payload_len=126 (extended length) - must be rejected
  22688. {
  22689. detail::BufferStream strm;
  22690. std::string frame;
  22691. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22692. frame += static_cast<char>(126); // payload_len=126 (>125)
  22693. frame += static_cast<char>(0x00); // extended length high byte
  22694. frame += static_cast<char>(126); // extended length low byte
  22695. frame += std::string(126, 'x');
  22696. strm.write(frame.data(), frame.size());
  22697. ws::Opcode opcode;
  22698. std::string payload;
  22699. bool fin;
  22700. EXPECT_EQ(
  22701. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22702. ws::impl::FrameRead::Fail);
  22703. }
  22704. // Ping with FIN=1 and payload_len=125 - should succeed
  22705. {
  22706. detail::BufferStream strm;
  22707. std::string frame;
  22708. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22709. frame += static_cast<char>(125); // payload_len=125
  22710. frame += std::string(125, 'x');
  22711. strm.write(frame.data(), frame.size());
  22712. ws::Opcode opcode;
  22713. std::string payload;
  22714. bool fin;
  22715. EXPECT_EQ(
  22716. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22717. ws::impl::FrameRead::Ok);
  22718. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22719. EXPECT_EQ(125u, payload.size());
  22720. EXPECT_TRUE(fin);
  22721. }
  22722. }
  22723. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22724. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22725. // length MUST be 0.
  22726. // MSB set - must be rejected
  22727. {
  22728. detail::BufferStream strm;
  22729. std::string frame;
  22730. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22731. frame += static_cast<char>(127); // 64-bit extended length
  22732. frame += static_cast<char>(0x80); // MSB set (invalid)
  22733. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22734. strm.write(frame.data(), frame.size());
  22735. ws::Opcode opcode;
  22736. std::string payload;
  22737. bool fin;
  22738. EXPECT_EQ(
  22739. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22740. ws::impl::FrameRead::Fail);
  22741. }
  22742. // MSB clear - should pass length parsing (will be rejected by max_len,
  22743. // but that's a different check; use a small length to verify)
  22744. {
  22745. detail::BufferStream strm;
  22746. std::string frame;
  22747. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22748. frame += static_cast<char>(127); // 64-bit extended length
  22749. frame += std::string(7, '\0'); // high bytes = 0
  22750. frame += static_cast<char>(0x03); // length = 3
  22751. frame += "abc";
  22752. strm.write(frame.data(), frame.size());
  22753. ws::Opcode opcode;
  22754. std::string payload;
  22755. bool fin;
  22756. EXPECT_EQ(
  22757. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22758. ws::impl::FrameRead::Ok);
  22759. EXPECT_EQ(ws::Opcode::Text, opcode);
  22760. EXPECT_EQ("abc", payload);
  22761. }
  22762. }
  22763. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22764. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22765. // Valid UTF-8
  22766. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22767. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22768. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22769. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22770. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22771. // Invalid UTF-8
  22772. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22773. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22774. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22775. EXPECT_FALSE(
  22776. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22777. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22778. }
  22779. TEST(WebSocketTest, ConnectAndDisconnect) {
  22780. Server svr;
  22781. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22782. std::string msg;
  22783. while (ws.read(msg)) {}
  22784. });
  22785. auto port = svr.bind_to_any_port(HOST);
  22786. std::thread t([&]() { svr.listen_after_bind(); });
  22787. svr.wait_until_ready();
  22788. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22789. auto res = client.connect();
  22790. ASSERT_TRUE(res);
  22791. EXPECT_EQ(Error::Success, res.error());
  22792. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22793. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22794. EXPECT_TRUE(client.is_open());
  22795. client.close();
  22796. EXPECT_FALSE(client.is_open());
  22797. svr.stop();
  22798. t.join();
  22799. }
  22800. TEST(WebSocketTest, ValidURL) {
  22801. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22802. EXPECT_TRUE(ws1.is_valid());
  22803. ws::WebSocketClient ws2("ws://example.com/path");
  22804. EXPECT_TRUE(ws2.is_valid());
  22805. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22806. EXPECT_TRUE(ws3.is_valid());
  22807. #ifdef CPPHTTPLIB_SSL_ENABLED
  22808. ws::WebSocketClient wss1("wss://example.com/path");
  22809. EXPECT_TRUE(wss1.is_valid());
  22810. ws::WebSocketClient wss2("wss://example.com:443/path");
  22811. EXPECT_TRUE(wss2.is_valid());
  22812. #endif
  22813. }
  22814. TEST(WebSocketTest, InvalidURL) {
  22815. // No scheme
  22816. ws::WebSocketClient ws1("localhost:8080/path");
  22817. EXPECT_FALSE(ws1.is_valid());
  22818. // No path
  22819. ws::WebSocketClient ws2("ws://localhost:8080");
  22820. EXPECT_FALSE(ws2.is_valid());
  22821. // Empty string
  22822. ws::WebSocketClient ws3("");
  22823. EXPECT_FALSE(ws3.is_valid());
  22824. // Missing host
  22825. ws::WebSocketClient ws4("ws://:8080/path");
  22826. EXPECT_FALSE(ws4.is_valid());
  22827. // Port number overflow — should not crash
  22828. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22829. EXPECT_FALSE(ws5.is_valid());
  22830. // Port out of range
  22831. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22832. EXPECT_FALSE(ws6.is_valid());
  22833. }
  22834. TEST(WebSocketTest, UnsupportedScheme) {
  22835. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22836. ws::WebSocketClient ws1("http://localhost:8080/path");
  22837. EXPECT_FALSE(ws1.is_valid());
  22838. ws::WebSocketClient ws2("https://localhost:8080/path");
  22839. EXPECT_FALSE(ws2.is_valid());
  22840. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22841. EXPECT_FALSE(ws3.is_valid());
  22842. #else
  22843. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22844. std::invalid_argument);
  22845. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22846. std::invalid_argument);
  22847. #endif
  22848. }
  22849. TEST(WebSocketTest, ConnectWhenInvalid) {
  22850. ws::WebSocketClient ws("not a valid url");
  22851. EXPECT_FALSE(ws.is_valid());
  22852. auto res = ws.connect();
  22853. EXPECT_FALSE(res);
  22854. EXPECT_EQ(Error::Connection, res.error());
  22855. EXPECT_EQ(-1, res.status());
  22856. }
  22857. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22858. // Grab a port that is free, then close it again so nothing listens there
  22859. Server svr;
  22860. auto port = svr.bind_to_any_port(HOST);
  22861. svr.stop();
  22862. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22863. auto res = client.connect();
  22864. ASSERT_FALSE(res);
  22865. EXPECT_EQ(Error::Connection, res.error());
  22866. EXPECT_EQ(-1, res.status());
  22867. }
  22868. TEST(WebSocketTest, DefaultPort) {
  22869. ws::WebSocketClient ws1("ws://example.com/path");
  22870. EXPECT_TRUE(ws1.is_valid());
  22871. // ws:// defaults to port 80 (verified by successful parse)
  22872. #ifdef CPPHTTPLIB_SSL_ENABLED
  22873. ws::WebSocketClient ws2("wss://example.com/path");
  22874. EXPECT_TRUE(ws2.is_valid());
  22875. // wss:// defaults to port 443 (verified by successful parse)
  22876. #endif
  22877. }
  22878. TEST(WebSocketTest, IPv6LiteralAddress) {
  22879. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22880. EXPECT_TRUE(ws1.is_valid());
  22881. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22882. EXPECT_TRUE(ws2.is_valid());
  22883. }
  22884. TEST(WebSocketTest, ComplexPath) {
  22885. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22886. EXPECT_TRUE(ws1.is_valid());
  22887. ws::WebSocketClient ws2("ws://localhost:8080/");
  22888. EXPECT_TRUE(ws2.is_valid());
  22889. }
  22890. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22891. Server svr;
  22892. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22893. std::string msg;
  22894. while (ws.read(msg)) {}
  22895. });
  22896. auto port = svr.bind_to_any_port(HOST);
  22897. std::thread t([&]() { svr.listen_after_bind(); });
  22898. svr.wait_until_ready();
  22899. auto another_host = "example.com";
  22900. auto wrong_ip = "192.0.2.1";
  22901. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22902. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22903. ASSERT_TRUE(client.connect());
  22904. EXPECT_TRUE(client.is_open());
  22905. client.close();
  22906. svr.stop();
  22907. t.join();
  22908. }
  22909. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22910. Server svr;
  22911. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22912. std::string msg;
  22913. while (ws.read(msg)) {}
  22914. });
  22915. auto port = svr.bind_to_any_port(HOST);
  22916. std::thread t([&]() { svr.listen_after_bind(); });
  22917. svr.wait_until_ready();
  22918. auto wrong_ip = "192.0.2.1";
  22919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22920. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22921. client.set_connection_timeout(1);
  22922. client.set_read_timeout(1);
  22923. client.set_write_timeout(1);
  22924. EXPECT_FALSE(client.connect());
  22925. EXPECT_FALSE(client.is_open());
  22926. svr.stop();
  22927. t.join();
  22928. }
  22929. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22930. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22931. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22932. // (RFC 6761) is only a map key and the Host header value.
  22933. auto host = "target.invalid";
  22934. Server svr;
  22935. std::string received_host;
  22936. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22937. received_host = req.get_header_value("Host");
  22938. std::string msg;
  22939. while (ws.read(msg)) {}
  22940. });
  22941. auto port = svr.bind_to_any_port(HOST);
  22942. std::thread t([&]() { svr.listen_after_bind(); });
  22943. // ASSERT_* below returns from the test body, which would leave t joinable
  22944. // and make ~thread call std::terminate.
  22945. auto se = detail::scope_exit([&] {
  22946. svr.stop();
  22947. if (t.joinable()) { t.join(); }
  22948. });
  22949. svr.wait_until_ready();
  22950. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22951. std::to_string(port) + "/ws");
  22952. client.set_hostname_addr_map({{host, HOST}});
  22953. ASSERT_TRUE(client.connect());
  22954. EXPECT_TRUE(client.is_open());
  22955. client.close();
  22956. svr.stop();
  22957. t.join();
  22958. // The mapping only redirects the connection; the identity stays host_.
  22959. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22960. }
  22961. class WebSocketIntegrationTest : public ::testing::Test {
  22962. protected:
  22963. void SetUp() override {
  22964. server_ = httplib::detail::make_unique<Server>();
  22965. setup_server();
  22966. start_server();
  22967. }
  22968. void TearDown() override {
  22969. server_->stop();
  22970. if (server_thread_.joinable()) { server_thread_.join(); }
  22971. }
  22972. void setup_server() {
  22973. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22974. std::string msg;
  22975. ws::ReadResult ret;
  22976. while ((ret = ws.read(msg))) {
  22977. if (ret == ws::Binary) {
  22978. ws.send(msg.data(), msg.size());
  22979. } else {
  22980. ws.send(msg);
  22981. }
  22982. }
  22983. });
  22984. server_->WebSocket("/ws-echo-string",
  22985. [](const Request &, ws::WebSocket &ws) {
  22986. std::string msg;
  22987. while (ws.read(msg)) {
  22988. ws.send("echo: " + msg);
  22989. }
  22990. });
  22991. server_->WebSocket(
  22992. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22993. // Echo back request metadata
  22994. ws.send("path:" + req.path);
  22995. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22996. std::string msg;
  22997. while (ws.read(msg)) {}
  22998. });
  22999. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23000. std::string msg;
  23001. ws.read(msg); // wait for a message
  23002. ws.close();
  23003. });
  23004. server_->WebSocket("/ws-close-status",
  23005. [](const Request &, ws::WebSocket &ws) {
  23006. std::string msg;
  23007. ws.read(msg); // wait for a message
  23008. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23009. });
  23010. server_->WebSocket(
  23011. "/ws-subprotocol",
  23012. [](const Request &, ws::WebSocket &ws) {
  23013. std::string msg;
  23014. while (ws.read(msg)) {
  23015. ws.send(msg);
  23016. }
  23017. },
  23018. [](const std::vector<std::string> &protocols) -> std::string {
  23019. for (const auto &p : protocols) {
  23020. if (p == "graphql-ws") { return p; }
  23021. }
  23022. return "";
  23023. });
  23024. server_->WebSocket(
  23025. "/ws-subprotocol-unoffered",
  23026. [](const Request &, ws::WebSocket &ws) {
  23027. std::string msg;
  23028. while (ws.read(msg)) {
  23029. ws.send(msg);
  23030. }
  23031. },
  23032. [](const std::vector<std::string> &) -> std::string {
  23033. return "admin";
  23034. });
  23035. }
  23036. void start_server() {
  23037. port_ = server_->bind_to_any_port(HOST);
  23038. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23039. server_->wait_until_ready();
  23040. }
  23041. std::unique_ptr<Server> server_;
  23042. std::thread server_thread_;
  23043. int port_ = 0;
  23044. };
  23045. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23046. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23047. "/ws-echo");
  23048. ASSERT_TRUE(client.connect());
  23049. ASSERT_TRUE(client.is_open());
  23050. ASSERT_TRUE(client.send("Hello WebSocket"));
  23051. std::string msg;
  23052. EXPECT_EQ(ws::Text, client.read(msg));
  23053. EXPECT_EQ("Hello WebSocket", msg);
  23054. client.close();
  23055. }
  23056. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23057. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23058. "/ws-echo");
  23059. ASSERT_TRUE(client.connect());
  23060. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23061. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23062. std::string msg;
  23063. EXPECT_EQ(ws::Binary, client.read(msg));
  23064. EXPECT_EQ(binary_data, msg);
  23065. client.close();
  23066. }
  23067. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23068. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23069. "/ws-echo");
  23070. ASSERT_TRUE(client.connect());
  23071. for (int i = 0; i < 10; i++) {
  23072. auto text = "message " + std::to_string(i);
  23073. ASSERT_TRUE(client.send(text));
  23074. std::string msg;
  23075. ASSERT_TRUE(client.read(msg));
  23076. EXPECT_EQ(text, msg);
  23077. }
  23078. client.close();
  23079. }
  23080. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23081. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23082. "/ws-close");
  23083. ASSERT_TRUE(client.connect());
  23084. // Send a message to trigger the server to close
  23085. ASSERT_TRUE(client.send("trigger close"));
  23086. // The server will close, so read should return false
  23087. std::string msg;
  23088. EXPECT_FALSE(client.read(msg));
  23089. EXPECT_FALSE(client.is_open());
  23090. }
  23091. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23092. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23093. "/ws-echo");
  23094. ASSERT_TRUE(client.connect());
  23095. // 128KB message
  23096. std::string large_data(128 * 1024, 'X');
  23097. ASSERT_TRUE(client.send(large_data));
  23098. std::string msg;
  23099. ASSERT_TRUE(client.read(msg));
  23100. EXPECT_EQ(large_data, msg);
  23101. client.close();
  23102. }
  23103. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23104. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23105. "/ws-echo");
  23106. ASSERT_TRUE(client.connect());
  23107. const int num_threads = 4;
  23108. std::vector<std::thread> threads;
  23109. std::atomic<int> send_count{0};
  23110. for (int t = 0; t < num_threads; t++) {
  23111. threads.emplace_back([&client, &send_count, t]() {
  23112. for (int i = 0; i < 5; i++) {
  23113. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23114. if (client.send(text)) { send_count++; }
  23115. }
  23116. });
  23117. }
  23118. for (auto &th : threads) {
  23119. th.join();
  23120. }
  23121. int received = 0;
  23122. std::string msg;
  23123. while (received < send_count.load()) {
  23124. if (!client.read(msg)) { break; }
  23125. received++;
  23126. }
  23127. EXPECT_EQ(send_count.load(), received);
  23128. client.close();
  23129. }
  23130. TEST_F(WebSocketIntegrationTest, ReadString) {
  23131. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23132. "/ws-echo-string");
  23133. ASSERT_TRUE(client.connect());
  23134. ASSERT_TRUE(client.send("hello"));
  23135. std::string msg;
  23136. ASSERT_TRUE(client.read(msg));
  23137. EXPECT_EQ("echo: hello", msg);
  23138. ASSERT_TRUE(client.send("world"));
  23139. ASSERT_TRUE(client.read(msg));
  23140. EXPECT_EQ("echo: world", msg);
  23141. client.close();
  23142. }
  23143. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23144. Headers headers = {{"X-Test-Header", "test-value"}};
  23145. ws::WebSocketClient client(
  23146. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23147. ASSERT_TRUE(client.connect());
  23148. std::string msg;
  23149. ASSERT_TRUE(client.read(msg));
  23150. EXPECT_EQ("path:/ws-request-info", msg);
  23151. ASSERT_TRUE(client.read(msg));
  23152. EXPECT_EQ("header:test-value", msg);
  23153. client.close();
  23154. }
  23155. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23156. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23157. "/ws-echo");
  23158. client.set_read_timeout(1, 0); // 1 second
  23159. ASSERT_TRUE(client.connect());
  23160. // Don't send anything — server echo handler waits for a message, so read()
  23161. // should time out. The connection survives it: nothing was consumed.
  23162. std::string msg;
  23163. EXPECT_EQ(client.read(msg), ws::Timeout);
  23164. EXPECT_TRUE(client.is_open());
  23165. // And it is still usable afterwards.
  23166. EXPECT_TRUE(client.send("after timeout"));
  23167. EXPECT_EQ(client.read(msg), ws::Text);
  23168. EXPECT_EQ(msg, "after timeout");
  23169. }
  23170. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23171. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23172. "/ws-echo");
  23173. client.set_read_timeout(1, 0);
  23174. ASSERT_TRUE(client.connect());
  23175. ASSERT_TRUE(client.send("first"));
  23176. std::string msg;
  23177. ASSERT_EQ(client.read(msg), ws::Text);
  23178. ASSERT_EQ(msg, "first");
  23179. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23180. // not be used with a read timeout: it would reprocess the previous message.
  23181. EXPECT_EQ(client.read(msg), ws::Timeout);
  23182. EXPECT_EQ(msg, "first");
  23183. }
  23184. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23185. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23186. "/ws-echo");
  23187. ASSERT_TRUE(client.connect());
  23188. // Setting it once the connection is open reaches the live stream, not just
  23189. // the seed for the next connect().
  23190. client.set_read_timeout(1, 0);
  23191. std::string msg;
  23192. EXPECT_EQ(client.read(msg), ws::Timeout);
  23193. EXPECT_TRUE(client.is_open());
  23194. }
  23195. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23196. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23197. "/ws-echo");
  23198. client.set_read_timeout(5, 0);
  23199. ASSERT_TRUE(client.connect());
  23200. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23201. // The server should reject it and close the connection.
  23202. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23203. client.send(oversized);
  23204. // The server's read() should have failed due to payload limit,
  23205. // so our read() should return false (connection closed).
  23206. std::string msg;
  23207. EXPECT_FALSE(client.read(msg));
  23208. }
  23209. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23210. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23211. "/ws-echo");
  23212. client.set_read_timeout(10, 0);
  23213. ASSERT_TRUE(client.connect());
  23214. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23215. // This should succeed.
  23216. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23217. ASSERT_TRUE(client.send(at_limit));
  23218. std::string msg;
  23219. ASSERT_TRUE(client.read(msg));
  23220. EXPECT_EQ(at_limit.size(), msg.size());
  23221. client.close();
  23222. }
  23223. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23224. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23225. "/nonexistent");
  23226. auto res = client.connect();
  23227. EXPECT_FALSE(res);
  23228. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23229. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23230. EXPECT_FALSE(client.is_open());
  23231. }
  23232. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23233. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23234. "/ws-echo");
  23235. ASSERT_TRUE(client.connect());
  23236. ASSERT_TRUE(client.send(""));
  23237. std::string msg;
  23238. EXPECT_EQ(ws::Text, client.read(msg));
  23239. EXPECT_EQ("", msg);
  23240. client.close();
  23241. }
  23242. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23243. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23244. "/ws-echo");
  23245. // First connection
  23246. ASSERT_TRUE(client.connect());
  23247. ASSERT_TRUE(client.send("first"));
  23248. std::string msg;
  23249. ASSERT_TRUE(client.read(msg));
  23250. EXPECT_EQ("first", msg);
  23251. client.close();
  23252. EXPECT_FALSE(client.is_open());
  23253. // Reconnect using the same client object
  23254. ASSERT_TRUE(client.connect());
  23255. ASSERT_TRUE(client.is_open());
  23256. ASSERT_TRUE(client.send("second"));
  23257. ASSERT_TRUE(client.read(msg));
  23258. EXPECT_EQ("second", msg);
  23259. client.close();
  23260. }
  23261. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23262. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23263. "/ws-close-status");
  23264. ASSERT_TRUE(client.connect());
  23265. // Trigger the server to close with GoingAway status
  23266. ASSERT_TRUE(client.send("trigger"));
  23267. // read() should return false after receiving the close frame
  23268. std::string msg;
  23269. EXPECT_FALSE(client.read(msg));
  23270. EXPECT_FALSE(client.is_open());
  23271. }
  23272. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23273. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23274. "/ws-echo");
  23275. ASSERT_TRUE(client.connect());
  23276. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23277. EXPECT_FALSE(client.is_open());
  23278. }
  23279. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23280. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23281. ws::WebSocketClient client(
  23282. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23283. ASSERT_TRUE(client.connect());
  23284. // Server should have selected graphql-ws
  23285. EXPECT_EQ("graphql-ws", client.subprotocol());
  23286. client.close();
  23287. }
  23288. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23289. Headers headers;
  23290. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23291. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23292. ws::WebSocketClient client(
  23293. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23294. ASSERT_TRUE(client.connect());
  23295. // The offer on the second field line counts too, so graphql-ws is selected
  23296. EXPECT_EQ("graphql-ws", client.subprotocol());
  23297. client.close();
  23298. }
  23299. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23300. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23301. ws::WebSocketClient client(
  23302. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23303. ASSERT_TRUE(client.connect());
  23304. // Server should not have selected any subprotocol
  23305. EXPECT_TRUE(client.subprotocol().empty());
  23306. client.close();
  23307. }
  23308. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23309. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23310. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23311. "/ws-subprotocol-unoffered",
  23312. headers);
  23313. ASSERT_TRUE(client.connect());
  23314. EXPECT_TRUE(client.subprotocol().empty());
  23315. client.close();
  23316. }
  23317. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23318. // Connect without requesting any subprotocol
  23319. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23320. "/ws-subprotocol");
  23321. ASSERT_TRUE(client.connect());
  23322. EXPECT_TRUE(client.subprotocol().empty());
  23323. client.close();
  23324. }
  23325. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23326. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23327. "/ws-echo");
  23328. client.set_tcp_nodelay(true);
  23329. client.set_connection_timeout(3, 0);
  23330. bool socket_options_called = false;
  23331. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23332. ASSERT_TRUE(client.connect());
  23333. ASSERT_TRUE(client.is_open());
  23334. EXPECT_TRUE(socket_options_called);
  23335. ASSERT_TRUE(client.send("hello"));
  23336. std::string msg;
  23337. auto result = client.read(msg);
  23338. EXPECT_EQ(result, ws::ReadResult::Text);
  23339. EXPECT_EQ(msg, "hello");
  23340. client.close();
  23341. }
  23342. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23343. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23344. "/ws-echo");
  23345. client.set_connection_timeout(std::chrono::seconds(3));
  23346. client.set_write_timeout(std::chrono::seconds(3));
  23347. // A sub-second remainder exercises the seconds/microseconds split.
  23348. client.set_read_timeout(std::chrono::milliseconds(1500));
  23349. ASSERT_TRUE(client.connect());
  23350. auto start = std::chrono::steady_clock::now();
  23351. std::string msg;
  23352. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23353. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23354. std::chrono::steady_clock::now() - start)
  23355. .count();
  23356. // Above 1s so that dropping the microseconds half of the split fails here.
  23357. // Ignoring the setter altogether would not reach this line at all: a client
  23358. // waits forever by default.
  23359. EXPECT_GE(elapsed, 1400);
  23360. EXPECT_LT(elapsed, 30000);
  23361. }
  23362. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23363. Server svr;
  23364. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23365. if (!req.has_header("Authorization")) {
  23366. res.status = StatusCode::Unauthorized_401;
  23367. res.set_content("Unauthorized", "text/plain");
  23368. return Server::HandlerResponse::Handled;
  23369. }
  23370. return Server::HandlerResponse::Unhandled;
  23371. });
  23372. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23373. std::string msg;
  23374. while (ws.read(msg)) {
  23375. ws.send(msg);
  23376. }
  23377. });
  23378. auto port = svr.bind_to_any_port("localhost");
  23379. std::thread t([&]() { svr.listen_after_bind(); });
  23380. svr.wait_until_ready();
  23381. // Without Authorization header - should be rejected before upgrade
  23382. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23383. EXPECT_FALSE(client1.connect());
  23384. // The rejection is framed like any other HTTP response
  23385. {
  23386. Client cli("localhost", port);
  23387. Headers headers = {{"Upgrade", "websocket"},
  23388. {"Connection", "Upgrade"},
  23389. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23390. {"Sec-WebSocket-Version", "13"}};
  23391. auto res = cli.Get("/ws", headers);
  23392. ASSERT_TRUE(res);
  23393. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23394. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23395. EXPECT_EQ("Unauthorized", res->body);
  23396. }
  23397. // With Authorization header - should succeed
  23398. Headers headers = {{"Authorization", "Bearer token123"}};
  23399. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23400. headers);
  23401. ASSERT_TRUE(client2.connect());
  23402. ASSERT_TRUE(client2.send("hello"));
  23403. std::string msg;
  23404. ASSERT_TRUE(client2.read(msg));
  23405. EXPECT_EQ("hello", msg);
  23406. client2.close();
  23407. svr.stop();
  23408. t.join();
  23409. }
  23410. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23411. Server svr;
  23412. std::atomic<int> pre_routing_calls{0};
  23413. std::atomic<int> pre_request_calls{0};
  23414. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23415. pre_routing_calls++;
  23416. if (req.path == "/handled") {
  23417. res.set_content("handled", "text/plain");
  23418. return Server::HandlerResponse::Handled;
  23419. }
  23420. return Server::HandlerResponse::Unhandled;
  23421. });
  23422. svr.set_pre_request_handler([&](const Request &, Response &) {
  23423. pre_request_calls++;
  23424. return Server::HandlerResponse::Unhandled;
  23425. });
  23426. svr.Get("/http", [](const Request &, Response &res) {
  23427. res.set_content("http", "text/plain");
  23428. });
  23429. svr.WebSocket("/ws",
  23430. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23431. auto port = svr.bind_to_any_port("localhost");
  23432. std::thread t([&]() { svr.listen_after_bind(); });
  23433. auto se = detail::scope_exit([&] {
  23434. svr.stop();
  23435. t.join();
  23436. });
  23437. svr.wait_until_ready();
  23438. Headers upgrade = {{"Upgrade", "websocket"},
  23439. {"Connection", "Upgrade"},
  23440. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23441. {"Sec-WebSocket-Version", "13"}};
  23442. auto get = [&](const char *path) {
  23443. pre_routing_calls = 0;
  23444. return Client("localhost", port).Get(path, upgrade);
  23445. };
  23446. // No WebSocket route, but an HTTP one
  23447. auto res = get("/http");
  23448. ASSERT_TRUE(res);
  23449. EXPECT_EQ(StatusCode::OK_200, res->status);
  23450. EXPECT_EQ("http", res->body);
  23451. EXPECT_EQ(1, pre_routing_calls);
  23452. EXPECT_EQ(1, pre_request_calls);
  23453. // No route at all
  23454. res = get("/none");
  23455. ASSERT_TRUE(res);
  23456. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23457. EXPECT_EQ(1, pre_routing_calls);
  23458. // Answered by the pre-routing handler
  23459. res = get("/handled");
  23460. ASSERT_TRUE(res);
  23461. EXPECT_EQ(StatusCode::OK_200, res->status);
  23462. EXPECT_EQ("handled", res->body);
  23463. EXPECT_EQ(1, pre_routing_calls);
  23464. // A WebSocket route
  23465. pre_routing_calls = 0;
  23466. pre_request_calls = 0;
  23467. {
  23468. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23469. "/ws");
  23470. ASSERT_TRUE(client.connect());
  23471. std::string msg;
  23472. ASSERT_TRUE(client.read(msg));
  23473. EXPECT_EQ("ws", msg);
  23474. client.close();
  23475. }
  23476. EXPECT_EQ(1, pre_routing_calls);
  23477. EXPECT_EQ(1, pre_request_calls);
  23478. }
  23479. // An upgrade request answered by a hook leaves its body unread, so that body
  23480. // must not be served as the next request on the connection.
  23481. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23482. Server svr;
  23483. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23484. if (req.path == "/pre-routing") {
  23485. res.set_content("pre-routing", "text/plain");
  23486. return Server::HandlerResponse::Handled;
  23487. }
  23488. return Server::HandlerResponse::Unhandled;
  23489. });
  23490. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23491. if (req.matched_route == "/pre-request") {
  23492. res.set_content("pre-request", "text/plain");
  23493. return Server::HandlerResponse::Handled;
  23494. }
  23495. return Server::HandlerResponse::Unhandled;
  23496. });
  23497. svr.Get("/smuggled", [](const Request &, Response &res) {
  23498. res.set_content("smuggled", "text/plain");
  23499. });
  23500. svr.WebSocket("/pre-request",
  23501. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23502. auto port = svr.bind_to_any_port(HOST);
  23503. std::thread t([&]() { svr.listen_after_bind(); });
  23504. auto se = detail::scope_exit([&] {
  23505. svr.stop();
  23506. t.join();
  23507. });
  23508. svr.wait_until_ready();
  23509. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23510. for (auto path : {"/pre-routing", "/pre-request"}) {
  23511. std::string req = std::string("GET ") + path +
  23512. " HTTP/1.1\r\n"
  23513. "Host: localhost\r\n"
  23514. "Upgrade: websocket\r\n"
  23515. "Connection: Upgrade\r\n"
  23516. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23517. "Sec-WebSocket-Version: 13\r\n"
  23518. "Content-Length: " +
  23519. std::to_string(body.size()) + "\r\n\r\n" + body;
  23520. std::string res;
  23521. ASSERT_TRUE(send_request(5, req, &res, port));
  23522. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23523. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23524. // Only one response, and the body was not served as a request
  23525. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23526. }
  23527. }
  23528. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23529. Server svr;
  23530. std::atomic<int> pre_request_calls{0};
  23531. std::atomic<bool> route_matched{false};
  23532. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23533. pre_request_calls++;
  23534. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23535. if (req.get_header_value("Authorization") != "Bearer token123") {
  23536. res.status = StatusCode::Unauthorized_401;
  23537. res.set_content("Unauthorized", "text/plain");
  23538. return Server::HandlerResponse::Handled;
  23539. }
  23540. return Server::HandlerResponse::Unhandled;
  23541. });
  23542. std::atomic<bool> handler_called{false};
  23543. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23544. handler_called = true;
  23545. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23546. });
  23547. auto port = svr.bind_to_any_port("localhost");
  23548. std::thread t([&]() { svr.listen_after_bind(); });
  23549. svr.wait_until_ready();
  23550. // Without Authorization header - should be rejected before upgrade
  23551. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23552. "/ws/1");
  23553. EXPECT_FALSE(client1.connect());
  23554. EXPECT_FALSE(handler_called);
  23555. EXPECT_EQ(1, pre_request_calls);
  23556. EXPECT_TRUE(route_matched);
  23557. // The rejection is an ordinary HTTP response, not a protocol switch
  23558. {
  23559. Client cli("localhost", port);
  23560. Headers headers = {{"Upgrade", "websocket"},
  23561. {"Connection", "Upgrade"},
  23562. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23563. {"Sec-WebSocket-Version", "13"}};
  23564. auto res = cli.Get("/ws/1", headers);
  23565. ASSERT_TRUE(res);
  23566. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23567. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23568. EXPECT_EQ("Unauthorized", res->body);
  23569. }
  23570. EXPECT_FALSE(handler_called);
  23571. // With Authorization header - should succeed
  23572. Headers headers = {{"Authorization", "Bearer token123"}};
  23573. ws::WebSocketClient client2(
  23574. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23575. ASSERT_TRUE(client2.connect());
  23576. std::string msg;
  23577. ASSERT_TRUE(client2.read(msg));
  23578. EXPECT_EQ("/ws/:id 2", msg);
  23579. EXPECT_TRUE(handler_called);
  23580. client2.close();
  23581. svr.stop();
  23582. t.join();
  23583. }
  23584. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23585. Server svr;
  23586. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23587. // A read timeout is how a handler gets control back. Without it, a handler
  23588. // parked in read() can never write on the connection it is reading.
  23589. ws.set_read_timeout(std::chrono::milliseconds(100));
  23590. std::string msg;
  23591. while (ws.is_open()) {
  23592. auto r = ws.read(msg);
  23593. if (r == httplib::ws::Timeout) {
  23594. ws.send("tick");
  23595. continue;
  23596. }
  23597. if (r == httplib::ws::Fail) { break; }
  23598. ws.send(msg);
  23599. }
  23600. });
  23601. auto port = svr.bind_to_any_port("localhost");
  23602. std::thread t([&]() { svr.listen_after_bind(); });
  23603. svr.wait_until_ready();
  23604. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23605. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23606. ASSERT_TRUE(client.connect());
  23607. // The client sends nothing, so anything it receives came out of the
  23608. // handler's timeout path.
  23609. std::string msg;
  23610. ASSERT_EQ(client.read(msg), ws::Text);
  23611. EXPECT_EQ("tick", msg);
  23612. client.close();
  23613. svr.stop();
  23614. t.join();
  23615. }
  23616. // Stream::read may return fewer bytes than asked for. This is that contract at
  23617. // its worst -- one byte per call -- which is what a frame header straddling a
  23618. // read buffer's boundary looks like to the frame parser.
  23619. class WsByteAtATimeStream : public Stream {
  23620. public:
  23621. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23622. bool is_readable() const override { return true; }
  23623. bool wait_readable() const override { return true; }
  23624. bool wait_writable() const override { return true; }
  23625. ssize_t read(char *ptr, size_t size) override {
  23626. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23627. *ptr = data_[pos_++];
  23628. return 1;
  23629. }
  23630. ssize_t write(const char *, size_t size) override {
  23631. return static_cast<ssize_t>(size);
  23632. }
  23633. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23634. ip = "127.0.0.1";
  23635. port = 0;
  23636. }
  23637. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23638. ip = "127.0.0.1";
  23639. port = 0;
  23640. }
  23641. socket_t socket() const override { return INVALID_SOCKET; }
  23642. time_t duration() const override { return 0; }
  23643. private:
  23644. std::string data_;
  23645. size_t pos_ = 0;
  23646. };
  23647. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23648. // The payload uses the 16-bit extended length, so the header, the length
  23649. // and the mask key are all multi-byte fields here. Each used to be read
  23650. // with a single read() call, which fails as soon as one is split. The
  23651. // payload is also a little over one read chunk, so it is read in two.
  23652. std::string body;
  23653. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23654. body += static_cast<char>(i % 251);
  23655. }
  23656. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23657. std::string frame;
  23658. frame += static_cast<char>(0x81); // FIN + Text
  23659. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23660. frame += static_cast<char>(body.size() >> 8);
  23661. frame += static_cast<char>(body.size() & 0xff);
  23662. for (size_t i = 0; i < 4; i++) {
  23663. frame += static_cast<char>(mask[i]);
  23664. }
  23665. for (size_t i = 0; i < body.size(); i++) {
  23666. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23667. }
  23668. WsByteAtATimeStream strm(frame);
  23669. ws::Opcode opcode;
  23670. std::string payload;
  23671. bool fin = false;
  23672. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23673. /*expect_masked=*/true, body.size()),
  23674. ws::impl::FrameRead::Ok);
  23675. EXPECT_TRUE(fin);
  23676. EXPECT_EQ(opcode, ws::Opcode::Text);
  23677. EXPECT_EQ(payload, body);
  23678. }
  23679. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23680. std::string body(2000, 'x');
  23681. std::string frame;
  23682. frame += static_cast<char>(0x82); // FIN + Binary
  23683. frame += static_cast<char>(126); // 16-bit length follows
  23684. frame += static_cast<char>(body.size() >> 8);
  23685. frame += static_cast<char>(body.size() & 0xff);
  23686. frame += body;
  23687. detail::BufferStream strm;
  23688. strm.write(frame.data(), frame.size());
  23689. ws::Opcode opcode;
  23690. std::string payload;
  23691. bool fin;
  23692. EXPECT_EQ(
  23693. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23694. ws::impl::FrameRead::Ok);
  23695. EXPECT_EQ(body, payload);
  23696. }
  23697. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23698. // The header announces the largest payload allowed, and only 3 bytes of it
  23699. // ever arrive.
  23700. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23701. std::string frame;
  23702. frame += static_cast<char>(0x82); // FIN + Binary
  23703. frame += static_cast<char>(127); // 64-bit length follows
  23704. for (int shift = 56; shift >= 0; shift -= 8) {
  23705. frame += static_cast<char>((len >> shift) & 0xff);
  23706. }
  23707. frame += "abc";
  23708. detail::BufferStream strm;
  23709. strm.write(frame.data(), frame.size());
  23710. ws::Opcode opcode;
  23711. std::string payload;
  23712. bool fin;
  23713. EXPECT_EQ(
  23714. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23715. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23716. ws::impl::FrameRead::Fail);
  23717. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23718. }
  23719. TEST(WebSocketTest, QueryStringInHandshake) {
  23720. Server svr;
  23721. std::mutex mtx;
  23722. std::string received_target;
  23723. std::string received_token;
  23724. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23725. {
  23726. std::lock_guard<std::mutex> lock(mtx);
  23727. received_target = req.target;
  23728. if (req.has_param("token")) {
  23729. received_token = req.get_param_value("token");
  23730. }
  23731. }
  23732. std::string msg;
  23733. while (ws.read(msg)) {
  23734. ws.send(msg);
  23735. }
  23736. });
  23737. auto port = svr.bind_to_any_port("localhost");
  23738. std::thread t([&]() { svr.listen_after_bind(); });
  23739. svr.wait_until_ready();
  23740. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23741. "/ws?token=ABC&session=123");
  23742. ASSERT_TRUE(client.connect());
  23743. // Round-trip ensures the handler has run and captured the request.
  23744. ASSERT_TRUE(client.send("hello"));
  23745. std::string msg;
  23746. ASSERT_TRUE(client.read(msg));
  23747. EXPECT_EQ("hello", msg);
  23748. client.close();
  23749. {
  23750. std::lock_guard<std::mutex> lock(mtx);
  23751. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23752. EXPECT_EQ("ABC", received_token);
  23753. }
  23754. svr.stop();
  23755. t.join();
  23756. }
  23757. // Run a handshake against a throwaway server and hand the request the server
  23758. // received back to the caller, so tests can assert on the headers the client
  23759. // actually put on the wire.
  23760. static void capture_websocket_handshake_request(
  23761. const Headers &client_headers,
  23762. std::function<void(const Request &, int port)> verify) {
  23763. Server svr;
  23764. std::mutex mtx;
  23765. Request received;
  23766. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23767. {
  23768. std::lock_guard<std::mutex> lock(mtx);
  23769. received = req;
  23770. }
  23771. std::string msg;
  23772. while (ws.read(msg)) {
  23773. ws.send(msg);
  23774. }
  23775. });
  23776. auto port = svr.bind_to_any_port("localhost");
  23777. std::thread t([&]() { svr.listen_after_bind(); });
  23778. auto se = detail::scope_exit([&] {
  23779. svr.stop();
  23780. t.join();
  23781. });
  23782. svr.wait_until_ready();
  23783. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23784. client_headers);
  23785. ASSERT_TRUE(client.connect());
  23786. ASSERT_TRUE(client.send("hello"));
  23787. std::string msg;
  23788. ASSERT_TRUE(client.read(msg));
  23789. client.close();
  23790. {
  23791. std::lock_guard<std::mutex> lock(mtx);
  23792. verify(received, port);
  23793. }
  23794. }
  23795. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23796. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23797. // Non-default port must be present in the Host header. Default ports
  23798. // (80/443) are omitted; that logic is covered by
  23799. // MakeHostAndPortStringTest.
  23800. EXPECT_EQ("localhost:" + std::to_string(port),
  23801. req.get_header_value("Host"));
  23802. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23803. req.get_header_value("User-Agent"));
  23804. EXPECT_FALSE(req.has_header("Accept"));
  23805. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23806. EXPECT_FALSE(req.has_header("Content-Length"));
  23807. });
  23808. }
  23809. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23810. capture_websocket_handshake_request(
  23811. {{"Host", "example.com"},
  23812. {"User-Agent", "custom-agent"},
  23813. {"X-Custom", "value"}},
  23814. [](const Request &req, int) {
  23815. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23816. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23817. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23818. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23819. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23820. });
  23821. }
  23822. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23823. capture_websocket_handshake_request(
  23824. {{"Upgrade", "bogus"},
  23825. {"Connection", "close"},
  23826. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23827. {"Sec-WebSocket-Version", "8"}},
  23828. [](const Request &req, int) {
  23829. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23830. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23831. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23832. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23833. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23834. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23835. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23836. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23837. req.get_header_value("Sec-WebSocket-Key"));
  23838. });
  23839. }
  23840. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23841. // A header the client refuses to send must abort the handshake before any
  23842. // part of it reaches the wire; a lone request line would otherwise sit in
  23843. // the peer's buffer as a truncated request.
  23844. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23845. ASSERT_NE(INVALID_SOCKET, srv);
  23846. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23847. sockaddr_in addr{};
  23848. addr.sin_family = AF_INET;
  23849. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23850. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23851. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23852. ASSERT_EQ(0, ::listen(srv, 1));
  23853. sockaddr_in bound{};
  23854. socklen_t bound_len = sizeof(bound);
  23855. ASSERT_EQ(
  23856. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23857. auto port = ntohs(bound.sin_port);
  23858. ssize_t received = -1;
  23859. std::thread t([&] {
  23860. // Bound every blocking call so a regression fails the test with a bad
  23861. // value instead of hanging the suite.
  23862. fd_set rfds;
  23863. FD_ZERO(&rfds);
  23864. FD_SET(srv, &rfds);
  23865. timeval tv{5, 0};
  23866. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23867. 0) {
  23868. return;
  23869. }
  23870. sockaddr_in cli_addr{};
  23871. socklen_t cli_len = sizeof(cli_addr);
  23872. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23873. if (cli == INVALID_SOCKET) { return; }
  23874. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23875. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23876. char buf[4096];
  23877. received = ::recv(cli, buf, sizeof(buf), 0);
  23878. });
  23879. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23880. // connect() has already shut the socket down by the time it returns false,
  23881. // so the peer sees EOF without waiting for the client to be destroyed.
  23882. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23883. {{"X-Bad", "a\r\nInjected: 1"}});
  23884. EXPECT_FALSE(client.connect());
  23885. t.join();
  23886. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23887. EXPECT_EQ(0, received);
  23888. }
  23889. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23890. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23891. // contains "upgrade" as a substring is a different token and must not
  23892. // start a WebSocket handshake.
  23893. auto make_request = [](const std::vector<std::string> &connection_values) {
  23894. Request req;
  23895. req.method = "GET";
  23896. req.headers.emplace("Upgrade", "websocket");
  23897. for (const auto &value : connection_values) {
  23898. req.headers.emplace("Connection", value);
  23899. }
  23900. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23901. req.headers.emplace("Sec-WebSocket-Version", "13");
  23902. return req;
  23903. };
  23904. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23905. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23906. EXPECT_TRUE(
  23907. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23908. EXPECT_TRUE(
  23909. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23910. EXPECT_TRUE(
  23911. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23912. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23913. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23914. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23915. EXPECT_FALSE(
  23916. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23917. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23918. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23919. }
  23920. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23921. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23922. // asks recipients to match each protocol-name case-insensitively, and RFC
  23923. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23924. // client naming websocket alongside another protocol, or on a second field
  23925. // line, is offering websocket; a value that merely contains "websocket" as a
  23926. // substring is a different protocol name and is not.
  23927. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23928. Request req;
  23929. req.method = "GET";
  23930. for (const auto &value : upgrade_values) {
  23931. req.headers.emplace("Upgrade", value);
  23932. }
  23933. req.headers.emplace("Connection", "Upgrade");
  23934. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23935. req.headers.emplace("Sec-WebSocket-Version", "13");
  23936. return req;
  23937. };
  23938. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23939. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23940. EXPECT_TRUE(
  23941. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23942. EXPECT_TRUE(
  23943. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23944. EXPECT_TRUE(
  23945. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23946. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23947. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23948. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23949. EXPECT_FALSE(
  23950. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23951. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23952. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23953. }
  23954. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23955. Server svr;
  23956. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23957. auto port = svr.bind_to_any_port("localhost");
  23958. std::thread t([&]() { svr.listen_after_bind(); });
  23959. auto se = detail::scope_exit([&] {
  23960. svr.stop();
  23961. t.join();
  23962. });
  23963. svr.wait_until_ready();
  23964. Headers headers = {{"Upgrade", "websocket"},
  23965. {"Connection", "notupgrade"},
  23966. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23967. {"Sec-WebSocket-Version", "13"}};
  23968. Client cli("localhost", port);
  23969. auto res = cli.Get("/ws", headers);
  23970. // The route exists only as a WebSocket route, so a request that fails the
  23971. // handshake check falls through to ordinary routing.
  23972. ASSERT_TRUE(res);
  23973. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23974. }
  23975. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23976. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23977. // Connection value is the only thing left for the client to reject.
  23978. Server svr;
  23979. svr.Get("/ws", [](const Request &req, Response &res) {
  23980. res.status = StatusCode::SwitchingProtocol_101;
  23981. res.set_header("Upgrade", "websocket");
  23982. res.set_header("Connection", "notupgrade");
  23983. res.set_header("Sec-WebSocket-Accept",
  23984. detail::websocket_accept_key(
  23985. req.get_header_value("Sec-WebSocket-Key")));
  23986. });
  23987. auto port = svr.bind_to_any_port("localhost");
  23988. std::thread t([&]() { svr.listen_after_bind(); });
  23989. auto se = detail::scope_exit([&] {
  23990. svr.stop();
  23991. t.join();
  23992. });
  23993. svr.wait_until_ready();
  23994. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23995. auto res = client.connect();
  23996. EXPECT_FALSE(res);
  23997. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23998. EXPECT_FALSE(client.is_open());
  23999. }
  24000. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24001. Server svr;
  24002. svr.Get("/ws", [](const Request &req, Response &res) {
  24003. res.status = StatusCode::SwitchingProtocol_101;
  24004. res.set_header("Upgrade", "websocket");
  24005. res.set_header("Connection", "Upgrade");
  24006. res.set_header("Sec-WebSocket-Accept",
  24007. detail::websocket_accept_key(
  24008. req.get_header_value("Sec-WebSocket-Key")));
  24009. res.set_header("Sec-WebSocket-Protocol", "admin");
  24010. });
  24011. auto port = svr.bind_to_any_port("localhost");
  24012. std::thread t([&]() { svr.listen_after_bind(); });
  24013. auto se = detail::scope_exit([&] {
  24014. svr.stop();
  24015. t.join();
  24016. });
  24017. svr.wait_until_ready();
  24018. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24019. // Server selects a subprotocol the client never offered
  24020. {
  24021. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24022. ws::WebSocketClient client(url, headers);
  24023. auto res = client.connect();
  24024. EXPECT_FALSE(res);
  24025. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24026. EXPECT_FALSE(client.is_open());
  24027. EXPECT_TRUE(client.subprotocol().empty());
  24028. }
  24029. // Client offered none but the server named one anyway
  24030. {
  24031. ws::WebSocketClient client(url);
  24032. auto res = client.connect();
  24033. EXPECT_FALSE(res);
  24034. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24035. EXPECT_FALSE(client.is_open());
  24036. EXPECT_TRUE(client.subprotocol().empty());
  24037. }
  24038. }
  24039. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24040. // The socket path doubles as the URL host, so it must not contain '/'.
  24041. const char *shard = getenv("GTEST_SHARD_INDEX");
  24042. const std::string sock_path =
  24043. shard ? std::string("httplib-ws-") + shard + ".sock"
  24044. : std::string("httplib-ws.sock");
  24045. std::remove(sock_path.c_str());
  24046. Server svr;
  24047. std::mutex mtx;
  24048. std::string received_host;
  24049. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24050. {
  24051. std::lock_guard<std::mutex> lock(mtx);
  24052. received_host = req.get_header_value("Host");
  24053. }
  24054. std::string msg;
  24055. while (ws.read(msg)) {
  24056. ws.send(msg);
  24057. }
  24058. });
  24059. svr.set_address_family(AF_UNIX);
  24060. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24061. auto se = detail::scope_exit([&] {
  24062. svr.stop();
  24063. t.join();
  24064. std::remove(sock_path.c_str());
  24065. });
  24066. svr.wait_until_ready();
  24067. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24068. client.set_address_family(AF_UNIX);
  24069. ASSERT_TRUE(client.connect());
  24070. ASSERT_TRUE(client.send("hello"));
  24071. std::string msg;
  24072. ASSERT_TRUE(client.read(msg));
  24073. client.close();
  24074. {
  24075. std::lock_guard<std::mutex> lock(mtx);
  24076. // There is no host:port for a Unix socket, so the same "localhost"
  24077. // placeholder the HTTP client uses is expected.
  24078. EXPECT_EQ("localhost", received_host);
  24079. }
  24080. }
  24081. // Two threads must never parse WebSocket frames from the same stream.
  24082. // close() used to read the peer's Close reply with its own frame read, so it
  24083. // raced a reader thread that was in the middle of a payload: the payload loop
  24084. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24085. // so bytes taken by close() were replaced with bytes from further along the
  24086. // stream. The message kept its length and silently changed content.
  24087. //
  24088. // The raw peer below sends a frame header plus part of the payload, waits for
  24089. // the handler to call close(), and only then sends the rest. Whichever thread
  24090. // would win the race for those bytes, the message must arrive intact, because
  24091. // close() must not touch the stream while read() owns it.
  24092. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24093. #ifndef _WIN32
  24094. signal(SIGPIPE, SIG_IGN);
  24095. #endif
  24096. const size_t payload_len = 120; // fits the 7-bit length field
  24097. const size_t prefix_len = 8;
  24098. const int attempts = 8;
  24099. std::string expected(payload_len, '\0');
  24100. for (size_t i = 0; i < payload_len; i++) {
  24101. expected[i] = static_cast<char>('a' + i % 26);
  24102. }
  24103. std::atomic<bool> peer_stalled{false};
  24104. std::atomic<bool> handler_done{false};
  24105. std::mutex received_mutex;
  24106. std::vector<std::string> received;
  24107. // Bound every wait, so a regression fails the test instead of hanging the
  24108. // suite.
  24109. auto wait_for = [](const std::atomic<bool> &flag) {
  24110. for (int i = 0; i < 500 && !flag; i++) {
  24111. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24112. }
  24113. };
  24114. Server svr;
  24115. svr.set_websocket_ping_interval(0);
  24116. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24117. std::thread reader([&]() {
  24118. std::string msg;
  24119. while (ws.read(msg)) {
  24120. std::lock_guard<std::mutex> guard(received_mutex);
  24121. received.push_back(msg);
  24122. }
  24123. });
  24124. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24125. // inside read_websocket_frame() when close() runs.
  24126. wait_for(peer_stalled);
  24127. ws.close();
  24128. reader.join();
  24129. handler_done = true;
  24130. });
  24131. auto port = svr.bind_to_any_port("127.0.0.1");
  24132. std::thread t([&]() { svr.listen_after_bind(); });
  24133. auto se = detail::scope_exit([&] {
  24134. svr.stop();
  24135. t.join();
  24136. });
  24137. svr.wait_until_ready();
  24138. auto send_bytes = [](socket_t s, const std::string &data) {
  24139. #ifdef _WIN32
  24140. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24141. #else
  24142. auto n = ::send(s, data.data(), data.size(), 0);
  24143. #endif
  24144. return n == static_cast<decltype(n)>(data.size());
  24145. };
  24146. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24147. // Every length used here fits the 7-bit length field.
  24148. auto masked_header = [](uint8_t first_byte, size_t len) {
  24149. std::string h;
  24150. h += static_cast<char>(first_byte);
  24151. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24152. h.append(4, '\0'); // mask key
  24153. return h;
  24154. };
  24155. for (int attempt = 0; attempt < attempts; attempt++) {
  24156. peer_stalled = false;
  24157. handler_done = false;
  24158. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24159. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24160. auto se_sock = detail::scope_exit([&] {
  24161. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24162. });
  24163. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24164. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24165. sockaddr_in addr{};
  24166. addr.sin_family = AF_INET;
  24167. addr.sin_port = htons(static_cast<uint16_t>(port));
  24168. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24169. ASSERT_EQ(
  24170. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24171. << "attempt " << attempt;
  24172. ASSERT_TRUE(send_bytes(sock,
  24173. "GET /ws HTTP/1.1\r\n"
  24174. "Host: 127.0.0.1\r\n"
  24175. "Upgrade: websocket\r\n"
  24176. "Connection: Upgrade\r\n"
  24177. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24178. "Sec-WebSocket-Version: 13\r\n"
  24179. "\r\n"))
  24180. << "attempt " << attempt;
  24181. std::string response;
  24182. while (response.find("\r\n\r\n") == std::string::npos) {
  24183. char buf[512];
  24184. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24185. if (n <= 0) { break; }
  24186. response.append(buf, static_cast<size_t>(n));
  24187. }
  24188. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24189. << "attempt " << attempt;
  24190. // Send the header of a Binary message but only the first prefix_len bytes
  24191. // of its payload, leaving the reader thread stalled inside the payload.
  24192. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24193. expected.substr(0, prefix_len)))
  24194. << "attempt " << attempt;
  24195. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24196. peer_stalled = true;
  24197. // Let close() send its Close frame and park in its own read before the
  24198. // rest of the payload arrives, so both threads are waiting for it.
  24199. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24200. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24201. close_frame += static_cast<char>(0x03); // status 1000
  24202. close_frame += static_cast<char>(0xE8);
  24203. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24204. << "attempt " << attempt;
  24205. // Closing the peer releases the reader thread even on the buggy path,
  24206. // where it waits for bytes another thread already consumed.
  24207. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24208. detail::close_socket(sock);
  24209. sock = INVALID_SOCKET;
  24210. wait_for(handler_done);
  24211. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24212. }
  24213. std::lock_guard<std::mutex> guard(received_mutex);
  24214. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24215. << "a message in flight when close() ran was dropped";
  24216. for (size_t i = 0; i < received.size(); i++) {
  24217. EXPECT_EQ(expected, received[i]) << "message " << i;
  24218. }
  24219. }
  24220. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24221. // returning the socket, or INVALID_SOCKET.
  24222. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24223. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24224. if (sock == INVALID_SOCKET) { return sock; }
  24225. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24226. sockaddr_in addr{};
  24227. addr.sin_family = AF_INET;
  24228. addr.sin_port = htons(static_cast<uint16_t>(port));
  24229. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24230. std::string req = "GET " + path +
  24231. " HTTP/1.1\r\n"
  24232. "Host: 127.0.0.1\r\n"
  24233. "Upgrade: websocket\r\n"
  24234. "Connection: Upgrade\r\n"
  24235. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24236. "Sec-WebSocket-Version: 13\r\n"
  24237. "\r\n";
  24238. std::string res;
  24239. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24240. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24241. static_cast<ssize_t>(req.size())) {
  24242. char c;
  24243. while (res.find("\r\n\r\n") == std::string::npos &&
  24244. ::recv(sock, &c, 1, 0) == 1) {
  24245. res += c;
  24246. }
  24247. }
  24248. if (res.find(" 101 ") == std::string::npos) {
  24249. detail::close_socket(sock);
  24250. return INVALID_SOCKET;
  24251. }
  24252. return sock;
  24253. }
  24254. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24255. // The payload must fit the 7-bit length field.
  24256. static std::string masked_frame(uint8_t first_byte,
  24257. const std::string &payload) {
  24258. std::string f;
  24259. f += static_cast<char>(first_byte);
  24260. f += static_cast<char>(0x80 | payload.size());
  24261. f.append(4, '\0');
  24262. return f + payload;
  24263. }
  24264. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24265. std::atomic<bool> done{false};
  24266. std::string received;
  24267. Server svr;
  24268. svr.set_websocket_ping_interval(0);
  24269. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24270. std::string msg;
  24271. if (ws.read(msg) == ws::Binary) { received = msg; }
  24272. done = true;
  24273. });
  24274. auto port = svr.bind_to_any_port("127.0.0.1");
  24275. std::thread t([&]() { svr.listen_after_bind(); });
  24276. auto se = detail::scope_exit([&] {
  24277. svr.stop();
  24278. t.join();
  24279. });
  24280. svr.wait_until_ready();
  24281. auto sock = connect_raw_websocket(port, "/ws");
  24282. ASSERT_NE(INVALID_SOCKET, sock);
  24283. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24284. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24285. masked_frame(0x89, "p") + // FIN + Ping
  24286. masked_frame(0x80, "lo"); // FIN + Continuation
  24287. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24288. for (int i = 0; i < 500 && !done; i++) {
  24289. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24290. }
  24291. ASSERT_TRUE(done);
  24292. EXPECT_EQ("Hello", received);
  24293. // The Ping between the fragments is answered with a Pong.
  24294. char pong[3];
  24295. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24296. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24297. }
  24298. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24299. Server svr;
  24300. svr.set_websocket_ping_interval(-1);
  24301. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24302. std::string msg;
  24303. while (ws.read(msg)) {}
  24304. });
  24305. auto port = svr.bind_to_any_port("127.0.0.1");
  24306. std::thread t([&]() { svr.listen_after_bind(); });
  24307. auto se = detail::scope_exit([&] {
  24308. svr.stop();
  24309. t.join();
  24310. });
  24311. svr.wait_until_ready();
  24312. auto sock = connect_raw_websocket(port, "/ws");
  24313. ASSERT_NE(INVALID_SOCKET, sock);
  24314. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24315. // Nothing comes while the client stays quiet.
  24316. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24317. char c;
  24318. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24319. }
  24320. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24321. // and that has to end a read() already waiting on the peer, on every platform.
  24322. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24323. // The peer sends no pings, and its handler never calls read(), which is
  24324. // where pongs are written.
  24325. std::mutex mutex;
  24326. std::condition_variable cv;
  24327. auto release = false;
  24328. svr.set_websocket_ping_interval(0);
  24329. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24330. std::unique_lock<std::mutex> lock(mutex);
  24331. cv.wait(lock, [&] { return release; });
  24332. });
  24333. auto port = svr.bind_to_any_port(HOST);
  24334. std::thread t([&]() { svr.listen_after_bind(); });
  24335. auto se = detail::scope_exit([&] {
  24336. {
  24337. std::lock_guard<std::mutex> lock(mutex);
  24338. release = true;
  24339. }
  24340. cv.notify_all();
  24341. svr.stop();
  24342. t.join();
  24343. });
  24344. svr.wait_until_ready();
  24345. ws::WebSocketClient client(std::string(scheme) +
  24346. "://localhost:" + std::to_string(port) + "/ws");
  24347. #ifdef CPPHTTPLIB_SSL_ENABLED
  24348. client.enable_server_certificate_verification(false);
  24349. #endif
  24350. // A ping a second, given up on after two go unanswered: about 3s
  24351. client.set_websocket_ping_interval(1);
  24352. client.set_websocket_max_missed_pongs(2);
  24353. // Well past that, so that a read the timeout ends instead stands out
  24354. client.set_read_timeout(10);
  24355. ASSERT_TRUE(client.connect());
  24356. auto start = std::chrono::steady_clock::now();
  24357. std::string msg;
  24358. EXPECT_EQ(ws::Fail, client.read(msg));
  24359. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24360. std::chrono::steady_clock::now() - start)
  24361. .count(),
  24362. 6000);
  24363. EXPECT_FALSE(client.is_open());
  24364. }
  24365. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24366. Server svr;
  24367. check_pong_timeout_ends_read(svr, "ws");
  24368. }
  24369. #ifdef CPPHTTPLIB_SSL_ENABLED
  24370. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24372. ASSERT_TRUE(svr.is_valid());
  24373. check_pong_timeout_ends_read(svr, "wss");
  24374. }
  24375. #endif
  24376. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24377. Server svr;
  24378. svr.set_websocket_ping_interval(0);
  24379. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24380. std::string msg;
  24381. while (ws.read(msg)) {}
  24382. });
  24383. auto port = svr.bind_to_any_port("127.0.0.1");
  24384. std::thread t([&]() { svr.listen_after_bind(); });
  24385. auto se = detail::scope_exit([&] {
  24386. svr.stop();
  24387. t.join();
  24388. });
  24389. svr.wait_until_ready();
  24390. // Each Close payload and the reply it should get: an echo when valid, 1002
  24391. // otherwise.
  24392. std::vector<std::pair<std::string, std::string>> cases = {
  24393. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24394. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24395. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24396. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24397. };
  24398. // Also between the fragments of a message.
  24399. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24400. for (const auto &c : cases) {
  24401. auto sock = connect_raw_websocket(port, "/ws");
  24402. ASSERT_NE(INVALID_SOCKET, sock);
  24403. auto frames = prefix + masked_frame(0x88, c.first);
  24404. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24405. std::string reply;
  24406. char buf[256];
  24407. while (reply.size() < 2 + c.second.size()) {
  24408. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24409. if (n <= 0) { break; }
  24410. reply.append(buf, static_cast<size_t>(n));
  24411. }
  24412. detail::close_socket(sock);
  24413. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24414. c.second,
  24415. reply);
  24416. }
  24417. }
  24418. }
  24419. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24420. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24421. protected:
  24422. void SetUp() override {
  24423. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24424. SERVER_PRIVATE_KEY_FILE);
  24425. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24426. std::string msg;
  24427. ws::ReadResult ret;
  24428. while ((ret = ws.read(msg))) {
  24429. if (ret == ws::Binary) {
  24430. ws.send(msg.data(), msg.size());
  24431. } else {
  24432. ws.send(msg);
  24433. }
  24434. }
  24435. });
  24436. port_ = server_->bind_to_any_port(HOST);
  24437. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24438. server_->wait_until_ready();
  24439. }
  24440. void TearDown() override {
  24441. server_->stop();
  24442. if (server_thread_.joinable()) { server_thread_.join(); }
  24443. }
  24444. std::unique_ptr<SSLServer> server_;
  24445. std::thread server_thread_;
  24446. int port_ = 0;
  24447. };
  24448. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24449. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24450. {
  24451. ws::WebSocketClient client(url);
  24452. client.enable_server_certificate_verification(false);
  24453. auto calls = 0;
  24454. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24455. calls++;
  24456. return false;
  24457. });
  24458. EXPECT_FALSE(client.connect());
  24459. EXPECT_GT(calls, 0);
  24460. }
  24461. {
  24462. ws::WebSocketClient client(url);
  24463. client.enable_server_certificate_verification(false);
  24464. client.set_session_verifier([](tls::session_t) {
  24465. return SSLVerifierResponse::CertificateRejected;
  24466. });
  24467. EXPECT_FALSE(client.connect());
  24468. }
  24469. {
  24470. ws::WebSocketClient client(url);
  24471. client.enable_server_certificate_verification(false);
  24472. client.set_session_verifier([](tls::session_t) {
  24473. return SSLVerifierResponse::CertificateAccepted;
  24474. });
  24475. EXPECT_TRUE(client.connect());
  24476. }
  24477. }
  24478. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24479. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24480. "/ws-echo");
  24481. client.enable_server_certificate_verification(false);
  24482. ASSERT_TRUE(client.connect());
  24483. ASSERT_TRUE(client.is_open());
  24484. ASSERT_TRUE(client.send("Hello WSS"));
  24485. std::string msg;
  24486. EXPECT_EQ(ws::Text, client.read(msg));
  24487. EXPECT_EQ("Hello WSS", msg);
  24488. client.close();
  24489. }
  24490. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24491. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24492. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24493. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24494. // client (without calling close() first) is the only path that runs
  24495. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24496. // bug exactly.
  24497. //
  24498. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24499. // when linked against an instrumented libssl; run under Valgrind to catch it
  24500. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24501. // suite (the freed session otherwise stalls on the close handshake) — this test
  24502. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24503. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24504. {
  24505. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24506. "/ws-echo");
  24507. client.enable_server_certificate_verification(false);
  24508. client.set_read_timeout(2, 0);
  24509. client.set_write_timeout(2, 0);
  24510. ASSERT_TRUE(client.connect());
  24511. ASSERT_TRUE(client.is_open());
  24512. ASSERT_TRUE(client.send("still open"));
  24513. // Intentionally do NOT call client.close(): leaving scope runs
  24514. // shutdown_and_close() with the WebSocket still open, which must send the
  24515. // close frame while the TLS session is still alive.
  24516. }
  24517. }
  24518. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24519. // shutdown_and_close() at the start of connect(), reproducing the same
  24520. // use-after-free within the test body rather than at scope exit. The second
  24521. // connect must succeed and echo, proving the close handshake ran over a live
  24522. // session. See the note above about memory-tool requirements.
  24523. TEST_F(WebSocketSSLIntegrationTest,
  24524. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24525. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24526. "/ws-echo");
  24527. client.enable_server_certificate_verification(false);
  24528. client.set_read_timeout(2, 0);
  24529. client.set_write_timeout(2, 0);
  24530. ASSERT_TRUE(client.connect());
  24531. ASSERT_TRUE(client.is_open());
  24532. ASSERT_TRUE(client.send("still open"));
  24533. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24534. // the still-open connection, which must not touch a freed TLS session.
  24535. ASSERT_TRUE(client.connect());
  24536. ASSERT_TRUE(client.is_open());
  24537. ASSERT_TRUE(client.send("after reconnect"));
  24538. std::string msg;
  24539. EXPECT_EQ(ws::Text, client.read(msg));
  24540. EXPECT_EQ("after reconnect", msg);
  24541. client.close();
  24542. }
  24543. #endif
  24544. #ifdef CPPHTTPLIB_SSL_ENABLED
  24545. class WebSocketSSLCATest : public ::testing::Test {
  24546. protected:
  24547. void SetUp() override {
  24548. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24549. SERVER_PRIVATE_KEY_FILE);
  24550. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24551. std::string msg;
  24552. while (ws.read(msg)) {
  24553. ws.send(msg);
  24554. }
  24555. });
  24556. port_ = server_->bind_to_any_port("127.0.0.1");
  24557. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24558. server_->wait_until_ready();
  24559. }
  24560. void TearDown() override {
  24561. server_->stop();
  24562. if (server_thread_.joinable()) { server_thread_.join(); }
  24563. }
  24564. std::string url() const {
  24565. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24566. }
  24567. std::unique_ptr<SSLServer> server_;
  24568. std::thread server_thread_;
  24569. int port_ = 0;
  24570. };
  24571. // A custom CA loaded as PEM verifies the server with full certificate
  24572. // verification enabled
  24573. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24574. ws::WebSocketClient client(url());
  24575. std::string cert;
  24576. read_file(SERVER_CERT2_FILE, cert);
  24577. client.load_ca_cert_store(cert.c_str(), cert.size());
  24578. ASSERT_TRUE(client.connect());
  24579. ASSERT_TRUE(client.send("hello"));
  24580. std::string msg;
  24581. EXPECT_EQ(ws::Text, client.read(msg));
  24582. EXPECT_EQ("hello", msg);
  24583. client.close();
  24584. }
  24585. // A custom CA that does not cover the server must fail verification (the
  24586. // custom CA is exclusive; system certs are not loaded alongside it)
  24587. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24588. ws::WebSocketClient client(url());
  24589. std::string cert;
  24590. read_file(CLIENT_CA_CERT_FILE, cert);
  24591. client.load_ca_cert_store(cert.c_str(), cert.size());
  24592. auto res = client.connect();
  24593. ASSERT_FALSE(res);
  24594. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24595. EXPECT_EQ(-1, res.status());
  24596. EXPECT_NE(0u, res.ssl_backend_error());
  24597. }
  24598. // The same CA as a file path rather than PEM in memory
  24599. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24600. ws::WebSocketClient client(url());
  24601. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24602. ASSERT_TRUE(client.connect());
  24603. ASSERT_TRUE(client.send("hello"));
  24604. std::string msg;
  24605. EXPECT_EQ(ws::Text, client.read(msg));
  24606. EXPECT_EQ("hello", msg);
  24607. client.close();
  24608. }
  24609. // ...and a CA file that does not cover the server still fails, so it is the
  24610. // path above that decides the outcome
  24611. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24612. ws::WebSocketClient client(url());
  24613. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24614. ASSERT_FALSE(client.connect());
  24615. }
  24616. // Regression test: reconnecting with a native custom CA store used to reuse
  24617. // a store handle the previous TLS context had already freed (use-after-free
  24618. // under the OpenSSL backend). The context now lives as long as the client.
  24619. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24620. ws::WebSocketClient client(url());
  24621. std::string cert;
  24622. read_file(SERVER_CERT2_FILE, cert);
  24623. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24624. ASSERT_TRUE(client.connect());
  24625. client.close();
  24626. ASSERT_TRUE(client.connect());
  24627. ASSERT_TRUE(client.send("again"));
  24628. std::string msg;
  24629. EXPECT_EQ(ws::Text, client.read(msg));
  24630. EXPECT_EQ("again", msg);
  24631. client.close();
  24632. }
  24633. // Regression test: a certificate with a trusted chain but no identity match
  24634. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24635. // verification entirely for IP hosts, so this connection succeeded there.
  24636. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24637. // chain verification while the identity check must still fail.
  24638. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24639. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24640. ASSERT_TRUE(svr.is_valid());
  24641. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24642. std::string msg;
  24643. while (ws.read(msg)) {
  24644. ws.send(msg);
  24645. }
  24646. });
  24647. auto port = svr.bind_to_any_port("127.0.0.1");
  24648. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24649. auto se = detail::scope_exit([&] {
  24650. svr.stop();
  24651. t.join();
  24652. });
  24653. svr.wait_until_ready();
  24654. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24655. "/echo");
  24656. std::string cert;
  24657. read_file(SERVER_CERT_FILE, cert);
  24658. client.load_ca_cert_store(cert.c_str(), cert.size());
  24659. ASSERT_FALSE(client.connect());
  24660. }
  24661. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24662. // SNI, so nothing binds the host name to the TLS session. These bind the
  24663. // server to "localhost" instead, the only shape that exercises the SNI and
  24664. // hostname-verification path with certificate verification left enabled.
  24665. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24666. protected:
  24667. void Start(const char *cert_file) {
  24668. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24669. SERVER_PRIVATE_KEY_FILE);
  24670. ASSERT_TRUE(server_->is_valid());
  24671. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24672. std::string msg;
  24673. while (ws.read(msg)) {
  24674. ws.send(msg);
  24675. }
  24676. });
  24677. port_ = server_->bind_to_any_port("localhost");
  24678. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24679. server_->wait_until_ready();
  24680. }
  24681. void TearDown() override {
  24682. if (server_) { server_->stop(); }
  24683. if (server_thread_.joinable()) { server_thread_.join(); }
  24684. }
  24685. std::string url() const {
  24686. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24687. }
  24688. std::unique_ptr<SSLServer> server_;
  24689. std::thread server_thread_;
  24690. int port_ = 0;
  24691. };
  24692. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24693. // out and the connection is usable
  24694. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24695. Start(SERVER_CERT2_FILE);
  24696. ws::WebSocketClient client(url());
  24697. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24698. ASSERT_TRUE(client.connect());
  24699. ASSERT_TRUE(client.send("hello"));
  24700. std::string msg;
  24701. EXPECT_EQ(ws::Text, client.read(msg));
  24702. EXPECT_EQ("hello", msg);
  24703. client.close();
  24704. }
  24705. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24706. // while the identity check must still reject "localhost"
  24707. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24708. Start(SERVER_CERT_FILE);
  24709. ws::WebSocketClient client(url());
  24710. client.set_ca_cert_path(SERVER_CERT_FILE);
  24711. auto res = client.connect();
  24712. ASSERT_FALSE(res);
  24713. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24714. EXPECT_EQ(-1, res.status());
  24715. }
  24716. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24717. // disabled: the chain is still checked, only the identity check is skipped
  24718. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24719. Start(SERVER_CERT_FILE);
  24720. ws::WebSocketClient client(url());
  24721. client.set_ca_cert_path(SERVER_CERT_FILE);
  24722. client.enable_server_hostname_verification(false);
  24723. ASSERT_TRUE(client.connect());
  24724. ASSERT_TRUE(client.send("hello"));
  24725. std::string msg;
  24726. EXPECT_EQ(ws::Text, client.read(msg));
  24727. EXPECT_EQ("hello", msg);
  24728. client.close();
  24729. }
  24730. // A CA that did not sign the server certificate fails the chain, even though
  24731. // the name would match
  24732. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24733. Start(SERVER_CERT2_FILE);
  24734. ws::WebSocketClient client(url());
  24735. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24736. ASSERT_FALSE(client.connect());
  24737. }
  24738. // With verification disabled, neither the chain nor the name is checked
  24739. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24740. Start(SERVER_CERT_FILE);
  24741. ws::WebSocketClient client(url());
  24742. client.enable_server_certificate_verification(false);
  24743. ASSERT_TRUE(client.connect());
  24744. ASSERT_TRUE(client.send("hello"));
  24745. std::string msg;
  24746. EXPECT_EQ(ws::Text, client.read(msg));
  24747. EXPECT_EQ("hello", msg);
  24748. client.close();
  24749. }
  24750. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24751. protected:
  24752. void SetUp() override {
  24753. server_ = httplib::detail::make_unique<SSLServer>(
  24754. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24755. ASSERT_TRUE(server_->is_valid());
  24756. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24757. std::string msg;
  24758. while (ws.read(msg)) {
  24759. ws.send(msg);
  24760. }
  24761. });
  24762. port_ = server_->bind_to_any_port("localhost");
  24763. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24764. server_->wait_until_ready();
  24765. }
  24766. void TearDown() override {
  24767. server_->stop();
  24768. if (server_thread_.joinable()) { server_thread_.join(); }
  24769. }
  24770. std::string url() const {
  24771. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24772. }
  24773. void ConnectWithClientCert(const std::string &client_cert_file,
  24774. const std::string &client_private_key_file,
  24775. const char *private_key_password) {
  24776. std::string cert_pem, key_pem;
  24777. read_file(client_cert_file, cert_pem);
  24778. read_file(client_private_key_file, key_pem);
  24779. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24780. key_pem.c_str(), key_pem.size(),
  24781. private_key_password};
  24782. ConnectWithPem(pem);
  24783. }
  24784. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24785. ws::WebSocketClient client(url(), pem);
  24786. ASSERT_TRUE(client.is_valid());
  24787. client.enable_server_certificate_verification(false);
  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. std::unique_ptr<SSLServer> server_;
  24796. std::thread server_thread_;
  24797. int port_ = 0;
  24798. };
  24799. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24800. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24801. }
  24802. // Control for the tests above: the fixture's server really does require a
  24803. // client certificate, so it is the PEM the constructor installed that decides
  24804. // the outcome.
  24805. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24806. ws::WebSocketClient client(url());
  24807. ASSERT_TRUE(client.is_valid());
  24808. client.enable_server_certificate_verification(false);
  24809. EXPECT_FALSE(client.connect());
  24810. }
  24811. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24812. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24813. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24814. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24815. }
  24816. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24817. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24818. std::string cert_pem, key_pem;
  24819. read_file(CLIENT_CERT_FILE, cert_pem);
  24820. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24821. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24822. std::vector<char> key(key_pem.begin(), key_pem.end());
  24823. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24824. key.size(), nullptr};
  24825. ConnectWithPem(pem);
  24826. }
  24827. #endif
  24828. #if !defined(_WIN32)
  24829. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24830. auto secret_dir = std::string("./symlink_test_secret");
  24831. auto served_dir = std::string("./symlink_test_served");
  24832. auto secret_file = secret_dir + "/secret.txt";
  24833. auto symlink_path = served_dir + "/escape";
  24834. // Setup: create directories and files
  24835. mkdir(secret_dir.c_str(), 0755);
  24836. mkdir(served_dir.c_str(), 0755);
  24837. {
  24838. std::ofstream ofs(secret_file);
  24839. ofs << "SECRET_DATA";
  24840. }
  24841. // Create symlink using absolute path so it resolves correctly
  24842. #ifdef PATH_MAX
  24843. char abs_secret[PATH_MAX];
  24844. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24845. #else
  24846. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24847. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24848. ASSERT_NE(nullptr, abs_secret);
  24849. #endif
  24850. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24851. auto se = detail::scope_exit([&] {
  24852. unlink(symlink_path.c_str());
  24853. unlink(secret_file.c_str());
  24854. rmdir(served_dir.c_str());
  24855. rmdir(secret_dir.c_str());
  24856. });
  24857. Server svr;
  24858. svr.set_mount_point("/", served_dir);
  24859. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24860. auto se2 = detail::scope_exit([&] {
  24861. svr.stop();
  24862. listen_thread.join();
  24863. });
  24864. svr.wait_until_ready();
  24865. Client cli("localhost", PORT);
  24866. // Symlink pointing outside base dir should be blocked
  24867. auto res = cli.Get("/escape/secret.txt");
  24868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24869. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24870. }
  24871. #endif
  24872. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24873. // "GET /smuggled" request), reads the first response, and only then sends the
  24874. // embedded request as the body. Returns how many times /smuggled ran.
  24875. //
  24876. // The body is sent AFTER receiving the first response (as in the original
  24877. // PoC) so that the stream_line_reader cannot buffer it together with the
  24878. // headers of the first request.
  24879. static int count_smuggled_requests(const std::string &outer_head,
  24880. std::string &first_response) {
  24881. Server svr;
  24882. svr.set_mount_point("/", "./www");
  24883. std::atomic<int> smuggled_count(0);
  24884. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24885. smuggled_count++;
  24886. res.set_content("oops", "text/plain");
  24887. });
  24888. svr.Post("/post", [&](const Request &req, Response &res) {
  24889. res.set_content(req.body, "text/plain");
  24890. });
  24891. auto port = svr.bind_to_any_port("localhost");
  24892. thread t = thread([&] { svr.listen_after_bind(); });
  24893. auto se = detail::scope_exit([&] {
  24894. svr.stop();
  24895. t.join();
  24896. });
  24897. svr.wait_until_ready();
  24898. auto error = Error::Success;
  24899. auto sock = detail::create_client_socket(
  24900. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24901. /*connection_timeout_sec=*/2, 0,
  24902. /*read_timeout_sec=*/2, 0,
  24903. /*write_timeout_sec=*/2, 0, std::string(), error);
  24904. EXPECT_NE(INVALID_SOCKET, sock);
  24905. if (sock == INVALID_SOCKET) { return -1; }
  24906. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24907. // The "smuggled" request will be sent as the body of the outer request
  24908. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24909. "Host: localhost\r\n"
  24910. "Connection: close\r\n"
  24911. "\r\n";
  24912. auto head = outer_head;
  24913. auto len = std::to_string(smuggled.size());
  24914. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24915. pos = head.find("{len}", pos + len.size())) {
  24916. head.replace(pos, 5, len);
  24917. }
  24918. // Step 1: Send only the outer request headers (no body yet)
  24919. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  24920. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24921. // Step 2: Read the first response
  24922. char buf[4096];
  24923. for (;;) {
  24924. auto n = recv(sock, buf, sizeof(buf), 0);
  24925. if (n <= 0) break;
  24926. first_response.append(buf, static_cast<size_t>(n));
  24927. // Stop once we have a complete response (headers + body)
  24928. auto hdr_end = first_response.find("\r\n\r\n");
  24929. if (hdr_end != std::string::npos) {
  24930. // Check for Content-Length to know when the body is complete
  24931. auto cl_pos = first_response.find("Content-Length:");
  24932. if (cl_pos != std::string::npos) {
  24933. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24934. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24935. auto cl = std::stoul(
  24936. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24937. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24938. } else {
  24939. break; // No Content-Length, assume headers-only response
  24940. }
  24941. }
  24942. }
  24943. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24944. // vulnerable server the keep-alive loop reads this as a second request. The
  24945. // server may already have closed the connection, so the result is ignored.
  24946. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  24947. // Half-close so that a server which drained the body sees EOF and closes,
  24948. // instead of the read below waiting for the read timeout.
  24949. #ifdef _WIN32
  24950. ::shutdown(sock, SD_SEND);
  24951. #else
  24952. ::shutdown(sock, SHUT_WR);
  24953. #endif
  24954. // Step 4: Read until the server closes the connection
  24955. for (;;) {
  24956. auto n = recv(sock, buf, sizeof(buf), 0);
  24957. if (n <= 0) break;
  24958. }
  24959. return smuggled_count.load();
  24960. }
  24961. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24962. // A GET request with Content-Length to a static file handler must have its
  24963. // body drained before the keep-alive connection is reused. Otherwise the
  24964. // unread body bytes are interpreted as the next HTTP request.
  24965. std::string first_response;
  24966. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24967. "Host: localhost\r\n"
  24968. "Content-Length: {len}\r\n"
  24969. "\r\n",
  24970. first_response));
  24971. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24972. }
  24973. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24974. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24975. // be answered with 400 and the connection closed. Treating it as "no body"
  24976. // leaves the body to be parsed as the next request.
  24977. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24978. const char *targets[] = {
  24979. "GET /file", // handler that never reads the body
  24980. "GET /not-found", // no handler matches (404)
  24981. "POST /post", // handler that reads the body
  24982. };
  24983. for (auto target : targets) {
  24984. for (auto value : values) {
  24985. std::string first_response;
  24986. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24987. " HTTP/1.1\r\n"
  24988. "Host: localhost\r\n"
  24989. "Content-Length: " +
  24990. value + "\r\n\r\n",
  24991. first_response))
  24992. << target << " with Content-Length: " << value;
  24993. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24994. << target << " with Content-Length: " << value;
  24995. }
  24996. }
  24997. }
  24998. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24999. // A 400 for an unparseable request line leaves the rest of the message
  25000. // unread, so the connection must be closed rather than reused.
  25001. std::string first_response;
  25002. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25003. "Host: localhost\r\n"
  25004. "Content-Length: {len}\r\n"
  25005. "\r\n",
  25006. first_response));
  25007. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25008. }
  25009. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25010. // Same as above for a header block that fails to parse.
  25011. std::string first_response;
  25012. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25013. "Host: localhost\r\n"
  25014. "Bad Header\r\n"
  25015. "Content-Length: {len}\r\n"
  25016. "\r\n",
  25017. first_response));
  25018. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25019. }
  25020. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25021. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25022. // server must not read another request on that connection, even when the
  25023. // request had no body to drain.
  25024. std::string first_response;
  25025. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25026. "Host: localhost\r\n"
  25027. "\r\n",
  25028. first_response));
  25029. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25030. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25031. }
  25032. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25033. // A content reader that stops early leaves the stream inside the body.
  25034. // Draining the whole Content-Length from there, or reading the body again,
  25035. // reads into the next request, and whatever follows is parsed as a request
  25036. // of its own.
  25037. Server svr;
  25038. std::atomic<int> smuggled_count(0);
  25039. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25040. svr.Post("/upload", [](const Request &req, Response &res,
  25041. const ContentReader &content_reader) {
  25042. // Stop at the last chunk, so the whole body has been read however it
  25043. // arrives.
  25044. auto length = req.get_header_value_u64("Content-Length");
  25045. size_t total = 0;
  25046. auto consumed = content_reader([&](const char *, size_t n) {
  25047. total += n;
  25048. return total < length;
  25049. });
  25050. EXPECT_FALSE(consumed);
  25051. if (req.has_param("retry")) {
  25052. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25053. }
  25054. // Replace the 400 the aborted read set, which would close the connection.
  25055. res.set_redirect("/done");
  25056. });
  25057. auto port = svr.bind_to_any_port(HOST);
  25058. thread t = thread([&] { svr.listen_after_bind(); });
  25059. auto se = detail::scope_exit([&] {
  25060. svr.stop();
  25061. t.join();
  25062. });
  25063. svr.wait_until_ready();
  25064. // A front end sees the second request as a POST whose body is the GET. The
  25065. // first body is as long as the POST's headers, so draining it again reads
  25066. // exactly those and leaves the GET to be parsed next.
  25067. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25068. "Host: localhost\r\n"
  25069. "\r\n";
  25070. std::string second_head = "POST /post HTTP/1.1\r\n"
  25071. "Host: localhost\r\n"
  25072. "Content-Length: " +
  25073. std::to_string(inner.size()) +
  25074. "\r\n"
  25075. "\r\n";
  25076. for (auto target : {"/upload", "/upload?retry"}) {
  25077. smuggled_count = 0;
  25078. std::string request = "POST " + std::string(target) +
  25079. " HTTP/1.1\r\n"
  25080. "Host: localhost\r\n"
  25081. "Content-Length: " +
  25082. std::to_string(second_head.size()) +
  25083. "\r\n"
  25084. "\r\n" +
  25085. std::string(second_head.size(), 'A') + second_head +
  25086. inner;
  25087. std::string response;
  25088. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25089. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25090. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25091. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25092. EXPECT_EQ(0, smuggled_count.load()) << target;
  25093. }
  25094. }
  25095. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25096. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25097. // must be rejected with 400 Bad Request.
  25098. Server svr;
  25099. svr.Post("/test", [&](const Request &, Response &res) {
  25100. res.set_content("ok", "text/plain");
  25101. });
  25102. thread t = thread([&] { svr.listen(HOST, PORT); });
  25103. auto se = detail::scope_exit([&] {
  25104. svr.stop();
  25105. t.join();
  25106. ASSERT_FALSE(svr.is_running());
  25107. });
  25108. svr.wait_until_ready();
  25109. // Exact "chunked"
  25110. {
  25111. auto req = "POST /test HTTP/1.1\r\n"
  25112. "Host: localhost\r\n"
  25113. "Content-Length: 5\r\n"
  25114. "Transfer-Encoding: chunked\r\n"
  25115. "Connection: close\r\n"
  25116. "\r\n"
  25117. "hello";
  25118. std::string response;
  25119. ASSERT_TRUE(send_request(1, req, &response));
  25120. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25121. response.substr(0, response.find("\r\n")));
  25122. }
  25123. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25124. {
  25125. auto req = "POST /test HTTP/1.1\r\n"
  25126. "Host: localhost\r\n"
  25127. "Content-Length: 5\r\n"
  25128. "Transfer-Encoding: gzip, chunked\r\n"
  25129. "Connection: close\r\n"
  25130. "\r\n"
  25131. "hello";
  25132. std::string response;
  25133. ASSERT_TRUE(send_request(1, req, &response));
  25134. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25135. response.substr(0, response.find("\r\n")));
  25136. }
  25137. }
  25138. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25139. Server svr;
  25140. svr.Post("/test", [&](const Request &, Response &res) {
  25141. res.set_content("ok", "text/plain");
  25142. });
  25143. thread t = thread([&] { svr.listen(HOST, PORT); });
  25144. auto se = detail::scope_exit([&] {
  25145. svr.stop();
  25146. t.join();
  25147. ASSERT_FALSE(svr.is_running());
  25148. });
  25149. svr.wait_until_ready();
  25150. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25151. // length cannot be determined, so the server must answer 400 and close
  25152. // rather than treat the request as bodyless and leave the body in the
  25153. // socket for the next request to pick up.
  25154. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25155. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25156. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25157. std::string response;
  25158. ASSERT_TRUE(send_request(1, req, &response));
  25159. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25160. response.substr(0, response.find("\r\n")))
  25161. << transfer_encoding;
  25162. }
  25163. // RFC 9110 5.3: the codings may also be split across several
  25164. // Transfer-Encoding lines, which combine in the order they were received.
  25165. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25166. // just like the single-line "chunked, gzip" above.
  25167. {
  25168. auto req = "POST /test HTTP/1.1\r\n"
  25169. "Host: localhost\r\n"
  25170. "Transfer-Encoding: chunked\r\n"
  25171. "Transfer-Encoding: gzip\r\n"
  25172. "\r\n"
  25173. "0\r\n\r\n";
  25174. std::string response;
  25175. ASSERT_TRUE(send_request(1, req, &response));
  25176. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25177. response.substr(0, response.find("\r\n")));
  25178. }
  25179. // A sequence ending in chunked stays valid.
  25180. auto req = "POST /test HTTP/1.1\r\n"
  25181. "Host: localhost\r\n"
  25182. "Transfer-Encoding: gzip, chunked\r\n"
  25183. "Connection: close\r\n"
  25184. "\r\n"
  25185. "0\r\n\r\n";
  25186. std::string response;
  25187. ASSERT_TRUE(send_request(1, req, &response));
  25188. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  25189. // ...including when it is spread over several lines.
  25190. auto split_req = "POST /test HTTP/1.1\r\n"
  25191. "Host: localhost\r\n"
  25192. "Transfer-Encoding: gzip\r\n"
  25193. "Transfer-Encoding: chunked\r\n"
  25194. "Connection: close\r\n"
  25195. "\r\n"
  25196. "0\r\n\r\n";
  25197. std::string split_response;
  25198. ASSERT_TRUE(send_request(1, split_req, &split_response));
  25199. EXPECT_EQ("HTTP/1.1 200 OK",
  25200. split_response.substr(0, split_response.find("\r\n")));
  25201. }
  25202. // Regression for issue #2450: a DELETE without Content-Length on a
  25203. // keep-alive connection must not let the post-response drain consume the
  25204. // next request's bytes.
  25205. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25206. Server svr;
  25207. std::atomic<int> delete_count(0);
  25208. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25209. delete_count++;
  25210. res.status = StatusCode::NoContent_204;
  25211. });
  25212. auto port = svr.bind_to_any_port(HOST);
  25213. thread t = thread([&] { svr.listen_after_bind(); });
  25214. auto se = detail::scope_exit([&] {
  25215. svr.stop();
  25216. t.join();
  25217. });
  25218. svr.wait_until_ready();
  25219. auto error = Error::Success;
  25220. auto sock = detail::create_client_socket(
  25221. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25222. /*connection_timeout_sec=*/2, 0,
  25223. /*read_timeout_sec=*/2, 0,
  25224. /*write_timeout_sec=*/2, 0, std::string(), error);
  25225. ASSERT_NE(INVALID_SOCKET, sock);
  25226. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25227. auto send_request_and_read_response = [&](const std::string &req,
  25228. std::string &out) -> bool {
  25229. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25230. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25231. char buf[4096];
  25232. for (;;) {
  25233. auto n = recv(sock, buf, sizeof(buf), 0);
  25234. if (n <= 0) { return !out.empty(); }
  25235. out.append(buf, static_cast<size_t>(n));
  25236. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25237. }
  25238. };
  25239. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25240. "Host: localhost\r\n"
  25241. "\r\n";
  25242. std::string resp1;
  25243. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25244. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25245. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25246. "Host: localhost\r\n"
  25247. "Connection: close\r\n"
  25248. "\r\n";
  25249. std::string resp2;
  25250. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25251. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25252. EXPECT_EQ(2, delete_count.load());
  25253. }
  25254. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25255. Server svr;
  25256. svr.Post("/ingest", [&](const Request &, Response &res,
  25257. const ContentReader &content_reader) {
  25258. auto consumed = content_reader([](const char *, size_t) { return false; });
  25259. EXPECT_FALSE(consumed);
  25260. res.status = StatusCode::Conflict_409;
  25261. res.set_header("Connection", "close");
  25262. });
  25263. auto port = svr.bind_to_any_port(HOST);
  25264. thread t = thread([&] { svr.listen_after_bind(); });
  25265. auto se = detail::scope_exit([&] {
  25266. svr.stop();
  25267. t.join();
  25268. });
  25269. svr.wait_until_ready();
  25270. auto error = Error::Success;
  25271. auto sock = detail::create_client_socket(
  25272. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25273. /*connection_timeout_sec=*/2, 0,
  25274. /*read_timeout_sec=*/1, 0,
  25275. /*write_timeout_sec=*/2, 0, std::string(), error);
  25276. ASSERT_NE(INVALID_SOCKET, sock);
  25277. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25278. std::string request = "POST /ingest HTTP/1.1\r\n"
  25279. "Host: localhost\r\n"
  25280. "Transfer-Encoding: chunked\r\n"
  25281. "\r\n"
  25282. "4\r\n"
  25283. "data\r\n";
  25284. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25285. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25286. std::string response;
  25287. ssize_t received = 0;
  25288. do {
  25289. char buf[4096];
  25290. received = recv(sock, buf, sizeof(buf), 0);
  25291. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25292. } while (received > 0);
  25293. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25294. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25295. EXPECT_EQ(0, received);
  25296. }
  25297. namespace no_proxy_test {
  25298. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25299. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25300. // calling listen().
  25301. class ScopedServer {
  25302. public:
  25303. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25304. ~ScopedServer() {
  25305. svr_.stop();
  25306. if (th_.joinable()) { th_.join(); }
  25307. }
  25308. Server &svr() { return svr_; }
  25309. int port() const { return port_; }
  25310. void listen() {
  25311. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25312. svr_.wait_until_ready();
  25313. }
  25314. private:
  25315. Server svr_;
  25316. std::thread th_;
  25317. int port_ = 0;
  25318. };
  25319. class ProxyAndTargetServers {
  25320. public:
  25321. ProxyAndTargetServers() {
  25322. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25323. proxy_hits_++;
  25324. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25325. res.set_content("via-proxy", "text/plain");
  25326. });
  25327. target_.Get(".*", [this](const Request &req, Response &res) {
  25328. target_hits_++;
  25329. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25330. res.set_content("direct", "text/plain");
  25331. });
  25332. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25333. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25334. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25335. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25336. proxy_mock_.wait_until_ready();
  25337. target_.wait_until_ready();
  25338. }
  25339. ~ProxyAndTargetServers() {
  25340. proxy_mock_.stop();
  25341. target_.stop();
  25342. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25343. if (target_thread_.joinable()) { target_thread_.join(); }
  25344. }
  25345. Server &proxy_mock() { return proxy_mock_; }
  25346. Server &target() { return target_; }
  25347. int proxy_port() const { return proxy_port_; }
  25348. int target_port() const { return target_port_; }
  25349. int proxy_hits() const { return proxy_hits_.load(); }
  25350. int target_hits() const { return target_hits_.load(); }
  25351. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25352. void reset_counters() {
  25353. proxy_hits_ = 0;
  25354. target_hits_ = 0;
  25355. last_had_proxy_authz_ = false;
  25356. }
  25357. private:
  25358. Server proxy_mock_;
  25359. Server target_;
  25360. std::thread proxy_thread_;
  25361. std::thread target_thread_;
  25362. int proxy_port_ = 0;
  25363. int target_port_ = 0;
  25364. std::atomic<int> proxy_hits_{0};
  25365. std::atomic<int> target_hits_{0};
  25366. std::atomic<bool> last_had_proxy_authz_{false};
  25367. };
  25368. inline std::unique_ptr<Client> make_client(const std::string &host,
  25369. ProxyAndTargetServers &s) {
  25370. auto cli = detail::make_unique<Client>(host, s.target_port());
  25371. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25372. cli->set_proxy("127.0.0.1", s.proxy_port());
  25373. return cli;
  25374. }
  25375. } // namespace no_proxy_test
  25376. using no_proxy_test::make_client;
  25377. using no_proxy_test::ProxyAndTargetServers;
  25378. // A stream request carries the credentials a buffered request does
  25379. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25380. no_proxy_test::ScopedServer origin;
  25381. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25382. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25383. });
  25384. origin.listen();
  25385. Client cli("127.0.0.1", origin.port());
  25386. cli.set_basic_auth("user", "pass");
  25387. auto handle = cli.open_stream("GET", "/x");
  25388. ASSERT_TRUE(handle.is_valid());
  25389. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25390. Client bearer("127.0.0.1", origin.port());
  25391. bearer.set_bearer_token_auth("tok");
  25392. auto handle2 = bearer.open_stream("GET", "/x");
  25393. ASSERT_TRUE(handle2.is_valid());
  25394. EXPECT_EQ("Bearer tok", read_all(handle2));
  25395. }
  25396. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25397. // takes its own credentials, as for a buffered request
  25398. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25399. std::string target, authz, proxy_authz;
  25400. no_proxy_test::ScopedServer proxy;
  25401. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25402. target = req.target;
  25403. authz = req.get_header_value("Authorization");
  25404. proxy_authz = req.get_header_value("Proxy-Authorization");
  25405. res.set_content("ok", "text/plain");
  25406. });
  25407. proxy.listen();
  25408. Client cli("origin.example", 8080);
  25409. cli.set_proxy("127.0.0.1", proxy.port());
  25410. cli.set_proxy_basic_auth("puser", "ppass");
  25411. cli.set_basic_auth("user", "pass");
  25412. auto handle = cli.open_stream("GET", "/x");
  25413. ASSERT_TRUE(handle.is_valid());
  25414. EXPECT_EQ("ok", read_all(handle));
  25415. EXPECT_EQ("http://origin.example:8080/x", target);
  25416. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25417. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25418. }
  25419. TEST(NoProxyTest, ExactHostnameBypasses) {
  25420. ProxyAndTargetServers s;
  25421. auto cli = make_client("example.com", s);
  25422. cli->set_no_proxy({"example.com"});
  25423. auto res = cli->Get("/");
  25424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25425. EXPECT_EQ(0, s.proxy_hits());
  25426. EXPECT_EQ(1, s.target_hits());
  25427. }
  25428. TEST(NoProxyTest, SubdomainBypasses) {
  25429. ProxyAndTargetServers s;
  25430. auto cli = make_client("foo.example.com", s);
  25431. cli->set_no_proxy({"example.com"});
  25432. auto res = cli->Get("/");
  25433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25434. EXPECT_EQ(0, s.proxy_hits());
  25435. EXPECT_EQ(1, s.target_hits());
  25436. }
  25437. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25438. // Regression guard: "evilexample.com" must not be considered a subdomain
  25439. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25440. // check would let traffic bypass the proxy and leak credentials direct
  25441. // to the attacker host.
  25442. ProxyAndTargetServers s;
  25443. auto cli = make_client("evilexample.com", s);
  25444. cli->set_no_proxy({"example.com"});
  25445. auto res = cli->Get("/");
  25446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25447. EXPECT_GE(s.proxy_hits(), 1);
  25448. EXPECT_EQ(0, s.target_hits());
  25449. }
  25450. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25451. ProxyAndTargetServers s;
  25452. auto cli = make_client("example.com.evil.com", s);
  25453. cli->set_no_proxy({"example.com"});
  25454. auto res = cli->Get("/");
  25455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25456. EXPECT_GE(s.proxy_hits(), 1);
  25457. EXPECT_EQ(0, s.target_hits());
  25458. }
  25459. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25460. ProxyAndTargetServers s;
  25461. auto cli = make_client("example.com", s);
  25462. cli->set_no_proxy({".example.com"});
  25463. auto res = cli->Get("/");
  25464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25465. EXPECT_EQ(0, s.proxy_hits());
  25466. EXPECT_EQ(1, s.target_hits());
  25467. }
  25468. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25469. ProxyAndTargetServers s;
  25470. auto cli = make_client("Example.COM", s);
  25471. cli->set_no_proxy({"EXAMPLE.com"});
  25472. auto res = cli->Get("/");
  25473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25474. EXPECT_EQ(0, s.proxy_hits());
  25475. EXPECT_EQ(1, s.target_hits());
  25476. }
  25477. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25478. ProxyAndTargetServers s;
  25479. auto cli = make_client("example.com.", s);
  25480. cli->set_no_proxy({"example.com"});
  25481. auto res = cli->Get("/");
  25482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25483. EXPECT_EQ(0, s.proxy_hits());
  25484. EXPECT_EQ(1, s.target_hits());
  25485. }
  25486. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25487. // Trailing dots must be normalized on BOTH sides — host and entry.
  25488. // An implementation that only strips the host-side trailing dot would
  25489. // fail to match host "example.com" against entry "example.com." because
  25490. // a literal substring search would compare 11 chars against 12.
  25491. ProxyAndTargetServers s;
  25492. auto cli = make_client("example.com", s);
  25493. cli->set_no_proxy({"example.com."});
  25494. auto res = cli->Get("/");
  25495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25496. EXPECT_EQ(0, s.proxy_hits());
  25497. EXPECT_EQ(1, s.target_hits());
  25498. }
  25499. TEST(NoProxyTest, WildcardBypassesEverything) {
  25500. ProxyAndTargetServers s;
  25501. auto cli = make_client("anything.invalid.test", s);
  25502. cli->set_no_proxy({"*"});
  25503. auto res = cli->Get("/");
  25504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25505. EXPECT_EQ(0, s.proxy_hits());
  25506. EXPECT_EQ(1, s.target_hits());
  25507. }
  25508. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25509. ProxyAndTargetServers s;
  25510. Client cli("127.0.0.1", s.target_port());
  25511. cli.set_proxy("127.0.0.1", s.proxy_port());
  25512. cli.set_no_proxy({"127.0.0.1"});
  25513. auto res = cli.Get("/");
  25514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25515. EXPECT_EQ(0, s.proxy_hits());
  25516. EXPECT_EQ(1, s.target_hits());
  25517. }
  25518. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25519. ProxyAndTargetServers s;
  25520. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25521. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25522. cli.set_proxy("127.0.0.1", s.proxy_port());
  25523. cli.set_no_proxy({"::1"});
  25524. auto res = cli.Get("/");
  25525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25526. EXPECT_EQ(0, s.proxy_hits());
  25527. EXPECT_EQ(1, s.target_hits());
  25528. }
  25529. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25530. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25531. // must still be recognized as IPv6 for CIDR matching. Implementations
  25532. // that detect IPv6 only when the host begins with '[' would parse the
  25533. // host as a hostname and miss the match.
  25534. ProxyAndTargetServers s;
  25535. Client cli("fe80::1", s.target_port());
  25536. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25537. cli.set_proxy("127.0.0.1", s.proxy_port());
  25538. cli.set_no_proxy({"fe80::/10"});
  25539. auto res = cli.Get("/");
  25540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25541. EXPECT_EQ(0, s.proxy_hits());
  25542. EXPECT_EQ(1, s.target_hits());
  25543. }
  25544. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25545. ProxyAndTargetServers s;
  25546. Client cli("::1", s.target_port());
  25547. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25548. cli.set_proxy("127.0.0.1", s.proxy_port());
  25549. cli.set_no_proxy({"[::1]"});
  25550. auto res = cli.Get("/");
  25551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25552. EXPECT_EQ(0, s.proxy_hits());
  25553. EXPECT_EQ(1, s.target_hits());
  25554. }
  25555. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25556. ProxyAndTargetServers s;
  25557. Client cli("fe80::1", s.target_port());
  25558. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25559. cli.set_proxy("127.0.0.1", s.proxy_port());
  25560. cli.set_no_proxy({"[fe80::]/10"});
  25561. auto res = cli.Get("/");
  25562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25563. EXPECT_EQ(0, s.proxy_hits());
  25564. EXPECT_EQ(1, s.target_hits());
  25565. }
  25566. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25567. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25568. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25569. // tricks via address-family conversion.
  25570. ProxyAndTargetServers s;
  25571. Client cli("::ffff:127.0.0.1", s.target_port());
  25572. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25573. cli.set_proxy("127.0.0.1", s.proxy_port());
  25574. cli.set_no_proxy({"127.0.0.1"});
  25575. auto res = cli.Get("/");
  25576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25577. EXPECT_GE(s.proxy_hits(), 1);
  25578. EXPECT_EQ(0, s.target_hits());
  25579. }
  25580. TEST(NoProxyTest, IPv4CidrMatch) {
  25581. ProxyAndTargetServers s;
  25582. Client cli("127.0.0.1", s.target_port());
  25583. cli.set_proxy("127.0.0.1", s.proxy_port());
  25584. cli.set_no_proxy({"127.0.0.0/8"});
  25585. auto res = cli.Get("/");
  25586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25587. EXPECT_EQ(0, s.proxy_hits());
  25588. EXPECT_EQ(1, s.target_hits());
  25589. }
  25590. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25591. ProxyAndTargetServers s;
  25592. Client cli("127.0.0.1", s.target_port());
  25593. cli.set_proxy("127.0.0.1", s.proxy_port());
  25594. cli.set_no_proxy({"10.0.0.0/8"});
  25595. auto res = cli.Get("/");
  25596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25597. EXPECT_GE(s.proxy_hits(), 1);
  25598. EXPECT_EQ(0, s.target_hits());
  25599. }
  25600. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25601. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25602. // IPv4 target matches.
  25603. ProxyAndTargetServers s;
  25604. Client cli("127.0.0.1", s.target_port());
  25605. cli.set_proxy("127.0.0.1", s.proxy_port());
  25606. cli.set_no_proxy({"0.0.0.0/0"});
  25607. auto res = cli.Get("/");
  25608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25609. EXPECT_EQ(0, s.proxy_hits());
  25610. EXPECT_EQ(1, s.target_hits());
  25611. }
  25612. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25613. ProxyAndTargetServers s;
  25614. Client cli("127.0.0.1", s.target_port());
  25615. cli.set_proxy("127.0.0.1", s.proxy_port());
  25616. cli.set_no_proxy({"127.0.0.1"});
  25617. auto res = cli.Get("/");
  25618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25619. EXPECT_EQ(0, s.proxy_hits());
  25620. EXPECT_EQ(1, s.target_hits());
  25621. }
  25622. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25623. ProxyAndTargetServers s;
  25624. Client cli("127.0.0.1", s.target_port());
  25625. cli.set_proxy("127.0.0.1", s.proxy_port());
  25626. cli.set_no_proxy({"127.0.0.0/33"});
  25627. auto res = cli.Get("/");
  25628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25629. EXPECT_GE(s.proxy_hits(), 1);
  25630. EXPECT_EQ(0, s.target_hits());
  25631. }
  25632. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25633. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25634. ProxyAndTargetServers s;
  25635. Client cli("127.0.0.1", s.target_port());
  25636. cli.set_proxy("127.0.0.1", s.proxy_port());
  25637. cli.set_no_proxy({"127.0.0.1/"});
  25638. auto res = cli.Get("/");
  25639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25640. EXPECT_GE(s.proxy_hits(), 1);
  25641. EXPECT_EQ(0, s.target_hits());
  25642. }
  25643. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25644. ProxyAndTargetServers s;
  25645. auto cli = make_client("internal.corp", s);
  25646. cli->set_proxy_basic_auth("u", "p");
  25647. cli->set_no_proxy({"internal.corp"});
  25648. auto res = cli->Get("/");
  25649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25650. EXPECT_EQ(1, s.target_hits());
  25651. EXPECT_EQ(0, s.proxy_hits());
  25652. EXPECT_FALSE(s.last_had_proxy_authz())
  25653. << "Proxy-Authorization must not be sent direct to the target";
  25654. }
  25655. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25656. ProxyAndTargetServers s;
  25657. auto cli = make_client("public.example", s);
  25658. cli->set_proxy_basic_auth("u", "p");
  25659. cli->set_no_proxy({"internal.corp"}); // does not match
  25660. auto res = cli->Get("/");
  25661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25662. EXPECT_GE(s.proxy_hits(), 1);
  25663. EXPECT_TRUE(s.last_had_proxy_authz());
  25664. }
  25665. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25666. std::atomic<int> hits{0};
  25667. std::atomic<int> hits_with_authz{0};
  25668. no_proxy_test::ScopedServer proxy_mock;
  25669. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25670. hits++;
  25671. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25672. if (req.target.find("/redir") != std::string::npos) {
  25673. res.set_redirect("http://other.example/landed");
  25674. } else {
  25675. res.set_content("via-proxy", "text/plain");
  25676. }
  25677. });
  25678. proxy_mock.listen();
  25679. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25680. hits = 0;
  25681. hits_with_authz = 0;
  25682. Client cli("public.example", 80);
  25683. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25684. cli.set_proxy_basic_auth(c.first, c.second);
  25685. cli.set_follow_location(true);
  25686. // The redirect to another host goes through the proxy as well
  25687. auto res = cli.Get("/redir");
  25688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25689. EXPECT_EQ(2, hits.load());
  25690. EXPECT_EQ(2, hits_with_authz.load());
  25691. }
  25692. }
  25693. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25694. ProxyAndTargetServers s;
  25695. auto cli = make_client("anything.test", s);
  25696. auto res = cli->Get("/");
  25697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25698. EXPECT_GE(s.proxy_hits(), 1);
  25699. EXPECT_EQ(0, s.target_hits());
  25700. }
  25701. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25702. ProxyAndTargetServers s;
  25703. auto cli = make_client("example.com", s);
  25704. cli->set_no_proxy({"example.com:8080"});
  25705. auto res = cli->Get("/");
  25706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25707. EXPECT_GE(s.proxy_hits(), 1);
  25708. EXPECT_EQ(0, s.target_hits());
  25709. }
  25710. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25711. ProxyAndTargetServers s;
  25712. auto cli = make_client("anything.test", s);
  25713. cli->set_no_proxy({"", " ", "\t"});
  25714. auto res = cli->Get("/");
  25715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25716. EXPECT_GE(s.proxy_hits(), 1);
  25717. EXPECT_EQ(0, s.target_hits());
  25718. }
  25719. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25720. // An entry with leading/trailing whitespace must still match — env-style
  25721. // values are commonly pasted with stray spaces and an implementation
  25722. // that feeds the raw token directly to inet_pton would fail to match
  25723. // valid CIDRs because of the spaces.
  25724. ProxyAndTargetServers s;
  25725. Client cli("127.0.0.1", s.target_port());
  25726. cli.set_proxy("127.0.0.1", s.proxy_port());
  25727. cli.set_no_proxy({" 127.0.0.0/8 "});
  25728. auto res = cli.Get("/");
  25729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25730. EXPECT_EQ(0, s.proxy_hits());
  25731. EXPECT_EQ(1, s.target_hits());
  25732. }
  25733. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25734. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25735. // go direct and must NOT carry Proxy-Authorization.
  25736. std::atomic<int> proxy_hits{0};
  25737. std::atomic<int> target_hits{0};
  25738. std::atomic<bool> target_saw_authz{false};
  25739. no_proxy_test::ScopedServer proxy_mock, target;
  25740. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25741. proxy_hits++;
  25742. res.status = 302;
  25743. res.set_header("Location", "http://127.0.0.1:" +
  25744. std::to_string(target.port()) + "/landed");
  25745. });
  25746. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25747. target_hits++;
  25748. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25749. res.set_content("direct", "text/plain");
  25750. });
  25751. proxy_mock.listen();
  25752. target.listen();
  25753. Client cli("public.example", target.port());
  25754. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25755. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25756. cli.set_proxy_basic_auth("u", "p");
  25757. cli.set_no_proxy({"127.0.0.1"});
  25758. cli.set_follow_location(true);
  25759. auto res = cli.Get("/redir");
  25760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25761. EXPECT_GE(proxy_hits.load(), 1);
  25762. EXPECT_GE(target_hits.load(), 1);
  25763. EXPECT_FALSE(target_saw_authz.load());
  25764. }
  25765. #ifdef CPPHTTPLIB_SSL_ENABLED
  25766. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25767. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25768. // proxy creds would be sent to the (possibly hostile) origin.
  25769. std::atomic<int> target_hits{0};
  25770. std::atomic<bool> target_saw_proxy_authz{false};
  25771. no_proxy_test::ScopedServer target;
  25772. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25773. target_hits++;
  25774. if (req.has_header("Proxy-Authorization")) {
  25775. target_saw_proxy_authz = true;
  25776. }
  25777. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25778. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25779. "nonce=\"abc\", algorithm=MD5");
  25780. });
  25781. target.listen();
  25782. // The proxy address is set to the target's port: the bypass MUST kick in;
  25783. // if it doesn't, the test still routes "via proxy" to the same server and
  25784. // the Proxy-Authorization assertion below catches the leak.
  25785. Client cli("evil.example", target.port());
  25786. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25787. cli.set_proxy("127.0.0.1", target.port());
  25788. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25789. cli.set_no_proxy({"evil.example"});
  25790. auto res = cli.Get("/x");
  25791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25792. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25793. EXPECT_EQ(1, target_hits.load());
  25794. EXPECT_FALSE(target_saw_proxy_authz.load());
  25795. }
  25796. #endif
  25797. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25798. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25799. std::atomic<int> proxy_hits{0};
  25800. std::atomic<int> bypass_hits{0};
  25801. std::atomic<bool> proxy_saw_c_url{false};
  25802. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25803. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25804. proxy_hits++;
  25805. if (req.path.find("/start") != std::string::npos) {
  25806. res.status = 302;
  25807. res.set_header("Location", "http://127.0.0.1:" +
  25808. std::to_string(bypass_server.port()) +
  25809. "/middle");
  25810. return;
  25811. }
  25812. if (req.path.find("/end") != std::string::npos) {
  25813. proxy_saw_c_url = true;
  25814. res.set_content("c-via-proxy", "text/plain");
  25815. return;
  25816. }
  25817. res.set_content("unexpected", "text/plain");
  25818. });
  25819. // public.example's "advertised" port is arbitrary (the request never lands
  25820. // there — it goes through the proxy), but use a dynamic value to stay
  25821. // friendly with sharded parallel runs.
  25822. int public_port = bypass_server.port();
  25823. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25824. bypass_hits++;
  25825. res.status = 302;
  25826. res.set_header("Location", "http://public.example:" +
  25827. std::to_string(public_port) + "/end");
  25828. });
  25829. proxy_mock.listen();
  25830. bypass_server.listen();
  25831. Client cli("public.example", public_port);
  25832. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25833. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25834. cli.set_no_proxy({"127.0.0.1"});
  25835. cli.set_follow_location(true);
  25836. auto res = cli.Get("/start");
  25837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25838. EXPECT_EQ(StatusCode::OK_200, res->status);
  25839. EXPECT_EQ("c-via-proxy", res->body);
  25840. EXPECT_GE(proxy_hits.load(), 2);
  25841. EXPECT_GE(bypass_hits.load(), 1);
  25842. EXPECT_TRUE(proxy_saw_c_url.load());
  25843. }
  25844. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25845. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25846. // request reconnects to the correct endpoint.
  25847. std::atomic<int> proxy_hits{0};
  25848. std::atomic<int> target_hits{0};
  25849. no_proxy_test::ScopedServer proxy_mock, target;
  25850. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25851. proxy_hits++;
  25852. res.set_content("via-proxy", "text/plain");
  25853. });
  25854. target.svr().Get(".*", [&](const Request &, Response &res) {
  25855. target_hits++;
  25856. res.set_content("direct", "text/plain");
  25857. });
  25858. proxy_mock.listen();
  25859. target.listen();
  25860. Client cli("public.example", target.port());
  25861. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25862. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25863. cli.set_keep_alive(true);
  25864. auto res1 = cli.Get("/a");
  25865. ASSERT_TRUE(res1);
  25866. EXPECT_EQ("via-proxy", res1->body);
  25867. EXPECT_EQ(1, proxy_hits.load());
  25868. EXPECT_EQ(0, target_hits.load());
  25869. cli.set_no_proxy({"public.example"});
  25870. auto res2 = cli.Get("/b");
  25871. ASSERT_TRUE(res2);
  25872. EXPECT_EQ("direct", res2->body);
  25873. EXPECT_EQ(1, proxy_hits.load());
  25874. EXPECT_EQ(1, target_hits.load());
  25875. }
  25876. // Forward declarations (see the base64_encode note).
  25877. namespace httplib {
  25878. namespace detail {
  25879. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  25880. int shutdown_socket(socket_t sock) noexcept;
  25881. } // namespace detail
  25882. } // namespace httplib
  25883. namespace proxy_tunnel_test {
  25884. const char *const kTunnelEstablished =
  25885. "HTTP/1.1 200 Connection established\r\n\r\n";
  25886. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  25887. using ConnectReply = std::function<std::string(const std::string &head)>;
  25888. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  25889. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  25890. class ScopedConnectProxy {
  25891. public:
  25892. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  25893. : forward_port_(forward_port), reply_(std::move(reply)) {
  25894. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25895. if (listen_sock_ == INVALID_SOCKET) { return; }
  25896. auto a = loopback(0);
  25897. auto addr = reinterpret_cast<sockaddr *>(&a);
  25898. socklen_t alen = sizeof(a);
  25899. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  25900. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  25901. ::listen(listen_sock_, 4) != 0) {
  25902. return;
  25903. }
  25904. port_ = ntohs(a.sin_port);
  25905. th_ = std::thread([this] { run(); });
  25906. }
  25907. ~ScopedConnectProxy() {
  25908. if (th_.joinable()) {
  25909. stop_ = true;
  25910. auto wake = connect_to(port_);
  25911. th_.join();
  25912. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  25913. }
  25914. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  25915. }
  25916. int port() const { return port_; }
  25917. int connect_hits() const { return connect_hits_.load(); }
  25918. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25919. std::string connect_request() const {
  25920. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25921. return connect_request_;
  25922. }
  25923. private:
  25924. static sockaddr_in loopback(int port) {
  25925. sockaddr_in a{};
  25926. a.sin_family = AF_INET;
  25927. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25928. a.sin_port = htons(static_cast<unsigned short>(port));
  25929. return a;
  25930. }
  25931. static socket_t connect_to(int port) {
  25932. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25933. if (sock == INVALID_SOCKET) { return sock; }
  25934. auto a = loopback(port);
  25935. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25936. detail::close_socket(sock);
  25937. return INVALID_SOCKET;
  25938. }
  25939. return sock;
  25940. }
  25941. static bool send_all(socket_t sock, const char *data, size_t size) {
  25942. while (size > 0) {
  25943. auto n = detail::send_socket(sock, data, size, 0);
  25944. if (n <= 0) { return false; }
  25945. data += n;
  25946. size -= static_cast<size_t>(n);
  25947. }
  25948. return true;
  25949. }
  25950. void run() {
  25951. for (;;) {
  25952. auto client = ::accept(listen_sock_, nullptr, nullptr);
  25953. if (stop_) {
  25954. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  25955. return;
  25956. }
  25957. if (client == INVALID_SOCKET) { continue; }
  25958. serve(client);
  25959. detail::close_socket(client);
  25960. }
  25961. }
  25962. void serve(socket_t client) {
  25963. std::string head;
  25964. char buf[2048];
  25965. while (head.find("\r\n\r\n") == std::string::npos) {
  25966. if (detail::select_read(client, 5, 0) <= 0) { return; }
  25967. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  25968. if (n <= 0) { return; }
  25969. head.append(buf, static_cast<size_t>(n));
  25970. }
  25971. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  25972. connect_hits_++;
  25973. {
  25974. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25975. connect_request_ = head;
  25976. }
  25977. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  25978. if (!send_all(client, res.data(), res.size()) ||
  25979. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  25980. return;
  25981. }
  25982. auto origin = connect_to(forward_port_);
  25983. if (origin == INVALID_SOCKET) { return; }
  25984. // When either side stops, shut both down so the other pump returns too.
  25985. auto pump = [&](socket_t from, socket_t to) {
  25986. char b[8192];
  25987. for (;;) {
  25988. auto n = detail::read_socket(from, b, sizeof(b), 0);
  25989. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  25990. }
  25991. detail::shutdown_socket(client);
  25992. detail::shutdown_socket(origin);
  25993. };
  25994. std::thread up([&] { pump(client, origin); });
  25995. pump(origin, client);
  25996. up.join();
  25997. detail::close_socket(origin);
  25998. }
  25999. int forward_port_;
  26000. ConnectReply reply_;
  26001. socket_t listen_sock_ = INVALID_SOCKET;
  26002. int port_ = 0;
  26003. std::thread th_;
  26004. std::atomic<bool> stop_{false};
  26005. std::atomic<int> connect_hits_{0};
  26006. mutable std::mutex connect_request_mutex_;
  26007. std::string connect_request_;
  26008. };
  26009. } // namespace proxy_tunnel_test
  26010. #ifdef CPPHTTPLIB_SSL_ENABLED
  26011. namespace proxy_tunnel_test {
  26012. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26013. class ScopedSSLServer {
  26014. public:
  26015. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26016. port_ = svr_.bind_to_any_port("127.0.0.1");
  26017. }
  26018. ~ScopedSSLServer() {
  26019. svr_.stop();
  26020. if (th_.joinable()) { th_.join(); }
  26021. }
  26022. SSLServer &svr() { return svr_; }
  26023. int port() const { return port_; }
  26024. void listen() {
  26025. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26026. svr_.wait_until_ready();
  26027. }
  26028. private:
  26029. SSLServer svr_;
  26030. std::thread th_;
  26031. int port_ = 0;
  26032. };
  26033. // Sends one request through the CONNECT proxy to the TLS origin with a
  26034. // credential configured for each hop, and checks that each credential reaches
  26035. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26036. // origin's (every header in origin_headers) on the tunnelled request.
  26037. void CredentialsStayWithTheirHop(
  26038. const std::function<void(SSLClient &)> &set_credentials,
  26039. const std::string &scheme,
  26040. const std::vector<std::string> &origin_headers = {"Authorization"},
  26041. bool stream = false) {
  26042. std::atomic<int> origin_hits{0};
  26043. std::atomic<bool> origin_saw_proxy_authz{false};
  26044. std::atomic<bool> origin_saw_headers{false};
  26045. ScopedSSLServer origin;
  26046. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26047. origin_hits++;
  26048. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26049. origin_saw_headers =
  26050. std::all_of(origin_headers.begin(), origin_headers.end(),
  26051. [&](const std::string &h) { return req.has_header(h); });
  26052. res.set_content("ok", "text/plain");
  26053. });
  26054. origin.listen();
  26055. ScopedConnectProxy proxy(origin.port());
  26056. ASSERT_NE(0, proxy.port());
  26057. // Pinned to 127.0.0.1 for the same reason as the test below.
  26058. SSLClient cli("127.0.0.1", origin.port());
  26059. cli.enable_server_certificate_verification(false);
  26060. cli.set_proxy("127.0.0.1", proxy.port());
  26061. set_credentials(cli);
  26062. if (stream) {
  26063. auto handle = cli.open_stream("GET", "/x");
  26064. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26065. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26066. } else {
  26067. auto res = cli.Get("/x");
  26068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26069. EXPECT_EQ(StatusCode::OK_200, res->status);
  26070. }
  26071. EXPECT_EQ(1, origin_hits.load());
  26072. EXPECT_EQ(1, proxy.connect_hits());
  26073. EXPECT_TRUE(origin_saw_headers.load());
  26074. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26075. << "Proxy-Authorization must not be sent inside the tunnel";
  26076. auto connect_req = proxy.connect_request();
  26077. EXPECT_NE(std::string::npos,
  26078. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26079. for (const auto &h : origin_headers) {
  26080. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26081. << h << " must not be sent to the proxy on CONNECT";
  26082. }
  26083. }
  26084. } // namespace proxy_tunnel_test
  26085. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26086. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26087. [](SSLClient &cli) {
  26088. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26089. cli.set_basic_auth("origin-user", "origin-pass");
  26090. },
  26091. "Basic");
  26092. }
  26093. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26094. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26095. [](SSLClient &cli) {
  26096. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26097. cli.set_basic_auth("origin-user", "origin-pass");
  26098. },
  26099. "Basic", {"Authorization"}, true);
  26100. }
  26101. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26102. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26103. [](SSLClient &cli) {
  26104. cli.set_proxy_bearer_token_auth("proxy-token");
  26105. cli.set_bearer_token_auth("origin-token");
  26106. },
  26107. "Bearer");
  26108. }
  26109. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26110. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26111. [](SSLClient &cli) {
  26112. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26113. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26114. {"Cookie", "sid=origin-session"},
  26115. {"X-Api-Key", "origin-key"}});
  26116. },
  26117. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26118. }
  26119. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26120. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26121. // retry; otherwise proxy creds would be sent to the origin.
  26122. std::atomic<int> origin_hits{0};
  26123. std::atomic<bool> origin_saw_proxy_authz{false};
  26124. proxy_tunnel_test::ScopedSSLServer origin;
  26125. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26126. origin_hits++;
  26127. if (req.has_header("Proxy-Authorization")) {
  26128. origin_saw_proxy_authz = true;
  26129. }
  26130. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26131. res.set_header("Proxy-Authenticate",
  26132. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26133. "algorithm=MD5");
  26134. });
  26135. origin.listen();
  26136. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26137. ASSERT_NE(0, proxy.port());
  26138. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26139. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26140. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26141. // and answer with its own status, making this test flaky.
  26142. SSLClient cli("127.0.0.1", origin.port());
  26143. cli.enable_server_certificate_verification(false);
  26144. cli.set_proxy("127.0.0.1", proxy.port());
  26145. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26146. auto res = cli.Get("/x");
  26147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26148. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26149. EXPECT_EQ(1, origin_hits.load());
  26150. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26151. EXPECT_EQ(1, proxy.connect_hits());
  26152. }
  26153. #endif
  26154. namespace proxy_tunnel_test {
  26155. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26156. // anything else gets a 407 with `challenge`.
  26157. ConnectReply require_proxy_auth(const std::string &expected,
  26158. const std::string &challenge) {
  26159. return [=](const std::string &head) -> std::string {
  26160. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26161. std::string::npos) {
  26162. return kTunnelEstablished;
  26163. }
  26164. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26165. "Proxy-Authenticate: " +
  26166. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26167. };
  26168. }
  26169. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26170. // request, then echoes.
  26171. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26172. ws.send(
  26173. "authorization:" + req.get_header_value("Authorization") +
  26174. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26175. std::string msg;
  26176. while (ws.read(msg)) {
  26177. ws.send(msg);
  26178. }
  26179. }
  26180. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26181. class ScopedWebSocketOrigin {
  26182. public:
  26183. ScopedWebSocketOrigin() {
  26184. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26185. server_.listen();
  26186. }
  26187. int port() const { return server_.port(); }
  26188. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26189. std::string url() const {
  26190. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26191. }
  26192. private:
  26193. no_proxy_test::ScopedServer server_;
  26194. };
  26195. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26196. // passed as a constructor header, and checks that each reaches only its hop.
  26197. void WebSocketCredentialsStayWithTheirHop(
  26198. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26199. const std::string &proxy_authz, const std::string &origin_authz) {
  26200. ScopedWebSocketOrigin origin;
  26201. ScopedConnectProxy proxy(
  26202. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26203. ASSERT_NE(0, proxy.port());
  26204. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26205. client.set_proxy("127.0.0.1", proxy.port());
  26206. set_proxy_credentials(client);
  26207. auto res = client.connect();
  26208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26209. std::string msg;
  26210. ASSERT_TRUE(client.read(msg));
  26211. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26212. client.close();
  26213. EXPECT_EQ(1, proxy.connect_hits());
  26214. EXPECT_EQ(std::string::npos,
  26215. proxy.connect_request().find("\r\nAuthorization: "))
  26216. << "origin credentials must not be sent to the proxy";
  26217. }
  26218. } // namespace proxy_tunnel_test
  26219. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26220. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26221. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26222. ASSERT_NE(0, proxy.port());
  26223. ws::WebSocketClient client(origin.url());
  26224. client.set_proxy("127.0.0.1", proxy.port());
  26225. auto res = client.connect();
  26226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26227. std::string msg;
  26228. ASSERT_TRUE(client.read(msg));
  26229. ASSERT_TRUE(client.send("hello"));
  26230. ASSERT_TRUE(client.read(msg));
  26231. EXPECT_EQ("hello", msg);
  26232. client.close();
  26233. EXPECT_EQ(1, proxy.connect_hits());
  26234. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26235. auto connect_req = proxy.connect_request();
  26236. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26237. EXPECT_NE(std::string::npos,
  26238. connect_req.find("\r\nHost: " + target + "\r\n"));
  26239. }
  26240. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26241. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26242. [](ws::WebSocketClient &cli) {
  26243. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26244. },
  26245. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26246. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26247. }
  26248. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26249. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26250. [](ws::WebSocketClient &cli) {
  26251. cli.set_proxy_bearer_token_auth("proxy-token");
  26252. },
  26253. "Bearer proxy-token", "Bearer origin-token");
  26254. }
  26255. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26256. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26257. proxy_tunnel_test::ScopedConnectProxy proxy(
  26258. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26259. "Basic " + detail::base64_encode("proxy-user:"),
  26260. "Basic realm=\"proxy\""));
  26261. ASSERT_NE(0, proxy.port());
  26262. ws::WebSocketClient client(origin.url());
  26263. client.set_proxy("127.0.0.1", proxy.port());
  26264. client.set_proxy_basic_auth("proxy-user", "");
  26265. auto res = client.connect();
  26266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26267. client.close();
  26268. EXPECT_EQ(1, proxy.connect_hits());
  26269. }
  26270. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26271. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26272. proxy_tunnel_test::ScopedConnectProxy proxy(
  26273. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26274. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26275. ASSERT_NE(0, proxy.port());
  26276. ws::WebSocketClient client(origin.url());
  26277. client.set_proxy("127.0.0.1", proxy.port());
  26278. auto res = client.connect();
  26279. EXPECT_FALSE(res);
  26280. EXPECT_EQ(Error::ProxyConnection, res.error());
  26281. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26282. EXPECT_EQ("Basic realm=\"proxy\"",
  26283. res.get_header_value("Proxy-Authenticate"));
  26284. EXPECT_FALSE(client.is_open());
  26285. }
  26286. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26287. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26288. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26289. ASSERT_NE(0, proxy.port());
  26290. ws::WebSocketClient client(origin.url());
  26291. client.set_proxy("127.0.0.1", proxy.port());
  26292. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26293. client.set_no_proxy({"127.0.0.1"});
  26294. auto res = client.connect();
  26295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26296. std::string msg;
  26297. ASSERT_TRUE(client.read(msg));
  26298. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26299. << "proxy credentials must not reach a bypassed origin";
  26300. client.close();
  26301. EXPECT_EQ(0, proxy.connect_hits());
  26302. }
  26303. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26304. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26305. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26306. ASSERT_NE(0, proxy.port());
  26307. ws::WebSocketClient client(origin.url());
  26308. client.set_proxy("127.0.0.1", proxy.port());
  26309. ASSERT_TRUE(client.connect());
  26310. ASSERT_TRUE(client.connect());
  26311. client.close();
  26312. EXPECT_EQ(2, proxy.connect_hits());
  26313. }
  26314. #ifdef CPPHTTPLIB_SSL_ENABLED
  26315. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26316. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26317. proxy_tunnel_test::ScopedConnectProxy proxy(
  26318. origin.port(), [](const std::string &head) -> std::string {
  26319. if (head.find(
  26320. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26321. std::string::npos) {
  26322. return proxy_tunnel_test::kTunnelEstablished;
  26323. }
  26324. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26325. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26326. "nonce=\"abc\", algorithm=MD5\r\n"
  26327. "Content-Length: 0\r\n\r\n";
  26328. });
  26329. ASSERT_NE(0, proxy.port());
  26330. ws::WebSocketClient client(origin.url());
  26331. client.set_proxy("127.0.0.1", proxy.port());
  26332. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26333. auto res = client.connect();
  26334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26335. std::string msg;
  26336. ASSERT_TRUE(client.read(msg));
  26337. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26338. client.close();
  26339. EXPECT_EQ(2, proxy.connect_hits());
  26340. }
  26341. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26342. proxy_tunnel_test::ScopedSSLServer origin;
  26343. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26344. origin.listen();
  26345. proxy_tunnel_test::ScopedConnectProxy proxy(
  26346. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26347. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26348. ASSERT_NE(0, proxy.port());
  26349. ws::WebSocketClient client(
  26350. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26351. client.enable_server_certificate_verification(false);
  26352. client.set_proxy("127.0.0.1", proxy.port());
  26353. client.set_proxy_bearer_token_auth("proxy-token");
  26354. auto res = client.connect();
  26355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26356. std::string msg;
  26357. ASSERT_TRUE(client.read(msg));
  26358. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26359. << "Proxy-Authorization must not be sent inside the tunnel";
  26360. client.close();
  26361. EXPECT_EQ(1, proxy.connect_hits());
  26362. }
  26363. #endif