test.cc 1018 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. std::vector<std::string> get_ca_names(ctx_t ctx);
  69. } // namespace tls
  70. } // namespace httplib
  71. #endif
  72. using namespace std;
  73. using namespace httplib;
  74. const char *HOST = "localhost";
  75. static int get_base_port() {
  76. const char *shard = getenv("GTEST_SHARD_INDEX");
  77. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  78. }
  79. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  80. // New standalone tests MUST use svr.bind_to_any_port() instead.
  81. const int PORT = get_base_port();
  82. const string LONG_QUERY_VALUE = string(25000, '@');
  83. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  84. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  85. const string TOO_LONG_QUERY_URL =
  86. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  87. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  88. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  89. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  90. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  91. return file.name == key;
  92. });
  93. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  94. return *it;
  95. #else
  96. if (it != items.end()) { return *it; }
  97. throw std::runtime_error("invalid multipart form data name error");
  98. #endif
  99. }
  100. static void read_file(const std::string &path, std::string &out) {
  101. std::ifstream fs(path, std::ios_base::binary);
  102. if (!fs) {
  103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  104. return;
  105. #else
  106. throw std::runtime_error("File not found: " + path);
  107. #endif
  108. }
  109. fs.seekg(0, std::ios_base::end);
  110. auto size = fs.tellg();
  111. fs.seekg(0);
  112. out.resize(static_cast<size_t>(size));
  113. fs.read(&out[0], static_cast<std::streamsize>(size));
  114. }
  115. class UnixSocketTest : public ::testing::Test {
  116. protected:
  117. void TearDown() override { std::remove(pathname_.c_str()); }
  118. void client_GET(const std::string &addr) {
  119. httplib::Client cli{addr};
  120. cli.set_address_family(AF_UNIX);
  121. ASSERT_TRUE(cli.is_valid());
  122. const auto &result = cli.Get(pattern_);
  123. ASSERT_TRUE(result) << "error: " << result.error();
  124. const auto &resp = result.value();
  125. EXPECT_EQ(resp.status, StatusCode::OK_200);
  126. EXPECT_EQ(resp.body, content_);
  127. }
  128. static std::string make_sock_path() {
  129. const char *shard = getenv("GTEST_SHARD_INDEX");
  130. return shard ? std::string("./httplib-server-") + shard + ".sock"
  131. : "./httplib-server.sock";
  132. }
  133. const std::string pathname_{make_sock_path()};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. // ".//x.sock", which is not taken for a URL
  154. client_GET("./" + pathname_.substr(1));
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_TRUE(s0.is_peer_alive());
  247. EXPECT_EQ(0, close(fds[1]));
  248. EXPECT_FALSE(s0.is_peer_alive());
  249. return true;
  250. });
  251. EXPECT_EQ(0, close(fds[0]));
  252. }
  253. TEST(SocketStream, wait_writable_INET) {
  254. sockaddr_in addr;
  255. memset(&addr, 0, sizeof(addr));
  256. addr.sin_family = AF_INET;
  257. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  258. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  259. int disconnected_svr_sock = -1;
  260. std::thread svr{[&] {
  261. const int s = socket(AF_INET, SOCK_STREAM, 0);
  262. ASSERT_LE(0, s);
  263. // PORT + 1 is shared with the SSL redirect tests and with
  264. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  265. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  266. // because that happens on a worker thread the ASSERT does not stop the
  267. // test: it runs on and fails at the disconnected_svr_sock check instead.
  268. default_socket_options(s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. // wait_writable() returns true because select_write() only checks if the
  292. // send buffer has space. Peer disconnection is detected later by send().
  293. EXPECT_TRUE(ss.wait_writable());
  294. return true;
  295. });
  296. ASSERT_EQ(0, close(disconnected_svr_sock));
  297. }
  298. #endif // #ifndef _WIN32
  299. TEST(SetSocketOptTest, TcpNoDelay) {
  300. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  301. ASSERT_NE(sock, INVALID_SOCKET);
  302. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  303. int val = 0;
  304. socklen_t len = sizeof(val);
  305. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  306. reinterpret_cast<char *>(&val), &len));
  307. EXPECT_NE(val, 0);
  308. detail::close_socket(sock);
  309. }
  310. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  311. // accept() reports failures through WSAGetLastError() on Windows and through
  312. // errno everywhere else. Asking the wrong one is what made the accept loop
  313. // treat every recoverable failure as fatal on Windows.
  314. struct Classification {
  315. bool resource;
  316. bool transient;
  317. };
  318. auto classify = [](int err) {
  319. #ifdef _WIN32
  320. WSASetLastError(err);
  321. #else
  322. errno = err;
  323. #endif
  324. // Read both before asserting: an assertion may clobber the error slot.
  325. Classification c;
  326. c.resource = detail::is_accept_resource_error();
  327. c.transient = detail::is_accept_transient_error();
  328. return c;
  329. };
  330. #ifdef _WIN32
  331. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  332. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  333. WSAECONNRESET, WSAECONNABORTED};
  334. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  335. #else
  336. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  337. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  338. ECONNABORTED};
  339. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  340. #endif
  341. for (auto err : resource_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.resource) << "error " << err;
  344. EXPECT_FALSE(c.transient) << "error " << err;
  345. }
  346. for (auto err : transient_errors) {
  347. const auto c = classify(err);
  348. EXPECT_TRUE(c.transient) << "error " << err;
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. }
  351. for (auto err : fatal_errors) {
  352. const auto c = classify(err);
  353. EXPECT_FALSE(c.resource) << "error " << err;
  354. EXPECT_FALSE(c.transient) << "error " << err;
  355. }
  356. #ifdef _WIN32
  357. WSASetLastError(0);
  358. #else
  359. errno = 0;
  360. #endif
  361. }
  362. TEST(ClientTest, MoveConstructible) {
  363. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  365. }
  366. TEST(ClientTest, MoveAssignable) {
  367. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  368. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  369. }
  370. #ifdef _WIN32
  371. TEST(StartupTest, WSAStartup) {
  372. WSADATA wsaData;
  373. int ret = WSAStartup(0x0002, &wsaData);
  374. ASSERT_EQ(0, ret);
  375. }
  376. #endif
  377. TEST(DecodePathTest, PercentCharacter) {
  378. EXPECT_EQ(
  379. decode_path_component(
  380. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  381. U8("descrip=Gastos áéíóúñÑ 6"));
  382. }
  383. TEST(DecodePathTest, PercentCharacterNUL) {
  384. string expected;
  385. expected.push_back('x');
  386. expected.push_back('\0');
  387. expected.push_back('x');
  388. EXPECT_EQ(decode_path_component("x%00x"), expected);
  389. }
  390. TEST(DecodePathTest, UnicodeEncoding) {
  391. // %u0041 = 'A' (1-byte UTF-8)
  392. EXPECT_EQ("A", decode_path_component("%u0041"));
  393. // %u00E9 = 'é' (2-byte UTF-8)
  394. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  395. // %u3042 = 'あ' (3-byte UTF-8)
  396. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  397. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  398. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  399. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  400. // neighbours)
  401. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  402. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  403. }
  404. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  405. // A sign or whitespace inside the two-character escape window must not be
  406. // accepted as a valid percent-encoding; the sequence is passed through
  407. // literally, matching decode_uri_component / decode_path_component.
  408. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  409. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  410. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  411. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  412. // Well-formed escapes still decode.
  413. EXPECT_EQ("-", decode_query_component("%2D", false));
  414. EXPECT_EQ("A", decode_query_component("%41", false));
  415. }
  416. TEST(SanitizeFilenameTest, VariousPatterns) {
  417. // Path traversal
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  420. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  421. // Normal and edge cases
  422. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  423. EXPECT_EQ("filename.txt",
  424. httplib::sanitize_filename("/path/to/filename.txt"));
  425. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  426. EXPECT_EQ("", httplib::sanitize_filename(".."));
  427. EXPECT_EQ("", httplib::sanitize_filename(""));
  428. // Null bytes stripped
  429. EXPECT_EQ("safe.txt",
  430. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  431. // Whitespace-only rejected
  432. EXPECT_EQ("", httplib::sanitize_filename(" "));
  433. }
  434. // Forward declaration (see the base64_encode note below): split builds move the
  435. // definition into httplib.cc, so re-declaring it here lets the test link.
  436. namespace httplib {
  437. namespace detail {
  438. bool is_chunked_transfer_encoding(const Headers &headers);
  439. } // namespace detail
  440. } // namespace httplib
  441. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  442. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  443. auto make = [](std::initializer_list<const char *> lines) {
  444. Headers h;
  445. for (auto te : lines) {
  446. if (te) { h.emplace("Transfer-Encoding", te); }
  447. }
  448. return h;
  449. };
  450. // Sole coding, matched case-insensitively.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  454. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  458. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  463. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  464. // were received, into one list. Headers preserves that order, so the answer
  465. // is decided by the last coding of the last line and the order the lines
  466. // arrived in is significant.
  467. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  470. // The split can fall anywhere in the list.
  471. EXPECT_TRUE(
  472. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  473. EXPECT_FALSE(
  474. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  475. // A trailing line naming no coding leaves the list ending in nothing, so it
  476. // must not inherit the chunked from the line before it.
  477. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  478. }
  479. // Forward declarations (see the base64_encode note below).
  480. namespace httplib {
  481. namespace detail {
  482. bool parse_status_line(const char *line, std::string &version, int &status,
  483. std::string &reason);
  484. std::string file_extension(const std::string &path);
  485. std::string
  486. find_content_type(const std::string &path,
  487. const std::map<std::string, std::string> &user_data,
  488. const std::string &default_content_type);
  489. bool can_compress_content_type(const std::string &content_type);
  490. bool is_prohibited_header_name(const std::string &name);
  491. #ifdef CPPHTTPLIB_SSL_ENABLED
  492. bool match_hostname(const std::string &pattern, const std::string &hostname);
  493. #endif
  494. } // namespace detail
  495. } // namespace httplib
  496. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  497. struct {
  498. const char *line;
  499. const char *version;
  500. int status;
  501. const char *reason;
  502. } cases[] = {
  503. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  504. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  505. // The reason phrase may be empty, or left out along with its space.
  506. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  507. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  508. };
  509. for (const auto &c : cases) {
  510. std::string version;
  511. int status = 0;
  512. std::string reason = "unset";
  513. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  514. << c.line;
  515. EXPECT_EQ(c.version, version);
  516. EXPECT_EQ(c.status, status);
  517. EXPECT_EQ(c.reason, reason);
  518. }
  519. }
  520. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  521. const char *lines[] = {
  522. "HTTP/2 200 OK\r\n",
  523. "HTTP/1.2 200 OK\r\n",
  524. "HTTP/1.1 20 OK\r\n",
  525. "HTTP/1.1 2000 OK\r\n",
  526. "HTTP/1.1 2x0 OK\r\n",
  527. "HTTP/1.1 200 OK\r\n",
  528. "HTTP/1.1 200OK\r\n",
  529. "HTTP/1.1 200 O\rK\r\n",
  530. "HTTP/1.1 200 OK",
  531. "HTTP/1.1 200 OK\r\nX",
  532. "",
  533. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  534. "HTTP/1.1 200 OK\n",
  535. #endif
  536. };
  537. for (auto line : lines) {
  538. std::string version;
  539. int status = 0;
  540. std::string reason;
  541. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  542. << line;
  543. }
  544. }
  545. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  546. // Long enough to overflow the stack when matched with std::regex.
  547. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  548. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  549. std::string version;
  550. int status = 0;
  551. std::string reason;
  552. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  553. EXPECT_EQ(200, status);
  554. EXPECT_EQ(long_reason, reason);
  555. }
  556. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  557. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  558. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  559. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  560. EXPECT_EQ("", detail::file_extension("noext"));
  561. EXPECT_EQ("", detail::file_extension("a."));
  562. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  563. EXPECT_EQ("", detail::file_extension("a.b-c"));
  564. // Long enough to overflow the stack when matched with std::regex.
  565. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  566. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  567. }
  568. #ifdef CPPHTTPLIB_SSL_ENABLED
  569. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  570. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  573. // A wildcard needs two labels after it, in the leftmost label only
  574. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  575. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  576. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  577. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  578. EXPECT_FALSE(
  579. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  580. // No name may have an empty label
  581. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  582. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  583. }
  584. #endif
  585. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  586. detail::case_ignore::hash hash;
  587. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  588. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  589. // Long enough to overflow the stack if hashed one call per character.
  590. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  591. }
  592. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  593. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  594. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  595. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  596. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  597. // Same 26-bit hash as html, svg and js.
  598. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  601. }
  602. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  603. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  604. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  605. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  606. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  607. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  608. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  609. // Same 26-bit hash as application/json.
  610. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  611. }
  612. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  613. Request req;
  614. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  615. EXPECT_TRUE(req.is_multipart_form_data());
  616. std::string boundary;
  617. EXPECT_TRUE(detail::parse_multipart_boundary(
  618. req.get_header_value("Content-Type"), boundary));
  619. EXPECT_EQ("x", boundary);
  620. }
  621. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  622. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  623. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  624. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  625. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  626. // Same 26-bit hash as REMOTE_ADDR.
  627. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  628. }
  629. // Forward declaration: in split builds split.py strips `inline` and moves the
  630. // definition into httplib.cc, so detail::base64_encode is not visible from the
  631. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  632. // in both header-only and split builds.
  633. namespace httplib {
  634. namespace detail {
  635. std::string base64_encode(const std::string &in);
  636. } // namespace detail
  637. } // namespace httplib
  638. TEST(Base64EncodeTest, KnownAnswers) {
  639. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  640. // where the accumulator's top bit is already set before the next shift.
  641. EXPECT_EQ("", detail::base64_encode(""));
  642. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  643. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  644. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  645. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  646. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  647. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  648. // High bytes keep the top bit set across several rounds.
  649. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  650. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  651. }
  652. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  653. string unescapedCharacters = "-_.!~*'()";
  654. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  655. }
  656. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  657. string reservedCharacters = ";,/?:@&=+$";
  658. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  659. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  660. }
  661. TEST(ClientQueryOrder, PreserveOrder) {
  662. // This test reproduces Issue #2259: client may reorder query parameters
  663. // when sending a GET request. The expected behavior is that the client
  664. // preserves the original query string order when the caller supplied it
  665. // as part of the path.
  666. Server svr;
  667. svr.Get("/", [&](const Request &req, Response &res) {
  668. // Echo back the raw target so the test can assert ordering
  669. res.set_content(req.target, "text/plain");
  670. });
  671. std::thread t{[&] { svr.listen(HOST, PORT); }};
  672. auto se = detail::scope_exit([&] {
  673. svr.stop();
  674. t.join();
  675. ASSERT_FALSE(svr.is_running());
  676. });
  677. svr.wait_until_ready();
  678. Client cli(HOST, PORT);
  679. ASSERT_TRUE(cli.is_valid());
  680. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  681. auto res = cli.Get(original);
  682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  683. // Expect the echoed target to exactly match the original path (order
  684. // preserved)
  685. EXPECT_EQ(res->body, original);
  686. }
  687. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  688. string chineseCharacters = U8("中国語");
  689. string russianCharacters = U8("дом");
  690. string brazilianCharacters = U8("óculos");
  691. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  692. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  693. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  694. "%D0%B4%D0%BE%D0%BC");
  695. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  696. }
  697. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  698. string unescapedCharacters = "-_.!~*'()";
  699. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  700. }
  701. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  702. string reservedCharacters = ";,/?:@&=+$";
  703. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  704. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  705. }
  706. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  707. string chineseCharacters = U8("中国語");
  708. string russianCharacters = U8("дом");
  709. string brazilianCharacters = U8("óculos");
  710. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  711. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  712. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  713. "%D0%B4%D0%BE%D0%BC");
  714. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  715. }
  716. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  717. // Issue #2082 use case: encoding path component with ampersand
  718. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  719. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  720. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  721. }
  722. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  723. string unescapedCharacters = "-_.!~*'()";
  724. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  725. }
  726. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  727. string reservedCharacters = ";,/?:@&=+$#";
  728. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  729. }
  730. TEST(EncodeUriTest, TestUTF8Characters) {
  731. string chineseCharacters = U8("中国語");
  732. string russianCharacters = U8("дом");
  733. string brazilianCharacters = U8("óculos");
  734. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  735. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  736. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  737. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  738. }
  739. TEST(EncodeUriTest, TestCompleteUri) {
  740. string uri =
  741. "https://example.com/path/to/resource?query=value&param=test#fragment";
  742. EXPECT_EQ(
  743. httplib::encode_uri(uri),
  744. "https://example.com/path/to/resource?query=value&param=test#fragment");
  745. }
  746. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  747. string uri =
  748. "https://example.com/path with spaces/file name.html?q=hello world";
  749. EXPECT_EQ(httplib::encode_uri(uri),
  750. "https://example.com/path%20with%20spaces/"
  751. "file%20name.html?q=hello%20world");
  752. }
  753. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  754. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  755. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  756. }
  757. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  758. string unescapedCharacters = "-_.!~*'()";
  759. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  760. }
  761. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  762. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  763. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  764. string encodedBrazilian = "%C3%B3culos";
  765. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  767. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  768. }
  769. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  770. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  772. "Piri Tommy Villiers - on & on");
  773. }
  774. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  775. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  776. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  777. }
  778. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  779. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  780. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  781. }
  782. TEST(DecodeUriTest, TestUTF8Characters) {
  783. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  784. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  785. string encodedBrazilian = "%C3%B3culos";
  786. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  787. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  788. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  789. }
  790. TEST(DecodeUriTest, TestCompleteUri) {
  791. string encodedUri = "https://example.com/path%20with%20spaces/"
  792. "file%20name.html?q=hello%20world";
  793. EXPECT_EQ(
  794. httplib::decode_uri(encodedUri),
  795. "https://example.com/path with spaces/file name.html?q=hello world");
  796. }
  797. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  798. string original =
  799. "https://example.com/path with spaces/file name.html?q=hello world";
  800. string encoded = httplib::encode_uri(original);
  801. string decoded = httplib::decode_uri(encoded);
  802. EXPECT_EQ(decoded, original);
  803. }
  804. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  805. // decode_uri is the inverse of encode_uri: an escaped reserved character
  806. // stays encoded so it is not promoted into a real delimiter, while
  807. // non-reserved escapes still decode (like JS decodeURI).
  808. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  809. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  810. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  811. "%3F%3A%40%26%3D%2B%24%2C%3B");
  812. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  813. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  814. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  815. "http://example.com/a%2Fb");
  816. // decode_uri_component still decodes the reserved character.
  817. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  818. }
  819. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  820. string original = "Piri Tommy Villiers - on & on";
  821. string encoded = httplib::encode_uri_component(original);
  822. string decoded = httplib::decode_uri_component(encoded);
  823. EXPECT_EQ(decoded, original);
  824. }
  825. TEST(TrimTests, TrimStringTests) {
  826. EXPECT_EQ("abc", detail::trim_copy("abc"));
  827. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  828. EXPECT_TRUE(detail::trim_copy("").empty());
  829. }
  830. TEST(AsciiTest, LocaleIndependentClassification) {
  831. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  832. // which consult the global C locale: std::isalnum(0xC5) can return true
  833. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  834. // helpers must classify every byte by the ASCII grammar alone.
  835. for (int i = 0; i < 256; i++) {
  836. auto c = static_cast<char>(i);
  837. auto is_digit = i >= '0' && i <= '9';
  838. auto is_upper = i >= 'A' && i <= 'Z';
  839. auto is_lower = i >= 'a' && i <= 'z';
  840. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  841. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  842. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  843. << "byte " << i;
  844. }
  845. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  846. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  847. // Non-ASCII bytes must be percent-encoded, never passed through as
  848. // alphanumeric.
  849. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  850. }
  851. TEST(FromCharsTest, Double) {
  852. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  853. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  854. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  855. auto parse = [](const std::string &s, double &v) {
  856. return detail::from_chars(s.data(), s.data() + s.size(), v);
  857. };
  858. double v = -1.0;
  859. // Representative quality values.
  860. EXPECT_EQ(parse("0", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.0);
  862. EXPECT_EQ(parse("1", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 1.0);
  864. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 0.8);
  866. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.001);
  868. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. // A missing integer or fractional part is tolerated.
  871. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  872. EXPECT_DOUBLE_EQ(v, 0.5);
  873. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 5.0);
  875. // Values outside [0, 1] still parse; the caller range-checks them.
  876. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  877. EXPECT_DOUBLE_EQ(v, 123.456);
  878. // Stops at the first byte that is not part of the number and reports where.
  879. std::string trailing = "0.9, text/html";
  880. auto r = parse(trailing, v);
  881. EXPECT_EQ(r.ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 0.9);
  883. EXPECT_EQ(*r.ptr, ',');
  884. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  885. // outright, and an 'e'/'E' simply ends the number.
  886. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  888. std::string exp_input = "1.5e3";
  889. r = parse(exp_input, v);
  890. EXPECT_EQ(r.ec, std::errc{});
  891. EXPECT_DOUBLE_EQ(v, 1.5);
  892. EXPECT_EQ(*r.ptr, 'e');
  893. // Invalid inputs.
  894. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  898. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  899. // Pathological but well-formed inputs must stay bounded (no overflow, no
  900. // out-of-bounds table access) and stay within [0, 1] for the caller.
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  902. std::errc{});
  903. EXPECT_DOUBLE_EQ(v, 0.0);
  904. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  905. std::errc{});
  906. EXPECT_GE(v, 0.0);
  907. EXPECT_LE(v, 1.0);
  908. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  909. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  910. }
  911. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  912. // Simple case without quality values
  913. std::vector<std::string> result1;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html,application/json,text/plain", result1));
  916. EXPECT_EQ(result1.size(), 3U);
  917. EXPECT_EQ(result1[0], "text/html");
  918. EXPECT_EQ(result1[1], "application/json");
  919. EXPECT_EQ(result1[2], "text/plain");
  920. // With quality values
  921. std::vector<std::string> result2;
  922. EXPECT_TRUE(detail::parse_accept_header(
  923. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  924. EXPECT_EQ(result2.size(), 3U);
  925. EXPECT_EQ(result2[0], "application/json"); // highest q value
  926. EXPECT_EQ(result2[1], "text/html");
  927. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  928. }
  929. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  930. // Mixed with and without quality values
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(
  933. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  934. EXPECT_EQ(result.size(), 3U);
  935. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  936. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  937. EXPECT_EQ(result[2], "application/json"); // q=0.5
  938. }
  939. TEST(ParseAcceptHeaderTest, EdgeCases) {
  940. // Empty header
  941. std::vector<std::string> empty_result;
  942. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  943. EXPECT_TRUE(empty_result.empty());
  944. // Single type
  945. std::vector<std::string> single_result;
  946. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  947. EXPECT_EQ(single_result.size(), 1U);
  948. EXPECT_EQ(single_result[0], "application/json");
  949. // Wildcard types
  950. std::vector<std::string> wildcard_result;
  951. EXPECT_TRUE(detail::parse_accept_header(
  952. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  953. EXPECT_EQ(wildcard_result.size(), 3U);
  954. EXPECT_EQ(wildcard_result[0], "application/json");
  955. EXPECT_EQ(wildcard_result[1], "text/*");
  956. EXPECT_EQ(wildcard_result[2], "*/*");
  957. }
  958. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  959. // Common browser Accept header
  960. std::vector<std::string> browser_result;
  961. EXPECT_TRUE(
  962. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  963. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  964. browser_result));
  965. EXPECT_EQ(browser_result.size(), 6U);
  966. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  970. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  971. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  972. // API client header
  973. std::vector<std::string> api_result;
  974. EXPECT_TRUE(detail::parse_accept_header(
  975. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  976. api_result));
  977. EXPECT_EQ(api_result.size(), 3U);
  978. EXPECT_EQ(api_result[0], "application/json");
  979. EXPECT_EQ(api_result[1], "application/xml");
  980. EXPECT_EQ(api_result[2], "text/plain");
  981. }
  982. TEST(ParseAcceptHeaderTest, SpecialCases) {
  983. // Quality value with 3 decimal places
  984. std::vector<std::string> decimal_result;
  985. EXPECT_TRUE(detail::parse_accept_header(
  986. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  987. EXPECT_EQ(decimal_result.size(), 2U);
  988. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  989. EXPECT_EQ(decimal_result[1], "text/html");
  990. // Zero quality (should still be included but with lowest priority)
  991. std::vector<std::string> zero_q_result;
  992. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  993. zero_q_result));
  994. EXPECT_EQ(zero_q_result.size(), 2U);
  995. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  996. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  997. // No spaces around commas
  998. std::vector<std::string> no_space_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1001. no_space_result));
  1002. EXPECT_EQ(no_space_result.size(), 3U);
  1003. EXPECT_EQ(no_space_result[0], "text/html");
  1004. EXPECT_EQ(no_space_result[1], "application/json");
  1005. EXPECT_EQ(no_space_result[2], "text/plain");
  1006. }
  1007. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1008. // Quality values always use '.' as the decimal separator, so parsing must
  1009. // not depend on the process locale. An embedding application may have
  1010. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1011. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1012. std::string saved = cur ? cur : "C";
  1013. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1014. "fr_FR.UTF-8"};
  1015. bool switched = false;
  1016. for (const auto loc : comma_locales) {
  1017. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1018. std::localeconv()->decimal_point[0] == ',') {
  1019. switched = true;
  1020. break;
  1021. }
  1022. }
  1023. if (!switched) {
  1024. std::setlocale(LC_NUMERIC, saved.c_str());
  1025. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1026. }
  1027. // The higher-weighted type appears later in the list, so a correct parse
  1028. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1029. // sensitive parse reads both weights as 0 and leaves the original order.
  1030. std::vector<std::string> result;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "application/json;q=0.1,text/html;q=0.9", result));
  1033. ASSERT_EQ(result.size(), 2U);
  1034. EXPECT_EQ(result[0], "text/html");
  1035. EXPECT_EQ(result[1], "application/json");
  1036. std::setlocale(LC_NUMERIC, saved.c_str());
  1037. }
  1038. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1039. std::vector<std::string> result;
  1040. // Invalid quality value (> 1.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1043. // Invalid quality value (< 0.0)
  1044. EXPECT_FALSE(
  1045. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1046. // Invalid quality value (not a number)
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=invalid,application/json", result));
  1049. // A valid numeric prefix does not make the entire quality value valid.
  1050. EXPECT_FALSE(detail::parse_accept_header(
  1051. "text/html;q=0.5junk,application/json", result));
  1052. // Empty quality value
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("text/html;q=,application/json", result));
  1055. // Invalid media type format (no slash and not wildcard)
  1056. EXPECT_FALSE(
  1057. detail::parse_accept_header("invalidtype,application/json", result));
  1058. // Valid cases should still work
  1059. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*/*");
  1062. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "*");
  1065. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "text/*");
  1068. }
  1069. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1070. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1071. // and must not be answered with 400 Bad Request.
  1072. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1073. struct {
  1074. const char *value;
  1075. std::vector<std::string> expected;
  1076. } cases[] = {
  1077. {",application/json", {"application/json"}},
  1078. {"text/html,", {"text/html"}},
  1079. {"text/html,,*/*", {"text/html", "*/*"}},
  1080. // An empty element may be spelled with whitespace in it
  1081. {"text/html, , application/json", {"text/html", "application/json"}},
  1082. // Nothing but empty elements is an empty list, which means the same
  1083. // thing as no Accept header at all
  1084. {",,,", {}},
  1085. // Quality values still apply across ignored empty elements
  1086. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1087. };
  1088. for (const auto &c : cases) {
  1089. std::vector<std::string> result;
  1090. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1091. << "value: " << c.value;
  1092. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1093. }
  1094. // An invalid entry is still rejected when empty elements surround it
  1095. std::vector<std::string> result;
  1096. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1097. }
  1098. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1099. // or ';' inside one does not end the list element or the parameter. Section
  1100. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1101. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1102. struct {
  1103. const char *value;
  1104. std::vector<std::string> expected;
  1105. } cases[] = {
  1106. {"text/html;profile=\"a,b\",application/json",
  1107. {"text/html", "application/json"}},
  1108. // A "q=" inside a quoted value is not the weight
  1109. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1110. {"text/html", "application/json"}},
  1111. // The weight after a quoted value still applies
  1112. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1113. {"application/json", "text/html"}},
  1114. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1115. {"application/json", "text/html"}},
  1116. {"text/html;profile=\"a\\\"b\",application/json",
  1117. {"text/html", "application/json"}},
  1118. // An escaped backslash does not escape the '"' after it
  1119. {"text/html;profile=\"a\\\\\",application/json",
  1120. {"text/html", "application/json"}},
  1121. };
  1122. for (const auto &c : cases) {
  1123. std::vector<std::string> result;
  1124. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1125. << "value: " << c.value;
  1126. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1127. }
  1128. }
  1129. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1130. Server svr;
  1131. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1132. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1133. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1134. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1135. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1136. res.set_content("ok", "text/plain");
  1137. });
  1138. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1139. EXPECT_TRUE(false);
  1140. res.set_content("bad request", "text/plain");
  1141. });
  1142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1143. auto se = detail::scope_exit([&] {
  1144. svr.stop();
  1145. listen_thread.join();
  1146. ASSERT_FALSE(svr.is_running());
  1147. });
  1148. svr.wait_until_ready();
  1149. Client cli("localhost", PORT);
  1150. {
  1151. auto res = cli.Get(
  1152. "/accept_ok",
  1153. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. auto res = cli.Get("/accept_bad_request",
  1159. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1162. }
  1163. }
  1164. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1165. Server svr;
  1166. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1167. res.set_content("ok", "text/plain");
  1168. });
  1169. std::atomic<int> start_count{0};
  1170. std::atomic<bool> running_when_called{false};
  1171. svr.set_start_handler([&]() {
  1172. running_when_called = svr.is_running();
  1173. start_count++;
  1174. });
  1175. auto port = svr.bind_to_any_port(HOST);
  1176. std::thread t([&]() { svr.listen_after_bind(); });
  1177. auto se = detail::scope_exit([&] {
  1178. svr.stop();
  1179. t.join();
  1180. ASSERT_FALSE(svr.is_running());
  1181. });
  1182. svr.wait_until_ready();
  1183. // A successful request proves the accept loop is running, which the start
  1184. // handler precedes; so by now the handler must have run exactly once.
  1185. Client cli(HOST, port);
  1186. cli.set_connection_timeout(std::chrono::seconds(5));
  1187. auto res = cli.Get("/");
  1188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1189. EXPECT_EQ(StatusCode::OK_200, res->status);
  1190. EXPECT_EQ(1, start_count.load());
  1191. EXPECT_TRUE(running_when_called.load());
  1192. }
  1193. TEST(DivideTest, DivideStringTests) {
  1194. auto divide = [](const std::string &str, char d) {
  1195. std::string lhs;
  1196. std::string rhs;
  1197. detail::divide(str, d,
  1198. [&](const char *lhs_data, std::size_t lhs_size,
  1199. const char *rhs_data, std::size_t rhs_size) {
  1200. lhs.assign(lhs_data, lhs_size);
  1201. rhs.assign(rhs_data, rhs_size);
  1202. });
  1203. return std::make_pair(std::move(lhs), std::move(rhs));
  1204. };
  1205. {
  1206. const auto res = divide("", '=');
  1207. EXPECT_EQ(res.first, "");
  1208. EXPECT_EQ(res.second, "");
  1209. }
  1210. {
  1211. const auto res = divide("=", '=');
  1212. EXPECT_EQ(res.first, "");
  1213. EXPECT_EQ(res.second, "");
  1214. }
  1215. {
  1216. const auto res = divide(" ", '=');
  1217. EXPECT_EQ(res.first, " ");
  1218. EXPECT_EQ(res.second, "");
  1219. }
  1220. {
  1221. const auto res = divide("a", '=');
  1222. EXPECT_EQ(res.first, "a");
  1223. EXPECT_EQ(res.second, "");
  1224. }
  1225. {
  1226. const auto res = divide("a=", '=');
  1227. EXPECT_EQ(res.first, "a");
  1228. EXPECT_EQ(res.second, "");
  1229. }
  1230. {
  1231. const auto res = divide("=b", '=');
  1232. EXPECT_EQ(res.first, "");
  1233. EXPECT_EQ(res.second, "b");
  1234. }
  1235. {
  1236. const auto res = divide("a=b", '=');
  1237. EXPECT_EQ(res.first, "a");
  1238. EXPECT_EQ(res.second, "b");
  1239. }
  1240. {
  1241. const auto res = divide("a=b=", '=');
  1242. EXPECT_EQ(res.first, "a");
  1243. EXPECT_EQ(res.second, "b=");
  1244. }
  1245. {
  1246. const auto res = divide("a=b=c", '=');
  1247. EXPECT_EQ(res.first, "a");
  1248. EXPECT_EQ(res.second, "b=c");
  1249. }
  1250. }
  1251. TEST(SplitTest, ParseQueryString) {
  1252. string s = "key1=val1&key2=val2&key3=val3";
  1253. Params dic;
  1254. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1255. [&](const char *b, const char *e) {
  1256. string key, val;
  1257. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1258. if (key.empty()) {
  1259. key.assign(b2, e2);
  1260. } else {
  1261. val.assign(b2, e2);
  1262. }
  1263. });
  1264. dic.emplace(key, val);
  1265. });
  1266. EXPECT_EQ("val1", dic.find("key1")->second);
  1267. EXPECT_EQ("val2", dic.find("key2")->second);
  1268. EXPECT_EQ("val3", dic.find("key3")->second);
  1269. }
  1270. TEST(SplitTest, ParseInvalidQueryTests) {
  1271. {
  1272. string s = " ";
  1273. Params dict;
  1274. detail::parse_query_text(s, dict);
  1275. EXPECT_TRUE(dict.empty());
  1276. }
  1277. {
  1278. string s = " = =";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. }
  1284. TEST(ParseQueryTest, ParseQueryString) {
  1285. {
  1286. std::string s = "key1=val1&key2=val2&key3=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("val1", dic.find("key1")->second);
  1290. EXPECT_EQ("val2", dic.find("key2")->second);
  1291. EXPECT_EQ("val3", dic.find("key3")->second);
  1292. }
  1293. {
  1294. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1295. Params dic;
  1296. detail::parse_query_text(s, dic);
  1297. EXPECT_EQ("", dic.find("key1")->second);
  1298. EXPECT_EQ("val1", dic.find("key2")->second);
  1299. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1300. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1301. }
  1302. }
  1303. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1304. Params dic;
  1305. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1306. dic.emplace("key1", "val1");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1308. dic.emplace("key2", "val2");
  1309. dic.emplace("key3", "val3");
  1310. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1311. }
  1312. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1313. Params params;
  1314. params.emplace("a", "1");
  1315. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1316. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1317. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1318. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1319. // Long enough to overflow the stack when matched with std::regex.
  1320. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1321. EXPECT_EQ("/p?" + long_query + "&a=1",
  1322. append_query_params("/p?" + long_query, params));
  1323. }
  1324. // Joins every entry of a Headers or Params into "key=value " so a whole
  1325. // traversal can be compared in one assertion. Both are instantiations of the
  1326. // same insertion-ordered container, so one helper serves both.
  1327. template <typename Map> static std::string entries_to_string(const Map &m) {
  1328. std::string s;
  1329. for (const auto &entry : m) {
  1330. s += entry.first + "=" + entry.second + " ";
  1331. }
  1332. return s;
  1333. }
  1334. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1335. // Params used to be a std::multimap, which sorted by name and handed the
  1336. // caller's query back alphabetised. A client signing its query string could
  1337. // not reproduce the order it asked for.
  1338. Params dic;
  1339. dic.emplace("zulu", "1");
  1340. dic.emplace("alpha", "2");
  1341. dic.emplace("mike", "3");
  1342. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1343. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1344. }
  1345. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1346. Params dic;
  1347. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1349. }
  1350. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1351. Request req;
  1352. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1353. req.params);
  1354. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag"));
  1356. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1357. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1358. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1359. EXPECT_EQ("", req.get_param_value("tag", 3));
  1360. }
  1361. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1362. // Params shares its container with Headers, which matches field names
  1363. // case-insensitively. Parameter names must not pick that up.
  1364. Params dic;
  1365. dic.emplace("Key", "upper");
  1366. dic.emplace("key", "lower");
  1367. EXPECT_EQ(2U, dic.size());
  1368. EXPECT_EQ(1U, dic.count("Key"));
  1369. EXPECT_EQ(1U, dic.count("key"));
  1370. EXPECT_EQ("upper", dic.find("Key")->second);
  1371. EXPECT_EQ("lower", dic.find("key")->second);
  1372. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1373. }
  1374. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1375. Server svr;
  1376. std::string order;
  1377. svr.Get("/order", [&](const Request &req, Response &res) {
  1378. order = entries_to_string(req.params);
  1379. res.set_content("ok", "text/plain");
  1380. });
  1381. auto port = svr.bind_to_any_port(HOST);
  1382. thread t = thread([&] { svr.listen_after_bind(); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. t.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, port);
  1390. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1391. ASSERT_TRUE(res);
  1392. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1393. }
  1394. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1395. Server svr;
  1396. std::string field_order, file_order;
  1397. svr.Post("/order", [&](const Request &req, Response &res) {
  1398. for (const auto &field : req.form.fields) {
  1399. field_order += field.first + "=" + field.second.content + " ";
  1400. }
  1401. for (const auto &file : req.form.files) {
  1402. file_order += file.first + "=" + file.second.filename + " ";
  1403. }
  1404. res.set_content("ok", "text/plain");
  1405. });
  1406. auto port = svr.bind_to_any_port(HOST);
  1407. thread t = thread([&] { svr.listen_after_bind(); });
  1408. auto se = detail::scope_exit([&] {
  1409. svr.stop();
  1410. t.join();
  1411. ASSERT_FALSE(svr.is_running());
  1412. });
  1413. svr.wait_until_ready();
  1414. UploadFormDataItems items = {
  1415. {"zulu", "1", "", ""},
  1416. {"alpha", "2", "", ""},
  1417. {"mike", "3", "", ""},
  1418. {"zebra", "z", "z.txt", "text/plain"},
  1419. {"apple", "a", "a.txt", "text/plain"},
  1420. };
  1421. Client cli(HOST, port);
  1422. auto res = cli.Post("/order", items);
  1423. ASSERT_TRUE(res);
  1424. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1425. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1426. }
  1427. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1428. Server svr;
  1429. std::vector<std::string> values;
  1430. std::string first, second, out_of_range, order;
  1431. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1432. values = req.form.get_fields("tag");
  1433. first = req.form.get_field("tag", 0);
  1434. second = req.form.get_field("tag", 1);
  1435. out_of_range = req.form.get_field("tag", 2);
  1436. for (const auto &field : req.form.fields) {
  1437. order += field.first + "=" + field.second.content + " ";
  1438. }
  1439. res.set_content("ok", "text/plain");
  1440. });
  1441. auto port = svr.bind_to_any_port(HOST);
  1442. thread t = thread([&] { svr.listen_after_bind(); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. t.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1450. // not adjacent in the container.
  1451. UploadFormDataItems items = {
  1452. {"tag", "first", "", ""},
  1453. {"other", "x", "", ""},
  1454. {"tag", "second", "", ""},
  1455. };
  1456. Client cli(HOST, port);
  1457. auto res = cli.Post("/repeated", items);
  1458. ASSERT_TRUE(res);
  1459. ASSERT_EQ(2U, values.size());
  1460. EXPECT_EQ("first", values[0]);
  1461. EXPECT_EQ("second", values[1]);
  1462. EXPECT_EQ("first", first);
  1463. EXPECT_EQ("second", second);
  1464. // std::multimap already kept entries sharing a name in insertion order, so
  1465. // everything above passes without this change too. The whole traversal is
  1466. // what tells the two apart: sorting by name would hoist "other" to the front
  1467. // and the two "tag" parts would end up adjacent.
  1468. EXPECT_EQ("tag=first other=x tag=second ", order);
  1469. // Advancing past the last entry of a name used to run off the container;
  1470. // the container's saturating increment makes it return the default instead.
  1471. EXPECT_EQ("", out_of_range);
  1472. }
  1473. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1474. Server svr;
  1475. std::string file_names;
  1476. svr.Post("/upload", [&](const Request &req, Response &res) {
  1477. for (const auto &file : req.form.files) {
  1478. file_names += file.first + "|" + file.second.filename + " ";
  1479. }
  1480. res.set_content("ok", "text/plain");
  1481. });
  1482. auto port = svr.bind_to_any_port(HOST);
  1483. thread t = thread([&] { svr.listen_after_bind(); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. t.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. // A trailing backslash would otherwise escape the closing quote.
  1491. UploadFormDataItems items = {
  1492. {"dir\\", "x", "a.txt", "text/plain"},
  1493. {"b", "y", "a\\\\b.txt", "text/plain"},
  1494. };
  1495. Client cli(HOST, port);
  1496. auto res = cli.Post("/upload", items);
  1497. ASSERT_TRUE(res);
  1498. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1499. }
  1500. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1501. // Server::read_content() keeps a FormFields::iterator alive across the
  1502. // content callbacks that fill the part it points at. The container is
  1503. // vector-backed, so a later emplace can reallocate and invalidate an older
  1504. // iterator; 64 parts grow the vector through seven reallocations, which
  1505. // checks that every part's content still lands in its own entry.
  1506. const size_t part_count = 64;
  1507. // One formula for both the parts sent and the values expected back, so the
  1508. // two cannot drift apart.
  1509. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1510. auto content_of = [](size_t i) {
  1511. return std::string(64, static_cast<char>('a' + (i % 26)));
  1512. };
  1513. Server svr;
  1514. std::vector<std::pair<std::string, std::string>> received;
  1515. svr.Post("/many", [&](const Request &req, Response &res) {
  1516. for (const auto &field : req.form.fields) {
  1517. received.emplace_back(field.first, field.second.content);
  1518. }
  1519. res.set_content("ok", "text/plain");
  1520. });
  1521. auto port = svr.bind_to_any_port(HOST);
  1522. thread t = thread([&] { svr.listen_after_bind(); });
  1523. auto se = detail::scope_exit([&] {
  1524. svr.stop();
  1525. t.join();
  1526. ASSERT_FALSE(svr.is_running());
  1527. });
  1528. svr.wait_until_ready();
  1529. UploadFormDataItems items;
  1530. for (size_t i = 0; i < part_count; i++) {
  1531. items.push_back({name_of(i), content_of(i), "", ""});
  1532. }
  1533. Client cli(HOST, port);
  1534. auto res = cli.Post("/many", items);
  1535. ASSERT_TRUE(res);
  1536. ASSERT_EQ(part_count, received.size());
  1537. for (size_t i = 0; i < part_count; i++) {
  1538. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1539. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1540. }
  1541. }
  1542. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1543. string content_type = "multipart/form-data; boundary=something";
  1544. string boundary;
  1545. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(boundary, "something");
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1550. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1551. string boundary;
  1552. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1553. EXPECT_TRUE(ret);
  1554. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1557. string content_type =
  1558. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1559. string boundary;
  1560. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1561. EXPECT_TRUE(ret);
  1562. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1565. string content_type =
  1566. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1567. string boundary;
  1568. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1569. EXPECT_TRUE(ret);
  1570. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1571. }
  1572. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1573. const string boundary(70, 'a');
  1574. string content_type = "multipart/form-data; boundary=" + boundary;
  1575. string parsed;
  1576. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1577. EXPECT_TRUE(ret);
  1578. EXPECT_EQ(parsed, boundary);
  1579. }
  1580. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1581. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1582. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1583. string parsed;
  1584. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1585. EXPECT_FALSE(ret);
  1586. }
  1587. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1588. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1589. // is 72 characters on the wire and still valid.
  1590. const string boundary(70, 'a');
  1591. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1592. string parsed;
  1593. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1594. EXPECT_EQ(parsed, boundary);
  1595. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1596. parsed.clear();
  1597. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1598. }
  1599. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1600. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1601. // The parameter parser must not treat that '=' as the key/value separator.
  1602. string content_type =
  1603. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1604. "charset=UTF-8";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1608. }
  1609. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1610. // A ';' inside the quoted-string is part of the value, not a parameter
  1611. // separator, so it must not truncate the boundary.
  1612. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1613. string parsed;
  1614. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1615. EXPECT_EQ(parsed, "a;b");
  1616. }
  1617. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1621. EXPECT_EQ("a\\b", parsed);
  1622. EXPECT_TRUE(detail::parse_multipart_boundary(
  1623. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1624. EXPECT_EQ("a\"b", parsed);
  1625. }
  1626. TEST(ParseDispositionParamsTest, QuotedValues) {
  1627. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1628. // ';' and '=' are ordinary characters inside one.
  1629. struct {
  1630. const char *value;
  1631. std::vector<std::pair<const char *, const char *>> expected;
  1632. } cases[] = {
  1633. {"name=\"file1\"; filename=\"a.txt\"",
  1634. {{"name", "file1"}, {"filename", "a.txt"}}},
  1635. // Whitespace around '=' and ';' is still trimmed
  1636. {"name=\"file2\" ;filename = \"a.html\"",
  1637. {{"name", "file2"}, {"filename", "a.html"}}},
  1638. // '=' inside the value used to leave only the text after the last one
  1639. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1640. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1641. {"name=\"x=y\"", {{"name", "x=y"}}},
  1642. // ';' inside the value used to truncate the pair and leave a bogus one
  1643. {"name=\"file3\"; filename=\"a;b.txt\"",
  1644. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1645. // An unquoted value keeps working, and so does filename*
  1646. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1647. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1648. // A parameter with no key is dropped rather than turned into one whose
  1649. // key is the value
  1650. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1651. // An escaped quote does not end the value
  1652. {"name=\"a\\\"; filename=evil.php\"",
  1653. {{"name", "a\"; filename=evil.php"}}},
  1654. // Other backslashes, as in a Windows path, are kept
  1655. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1656. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1657. };
  1658. for (const auto &c : cases) {
  1659. Params params;
  1660. detail::parse_disposition_params(c.value, params);
  1661. for (const auto &kv : c.expected) {
  1662. auto it = params.find(kv.first);
  1663. ASSERT_NE(it, params.end())
  1664. << "value: " << c.value << ", key: " << kv.first;
  1665. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1666. }
  1667. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1668. }
  1669. }
  1670. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1671. Server svr;
  1672. std::string filename;
  1673. std::string content;
  1674. svr.Post("/upload", [&](const Request &req, Response &) {
  1675. const auto &file = req.form.get_file("file");
  1676. filename = file.filename;
  1677. content = file.content;
  1678. });
  1679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1680. auto se = detail::scope_exit([&] {
  1681. svr.stop();
  1682. thread.join();
  1683. ASSERT_FALSE(svr.is_running());
  1684. });
  1685. svr.wait_until_ready();
  1686. std::string body = "--B\r\n"
  1687. "Content-Disposition: form-data; name=\"file\"; "
  1688. "filename=\"a.txt\"\r\n"
  1689. "Content-Type: text/plain\r\n"
  1690. "\r\n"
  1691. "hello\r\n"
  1692. "--B--\r\n";
  1693. Client cli(HOST, PORT);
  1694. auto res = cli.Post(
  1695. "/upload",
  1696. [&](size_t offset, DataSink &sink) {
  1697. if (offset < body.size()) {
  1698. sink.write(&body[offset], 1);
  1699. } else {
  1700. sink.done();
  1701. }
  1702. return true;
  1703. },
  1704. "multipart/form-data; boundary=B");
  1705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1706. EXPECT_EQ(StatusCode::OK_200, res->status);
  1707. EXPECT_EQ("a.txt", filename);
  1708. EXPECT_EQ("hello", content);
  1709. }
  1710. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1711. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1712. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1713. Server svr;
  1714. std::string field_value, file_name, file_filename;
  1715. bool has_field = false, has_file = false;
  1716. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1717. has_field = req.form.has_field("x=y");
  1718. field_value = req.form.get_field("x=y");
  1719. has_file = req.form.has_file("file1");
  1720. const auto &file = req.form.get_file("file1");
  1721. file_name = file.name;
  1722. file_filename = file.filename;
  1723. res.set_content("ok", "text/plain");
  1724. });
  1725. auto port = svr.bind_to_any_port(HOST);
  1726. thread t = thread([&] { svr.listen_after_bind(); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. t.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. UploadFormDataItems items = {
  1734. {"x=y", "field-value", "", ""},
  1735. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1736. };
  1737. Client cli(HOST, port);
  1738. auto res = cli.Post("/quoted", items);
  1739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1740. ASSERT_EQ(StatusCode::OK_200, res->status);
  1741. EXPECT_TRUE(has_field);
  1742. EXPECT_EQ("field-value", field_value);
  1743. EXPECT_TRUE(has_file);
  1744. EXPECT_EQ("file1", file_name);
  1745. EXPECT_EQ("a;b=report.pdf", file_filename);
  1746. }
  1747. TEST(GetHeaderValueTest, DefaultValue) {
  1748. Headers headers = {{"Dummy", "Dummy"}};
  1749. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1750. EXPECT_STREQ("text/plain", val);
  1751. }
  1752. TEST(GetHeaderValueTest, DefaultValueInt) {
  1753. Headers headers = {{"Dummy", "Dummy"}};
  1754. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1755. EXPECT_EQ(100ull, val);
  1756. }
  1757. TEST(GetHeaderValueTest, RegularValue) {
  1758. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1759. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1760. EXPECT_STREQ("text/html", val);
  1761. }
  1762. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1763. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1764. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1765. EXPECT_STREQ("text/html", val);
  1766. }
  1767. TEST(GetHeaderValueTest, SetContent) {
  1768. Response res;
  1769. res.set_content("html", "text/html");
  1770. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1771. res.set_content("text", "text/plain");
  1772. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1773. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueInt) {
  1776. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1778. EXPECT_EQ(100ull, val);
  1779. }
  1780. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1781. Headers headers = {{"Content-Length", "x"}};
  1782. auto is_invalid_value = false;
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1784. is_invalid_value);
  1785. EXPECT_EQ(0ull, val);
  1786. EXPECT_TRUE(is_invalid_value);
  1787. }
  1788. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1789. // An all-digit value that overflows size_t must be reported as invalid, not
  1790. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1791. // a large length to a small one on 32-bit builds, leaving the framing length
  1792. // wrong while is_invalid_value stayed false.
  1793. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1794. auto is_invalid_value = false;
  1795. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1796. is_invalid_value);
  1797. EXPECT_TRUE(is_invalid_value);
  1798. // A well-formed length is unaffected.
  1799. Headers ok = {{"Content-Length", "1234"}};
  1800. is_invalid_value = false;
  1801. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_EQ(1234ull, val);
  1804. EXPECT_FALSE(is_invalid_value);
  1805. }
  1806. TEST(GetHeaderValueTest, Range) {
  1807. {
  1808. Headers headers = {make_range_header({{1, -1}})};
  1809. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1810. EXPECT_STREQ("bytes=1-", val);
  1811. }
  1812. {
  1813. Headers headers = {make_range_header({{-1, 1}})};
  1814. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1815. EXPECT_STREQ("bytes=-1", val);
  1816. }
  1817. {
  1818. Headers headers = {make_range_header({{1, 10}})};
  1819. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1820. EXPECT_STREQ("bytes=1-10", val);
  1821. }
  1822. {
  1823. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1824. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1825. EXPECT_STREQ("bytes=1-10, 100-", val);
  1826. }
  1827. {
  1828. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1829. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1830. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1831. }
  1832. {
  1833. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1834. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1835. EXPECT_STREQ("bytes=0-0, -1", val);
  1836. }
  1837. }
  1838. TEST(BearerTokenAuthTest, SchemeValidation) {
  1839. // A value shorter than "Bearer " must not throw from the fixed-length
  1840. // substr, and a non-Bearer scheme must not be reported as a token.
  1841. struct {
  1842. const char *value;
  1843. const char *expected;
  1844. } cases[] = {
  1845. {"x", ""},
  1846. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1847. {"Bearer abc123", "abc123"},
  1848. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1849. };
  1850. for (const auto &c : cases) {
  1851. Request req;
  1852. req.set_header("Authorization", c.value);
  1853. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1854. }
  1855. }
  1856. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1857. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1858. // to depend on the standard library (libstdc++ handed back duplicates in
  1859. // reverse insertion order, libc++ in insertion order).
  1860. Request req;
  1861. req.set_header("Accept-Encoding", "gzip");
  1862. req.set_header("Accept-Encoding", "deflate");
  1863. req.set_header("Accept-Encoding", "br");
  1864. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1866. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1867. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1868. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1869. }
  1870. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1871. Request req;
  1872. req.set_header("X-Test", "only");
  1873. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1875. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1876. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1877. }
  1878. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1879. Request req;
  1880. req.set_header("X-First", "1");
  1881. req.set_header("X-Test", "2");
  1882. req.params.emplace("first", "1");
  1883. req.params.emplace("test", "2");
  1884. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1885. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1886. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1887. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1888. // The second one is negative when read as a signed value
  1889. const auto max_id = (std::numeric_limits<size_t>::max)();
  1890. for (auto id : {max_id / 2, max_id}) {
  1891. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1892. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1893. EXPECT_EQ("", req.get_param_value("test", id));
  1894. EXPECT_EQ("", req.form.get_field("test", id));
  1895. EXPECT_EQ("", req.form.get_file("test", id).content);
  1896. }
  1897. }
  1898. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1899. Headers headers;
  1900. headers.emplace("Host", "example.com");
  1901. headers.emplace("Accept-Encoding", "gzip");
  1902. headers.emplace("User-Agent", "test");
  1903. headers.emplace("Accept-Encoding", "deflate");
  1904. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1905. "Accept-Encoding=deflate ",
  1906. entries_to_string(headers));
  1907. }
  1908. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1909. Headers headers = {{"Content-Type", "text/html"},
  1910. {"CONTENT-TYPE", "text/xml"}};
  1911. EXPECT_EQ(2U, headers.count("content-type"));
  1912. auto it = headers.find("content-type");
  1913. ASSERT_TRUE(it != headers.end());
  1914. EXPECT_EQ("text/html", it->second);
  1915. }
  1916. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1917. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1918. // drop only those fields and leave everything positioned between them.
  1919. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1920. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1921. auto rng = headers.equal_range("a");
  1922. headers.erase(rng.first, rng.second);
  1923. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1924. }
  1925. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1926. Headers headers = {
  1927. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1928. EXPECT_EQ(3U, headers.erase("A"));
  1929. EXPECT_EQ(0U, headers.count("A"));
  1930. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1933. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1934. headers.emplace_front("Host", "example.com");
  1935. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1936. entries_to_string(headers));
  1937. }
  1938. TEST(ParseHeaderValueTest, Range) {
  1939. {
  1940. Ranges ranges;
  1941. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1944. }
  1945. {
  1946. Ranges ranges;
  1947. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1948. EXPECT_TRUE(ret);
  1949. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1960. EXPECT_FALSE(ret);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1965. EXPECT_TRUE(ret);
  1966. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret =
  1971. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1990. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1991. EXPECT_FALSE(
  1992. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1993. EXPECT_TRUE(ranges.empty());
  1994. }
  1995. {
  1996. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1997. // remainder of the representation, so it stays accepted.
  1998. Ranges ranges;
  1999. auto ret =
  2000. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2001. EXPECT_TRUE(ret);
  2002. ASSERT_EQ(1u, ranges.size());
  2003. EXPECT_EQ(0, ranges[0].first);
  2004. EXPECT_EQ(-1, ranges[0].second);
  2005. }
  2006. // RFC 9110 14.1: range unit names are case-insensitive.
  2007. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2008. Ranges ranges;
  2009. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2010. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2011. }
  2012. }
  2013. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding", "gzip");
  2016. Response res;
  2017. res.set_header("Content-Type", "text/plain");
  2018. auto ret = detail::encoding_type(req, res);
  2019. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2020. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2021. #else
  2022. EXPECT_TRUE(ret == detail::EncodingType::None);
  2023. #endif
  2024. }
  2025. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2033. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2034. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2035. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2036. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2037. #else
  2038. EXPECT_TRUE(ret == detail::EncodingType::None);
  2039. #endif
  2040. }
  2041. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2042. Request req;
  2043. req.set_header("Accept-Encoding",
  2044. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2045. Response res;
  2046. res.set_header("Content-Type", "text/plain");
  2047. auto ret = detail::encoding_type(req, res);
  2048. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2050. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2052. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2053. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2054. #else
  2055. EXPECT_TRUE(ret == detail::EncodingType::None);
  2056. #endif
  2057. }
  2058. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2059. // All supported encodings rejected with q=0 should return None
  2060. Request req;
  2061. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2062. Response res;
  2063. res.set_header("Content-Type", "text/plain");
  2064. auto ret = detail::encoding_type(req, res);
  2065. EXPECT_TRUE(ret == detail::EncodingType::None);
  2066. }
  2067. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2068. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2069. Request req;
  2070. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2071. Response res;
  2072. res.set_header("Content-Type", "text/plain");
  2073. auto ret = detail::encoding_type(req, res);
  2074. EXPECT_TRUE(ret == detail::EncodingType::None);
  2075. }
  2076. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2077. Request req;
  2078. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2079. Response res;
  2080. res.set_header("Content-Type", "text/plain");
  2081. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2082. }
  2083. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2084. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2085. Request req;
  2086. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2087. Response res;
  2088. res.set_header("Content-Type", "text/plain");
  2089. auto ret = detail::encoding_type(req, res);
  2090. EXPECT_TRUE(ret == detail::EncodingType::None);
  2091. }
  2092. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2093. // RFC 7231: Accept-Encoding values are case-insensitive
  2094. Request req;
  2095. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2096. Response res;
  2097. res.set_header("Content-Type", "text/plain");
  2098. auto ret = detail::encoding_type(req, res);
  2099. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2100. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2101. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2102. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2103. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2104. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2105. #else
  2106. EXPECT_TRUE(ret == detail::EncodingType::None);
  2107. #endif
  2108. }
  2109. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2110. // q value should determine priority, not hardcoded order
  2111. Request req;
  2112. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2113. Response res;
  2114. res.set_header("Content-Type", "text/plain");
  2115. auto ret = detail::encoding_type(req, res);
  2116. // gzip has highest q=1.0, so it should be selected even though
  2117. // br and zstd are also supported
  2118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2120. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2121. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2122. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2123. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2124. #else
  2125. EXPECT_TRUE(ret == detail::EncodingType::None);
  2126. #endif
  2127. }
  2128. TEST(BufferStreamTest, read) {
  2129. detail::BufferStream strm1;
  2130. Stream &strm = strm1;
  2131. EXPECT_EQ(5, strm.write("hello"));
  2132. char buf[512];
  2133. EXPECT_EQ(2, strm.read(buf, 2));
  2134. EXPECT_EQ('h', buf[0]);
  2135. EXPECT_EQ('e', buf[1]);
  2136. EXPECT_EQ(2, strm.read(buf, 2));
  2137. EXPECT_EQ('l', buf[0]);
  2138. EXPECT_EQ('l', buf[1]);
  2139. EXPECT_EQ(1, strm.read(buf, 1));
  2140. EXPECT_EQ('o', buf[0]);
  2141. EXPECT_EQ(0, strm.read(buf, 1));
  2142. }
  2143. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2144. auto host = "www.httpwatch.com";
  2145. auto ip = hosted_at(host);
  2146. EXPECT_EQ("23.96.13.243", ip);
  2147. std::vector<std::string> addrs;
  2148. hosted_at(host, addrs);
  2149. EXPECT_EQ(1u, addrs.size());
  2150. }
  2151. #if 0 // It depends on each test environment...
  2152. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2153. auto host = "www.youtube.com";
  2154. std::vector<std::string> addrs;
  2155. hosted_at(host, addrs);
  2156. EXPECT_EQ(20u, addrs.size());
  2157. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2158. EXPECT_TRUE(it != addrs.end());
  2159. }
  2160. #endif
  2161. class ChunkedEncodingTest : public ::testing::Test {
  2162. protected:
  2163. ChunkedEncodingTest()
  2164. : cli_(HOST, PORT)
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. ,
  2167. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2168. #endif
  2169. {
  2170. cli_.set_connection_timeout(2);
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. cli_.enable_server_certificate_verification(false);
  2173. #endif
  2174. }
  2175. virtual void SetUp() {
  2176. read_file("./image.jpg", image_data_);
  2177. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2178. res.set_content("Hello World!", "text/plain");
  2179. });
  2180. svr_.Get(
  2181. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2182. res.set_chunked_content_provider(
  2183. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2184. size_t remaining = image_data_.size() - offset;
  2185. if (remaining == 0) {
  2186. sink.done();
  2187. } else {
  2188. constexpr size_t CHUNK_SIZE = 1024;
  2189. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2190. sink.write(&image_data_[offset], send_size);
  2191. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2192. }
  2193. return true;
  2194. });
  2195. });
  2196. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2197. svr_.wait_until_ready();
  2198. }
  2199. virtual void TearDown() {
  2200. svr_.stop();
  2201. if (!request_threads_.empty()) {
  2202. std::this_thread::sleep_for(std::chrono::seconds(1));
  2203. for (auto &t : request_threads_) {
  2204. t.join();
  2205. }
  2206. }
  2207. t_.join();
  2208. }
  2209. #ifdef CPPHTTPLIB_SSL_ENABLED
  2210. SSLClient cli_;
  2211. SSLServer svr_;
  2212. #else
  2213. Client cli_;
  2214. Server svr_;
  2215. #endif
  2216. thread t_;
  2217. std::vector<thread> request_threads_;
  2218. std::string image_data_;
  2219. };
  2220. TEST_F(ChunkedEncodingTest, NormalGet) {
  2221. auto res = cli_.Get("/chunked");
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. std::string out;
  2224. read_file("./image.jpg", out);
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(out, res->body);
  2227. }
  2228. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2229. std::string body;
  2230. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2231. body.append(data, data_length);
  2232. return true;
  2233. });
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get(
  2243. "/chunked",
  2244. [&](const Response &response) {
  2245. EXPECT_EQ(StatusCode::OK_200, response.status);
  2246. return true;
  2247. },
  2248. [&](const char *data, size_t data_length) {
  2249. body.append(data, data_length);
  2250. return true;
  2251. });
  2252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2253. std::string out;
  2254. read_file("./image.jpg", out);
  2255. EXPECT_EQ(StatusCode::OK_200, res->status);
  2256. EXPECT_EQ(out, body);
  2257. }
  2258. TEST(RangeTest, FromHTTPBin_Online) {
  2259. auto host = "httpbingo.org";
  2260. auto path = std::string{"/range/32"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(5);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. }
  2275. {
  2276. Headers headers = {make_range_header({{1, -1}})};
  2277. auto res = cli.Get(path, headers);
  2278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2279. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2281. }
  2282. {
  2283. Headers headers = {make_range_header({{1, 10}})};
  2284. auto res = cli.Get(path, headers);
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("bcdefghijk", res->body);
  2287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2288. }
  2289. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2290. // entire resource, while the original httpbin returned 200. Both are
  2291. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2292. {
  2293. Headers headers = {make_range_header({{0, 31}})};
  2294. auto res = cli.Get(path, headers);
  2295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2296. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2297. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2298. res->status == StatusCode::PartialContent_206);
  2299. }
  2300. {
  2301. Headers headers = {make_range_header({{0, -1}})};
  2302. auto res = cli.Get(path, headers);
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2305. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2306. res->status == StatusCode::PartialContent_206);
  2307. }
  2308. // go-httpbin returns 206 with clamped range for over-range requests,
  2309. // while the original httpbin returned 416. Both behaviors are observed
  2310. // in real servers, so we only verify the request succeeds.
  2311. {
  2312. Headers headers = {make_range_header({{0, 32}})};
  2313. auto res = cli.Get(path, headers);
  2314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2315. }
  2316. }
  2317. TEST(RangeTest, IgnoredForPost) {
  2318. Server svr;
  2319. svr.Post("/", [](const Request &, Response &res) {
  2320. res.set_content("abcdefg", "text/plain");
  2321. });
  2322. auto port = svr.bind_to_any_port(HOST);
  2323. ASSERT_GT(port, 0);
  2324. thread t = thread([&] { svr.listen_after_bind(); });
  2325. auto se = detail::scope_exit([&] {
  2326. svr.stop();
  2327. t.join();
  2328. ASSERT_FALSE(svr.is_running());
  2329. });
  2330. svr.wait_until_ready();
  2331. Client cli(HOST, port);
  2332. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2333. auto res = cli.Post("/", Headers{{"Range", range}});
  2334. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2335. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2336. EXPECT_EQ("abcdefg", res->body) << range;
  2337. }
  2338. }
  2339. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2340. auto host = "unresolvableaddress.local";
  2341. auto path = std::string{"/"};
  2342. #ifdef CPPHTTPLIB_SSL_ENABLED
  2343. auto port = 443;
  2344. SSLClient cli(host, port);
  2345. #else
  2346. auto port = 80;
  2347. Client cli(host, port);
  2348. #endif
  2349. cli.set_connection_timeout(1);
  2350. {
  2351. auto res = cli.Get(path);
  2352. ASSERT_FALSE(res);
  2353. }
  2354. std::this_thread::sleep_for(std::chrono::seconds(8));
  2355. }
  2356. #if defined(__linux__) && defined(__GLIBC__) && \
  2357. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2358. // Forward declaration: in split builds split.py strips `inline` and moves the
  2359. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2360. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2361. // against the symbol in both header-only and split builds.
  2362. namespace httplib {
  2363. namespace detail {
  2364. int getaddrinfo_with_timeout(const char *node, const char *service,
  2365. const struct addrinfo *hints,
  2366. struct addrinfo **res, time_t timeout_sec);
  2367. } // namespace detail
  2368. } // namespace httplib
  2369. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2370. //
  2371. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2372. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2373. // gai_suspend() call hits the connection timeout the function calls
  2374. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2375. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2376. // still alive and still references the now-destroyed stack frame.
  2377. //
  2378. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2379. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2380. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2381. // and runs them in a container.
  2382. namespace {
  2383. bool should_run_issue_2431_tests() {
  2384. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2385. return v && *v && std::string(v) != "0";
  2386. }
  2387. std::string unique_unresolvable_host(int n) {
  2388. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2389. // glibc still asks the configured nameserver — which is exactly the path
  2390. // we want to exercise. A unique label per call avoids the resolver cache.
  2391. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2392. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2393. std::to_string(n) + ".invalid";
  2394. }
  2395. } // namespace
  2396. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2397. if (!should_run_issue_2431_tests()) {
  2398. GTEST_SKIP()
  2399. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2400. }
  2401. for (int i = 0; i < 8; ++i) {
  2402. struct addrinfo hints;
  2403. memset(&hints, 0, sizeof(hints));
  2404. hints.ai_family = AF_UNSPEC;
  2405. hints.ai_socktype = SOCK_STREAM;
  2406. auto host = unique_unresolvable_host(i);
  2407. struct addrinfo *result = nullptr;
  2408. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2409. &result, /*timeout_sec=*/1);
  2410. if (rc == 0 && result) { freeaddrinfo(result); }
  2411. }
  2412. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2413. // stack region they still believe holds their gaicb.
  2414. std::this_thread::sleep_for(std::chrono::seconds(3));
  2415. }
  2416. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2417. if (!should_run_issue_2431_tests()) {
  2418. GTEST_SKIP()
  2419. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2420. }
  2421. std::atomic<bool> stop{false};
  2422. std::vector<std::thread> threads;
  2423. for (int t = 0; t < 8; ++t) {
  2424. threads.emplace_back([t, &stop] {
  2425. int i = 0;
  2426. while (!stop.load(std::memory_order_relaxed)) {
  2427. struct addrinfo hints;
  2428. memset(&hints, 0, sizeof(hints));
  2429. hints.ai_family = AF_UNSPEC;
  2430. hints.ai_socktype = SOCK_STREAM;
  2431. auto host = unique_unresolvable_host(t * 100000 + i++);
  2432. struct addrinfo *result = nullptr;
  2433. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2434. &result, /*timeout_sec=*/1);
  2435. if (rc == 0 && result) { freeaddrinfo(result); }
  2436. }
  2437. });
  2438. }
  2439. std::this_thread::sleep_for(std::chrono::seconds(8));
  2440. stop.store(true, std::memory_order_relaxed);
  2441. for (auto &th : threads) {
  2442. th.join();
  2443. }
  2444. std::this_thread::sleep_for(std::chrono::seconds(3));
  2445. }
  2446. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2447. if (!should_run_issue_2431_tests()) {
  2448. GTEST_SKIP()
  2449. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2450. }
  2451. std::atomic<bool> stop{false};
  2452. std::vector<std::thread> threads;
  2453. for (int t = 0; t < 8; ++t) {
  2454. threads.emplace_back([t, &stop] {
  2455. int i = 0;
  2456. while (!stop.load(std::memory_order_relaxed)) {
  2457. auto host = unique_unresolvable_host(t * 100000 + i++);
  2458. Client cli(host, 80);
  2459. cli.set_connection_timeout(1, 0);
  2460. cli.set_read_timeout(1, 0);
  2461. cli.set_write_timeout(1, 0);
  2462. (void)cli.Get("/");
  2463. }
  2464. });
  2465. }
  2466. std::this_thread::sleep_for(std::chrono::seconds(8));
  2467. stop.store(true, std::memory_order_relaxed);
  2468. for (auto &th : threads) {
  2469. th.join();
  2470. }
  2471. std::this_thread::sleep_for(std::chrono::seconds(3));
  2472. }
  2473. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2474. TEST(ConnectionErrorTest, InvalidHost) {
  2475. auto host = "-abcde.com";
  2476. #ifdef CPPHTTPLIB_SSL_ENABLED
  2477. auto port = 443;
  2478. SSLClient cli(host, port);
  2479. #else
  2480. auto port = 80;
  2481. Client cli(host, port);
  2482. #endif
  2483. cli.set_connection_timeout(std::chrono::seconds(2));
  2484. auto res = cli.Get("/");
  2485. ASSERT_TRUE(!res);
  2486. EXPECT_EQ(Error::Connection, res.error());
  2487. }
  2488. TEST(ConnectionErrorTest, InvalidHost2) {
  2489. auto host = "httpcan.org/";
  2490. #ifdef CPPHTTPLIB_SSL_ENABLED
  2491. SSLClient cli(host);
  2492. #else
  2493. Client cli(host);
  2494. #endif
  2495. cli.set_connection_timeout(std::chrono::seconds(2));
  2496. auto res = cli.Get("/");
  2497. ASSERT_TRUE(!res);
  2498. EXPECT_EQ(Error::Connection, res.error());
  2499. }
  2500. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2501. auto host = "httpcan.org/";
  2502. #ifdef CPPHTTPLIB_SSL_ENABLED
  2503. SSLClient cli(host);
  2504. #else
  2505. Client cli(host);
  2506. #endif
  2507. cli.set_connection_timeout(std::chrono::seconds(2));
  2508. auto res = cli.Get("/");
  2509. ASSERT_TRUE(!res);
  2510. stringstream s;
  2511. s << "error code: " << res.error();
  2512. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2513. }
  2514. TEST(ConnectionErrorTest, InvalidPort) {
  2515. auto host = "localhost";
  2516. auto port = 44380;
  2517. #ifdef CPPHTTPLIB_SSL_ENABLED
  2518. SSLClient cli(host, port);
  2519. #else
  2520. Client cli(host, port);
  2521. #endif
  2522. cli.set_connection_timeout(std::chrono::seconds(2));
  2523. auto res = cli.Get("/");
  2524. ASSERT_TRUE(!res);
  2525. EXPECT_TRUE(Error::Connection == res.error() ||
  2526. Error::ConnectionTimeout == res.error());
  2527. }
  2528. TEST(ConnectionErrorTest, Timeout_Online) {
  2529. auto host = "google.com";
  2530. #ifdef CPPHTTPLIB_SSL_ENABLED
  2531. auto port = 44380;
  2532. SSLClient cli(host, port);
  2533. #else
  2534. auto port = 8080;
  2535. Client cli(host, port);
  2536. #endif
  2537. cli.set_connection_timeout(std::chrono::seconds(2));
  2538. // only probe one address type so that the error reason
  2539. // correlates to the timed-out IPv4, not the unsupported
  2540. // IPv6 connection attempt
  2541. cli.set_address_family(AF_INET);
  2542. auto res = cli.Get("/");
  2543. ASSERT_TRUE(!res);
  2544. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2545. }
  2546. TEST(CancelTest, NoCancel_Online) {
  2547. auto host = "httpbingo.org";
  2548. auto path = std::string{"/range/32"};
  2549. #ifdef CPPHTTPLIB_SSL_ENABLED
  2550. auto port = 443;
  2551. SSLClient cli(host, port);
  2552. #else
  2553. auto port = 80;
  2554. Client cli(host, port);
  2555. #endif
  2556. cli.set_connection_timeout(std::chrono::seconds(5));
  2557. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2559. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2560. EXPECT_EQ(StatusCode::OK_200, res->status);
  2561. }
  2562. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2563. // Use /bytes with a large payload so that the DownloadProgress callback
  2564. // (which only fires for Content-Length responses) is invoked before the
  2565. // entire body is received, giving cancellation a chance to fire.
  2566. auto host = "httpbingo.org";
  2567. auto path = std::string{"/bytes/524288"};
  2568. #ifdef CPPHTTPLIB_SSL_ENABLED
  2569. auto port = 443;
  2570. SSLClient cli(host, port);
  2571. #else
  2572. auto port = 80;
  2573. Client cli(host, port);
  2574. #endif
  2575. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2576. cli.set_connection_timeout(std::chrono::seconds(5));
  2577. ASSERT_TRUE(!res);
  2578. EXPECT_EQ(Error::Canceled, res.error());
  2579. }
  2580. TEST(CancelTest, WithCancelLargePayload_Online) {
  2581. auto host = "httpbingo.org";
  2582. auto path = std::string{"/bytes/524288"};
  2583. #ifdef CPPHTTPLIB_SSL_ENABLED
  2584. auto port = 443;
  2585. SSLClient cli(host, port);
  2586. #else
  2587. auto port = 80;
  2588. Client cli(host, port);
  2589. #endif
  2590. cli.set_connection_timeout(std::chrono::seconds(5));
  2591. uint32_t count = 0;
  2592. auto res =
  2593. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2594. ASSERT_TRUE(!res);
  2595. EXPECT_EQ(Error::Canceled, res.error());
  2596. }
  2597. TEST(CancelTest, NoCancelPost) {
  2598. Server svr;
  2599. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2600. res.set_content("Hello World!", "text/plain");
  2601. });
  2602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2603. auto se = detail::scope_exit([&] {
  2604. svr.stop();
  2605. thread.join();
  2606. ASSERT_FALSE(svr.is_running());
  2607. });
  2608. svr.wait_until_ready();
  2609. Client cli(HOST, PORT);
  2610. cli.set_connection_timeout(std::chrono::seconds(5));
  2611. auto res =
  2612. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2613. "application/json", [](uint64_t, uint64_t) { return true; });
  2614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2615. EXPECT_EQ("Hello World!", res->body);
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. }
  2618. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2619. Server svr;
  2620. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2621. res.set_content("Hello World!", "text/plain");
  2622. });
  2623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli(HOST, PORT);
  2631. cli.set_connection_timeout(std::chrono::seconds(5));
  2632. auto res =
  2633. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2634. "application/json", [](uint64_t, uint64_t) { return false; });
  2635. ASSERT_TRUE(!res);
  2636. EXPECT_EQ(Error::Canceled, res.error());
  2637. }
  2638. TEST(CancelTest, WithCancelLargePayloadPost) {
  2639. Server svr;
  2640. svr.set_payload_max_length(200 * 1024 * 1024);
  2641. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2642. res.set_content(LARGE_DATA, "text/plain");
  2643. });
  2644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. Client cli(HOST, PORT);
  2652. cli.set_payload_max_length(200 * 1024 * 1024);
  2653. cli.set_connection_timeout(std::chrono::seconds(5));
  2654. auto res =
  2655. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2656. "application/json", [](uint64_t, uint64_t) { return false; });
  2657. ASSERT_TRUE(!res);
  2658. EXPECT_EQ(Error::Canceled, res.error());
  2659. }
  2660. TEST(CancelTest, NoCancelPut) {
  2661. Server svr;
  2662. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2663. res.set_content("Hello World!", "text/plain");
  2664. });
  2665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2666. auto se = detail::scope_exit([&] {
  2667. svr.stop();
  2668. thread.join();
  2669. ASSERT_FALSE(svr.is_running());
  2670. });
  2671. svr.wait_until_ready();
  2672. Client cli(HOST, PORT);
  2673. cli.set_connection_timeout(std::chrono::seconds(5));
  2674. auto res =
  2675. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2676. "application/json", [](uint64_t, uint64_t) { return true; });
  2677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2678. EXPECT_EQ("Hello World!", res->body);
  2679. EXPECT_EQ(StatusCode::OK_200, res->status);
  2680. }
  2681. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2682. Server svr;
  2683. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2684. res.set_content("Hello World!", "text/plain");
  2685. });
  2686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2687. auto se = detail::scope_exit([&] {
  2688. svr.stop();
  2689. thread.join();
  2690. ASSERT_FALSE(svr.is_running());
  2691. });
  2692. svr.wait_until_ready();
  2693. Client cli(HOST, PORT);
  2694. cli.set_connection_timeout(std::chrono::seconds(5));
  2695. auto res =
  2696. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2697. "application/json", [](uint64_t, uint64_t) { return false; });
  2698. ASSERT_TRUE(!res);
  2699. EXPECT_EQ(Error::Canceled, res.error());
  2700. }
  2701. TEST(CancelTest, WithCancelLargePayloadPut) {
  2702. Server svr;
  2703. svr.set_payload_max_length(200 * 1024 * 1024);
  2704. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2705. res.set_content(LARGE_DATA, "text/plain");
  2706. });
  2707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2708. auto se = detail::scope_exit([&] {
  2709. svr.stop();
  2710. thread.join();
  2711. ASSERT_FALSE(svr.is_running());
  2712. });
  2713. svr.wait_until_ready();
  2714. Client cli(HOST, PORT);
  2715. cli.set_payload_max_length(200 * 1024 * 1024);
  2716. cli.set_connection_timeout(std::chrono::seconds(5));
  2717. auto res =
  2718. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2719. "application/json", [](uint64_t, uint64_t) { return false; });
  2720. ASSERT_TRUE(!res);
  2721. EXPECT_EQ(Error::Canceled, res.error());
  2722. }
  2723. TEST(CancelTest, NoCancelPatch) {
  2724. Server svr;
  2725. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2726. res.set_content("Hello World!", "text/plain");
  2727. });
  2728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2729. auto se = detail::scope_exit([&] {
  2730. svr.stop();
  2731. thread.join();
  2732. ASSERT_FALSE(svr.is_running());
  2733. });
  2734. svr.wait_until_ready();
  2735. Client cli(HOST, PORT);
  2736. cli.set_connection_timeout(std::chrono::seconds(5));
  2737. auto res =
  2738. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2739. "application/json", [](uint64_t, uint64_t) { return true; });
  2740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2741. EXPECT_EQ("Hello World!", res->body);
  2742. EXPECT_EQ(StatusCode::OK_200, res->status);
  2743. }
  2744. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2745. Server svr;
  2746. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2747. res.set_content("Hello World!", "text/plain");
  2748. });
  2749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2750. auto se = detail::scope_exit([&] {
  2751. svr.stop();
  2752. thread.join();
  2753. ASSERT_FALSE(svr.is_running());
  2754. });
  2755. svr.wait_until_ready();
  2756. Client cli(HOST, PORT);
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. auto res =
  2759. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2760. "application/json", [](uint64_t, uint64_t) { return false; });
  2761. ASSERT_TRUE(!res);
  2762. EXPECT_EQ(Error::Canceled, res.error());
  2763. }
  2764. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2765. Server svr;
  2766. svr.set_payload_max_length(200 * 1024 * 1024);
  2767. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2768. res.set_content(LARGE_DATA, "text/plain");
  2769. });
  2770. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2771. auto se = detail::scope_exit([&] {
  2772. svr.stop();
  2773. thread.join();
  2774. ASSERT_FALSE(svr.is_running());
  2775. });
  2776. svr.wait_until_ready();
  2777. Client cli(HOST, PORT);
  2778. cli.set_payload_max_length(200 * 1024 * 1024);
  2779. cli.set_connection_timeout(std::chrono::seconds(5));
  2780. auto res =
  2781. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2782. "application/json", [](uint64_t, uint64_t) { return false; });
  2783. ASSERT_TRUE(!res);
  2784. EXPECT_EQ(Error::Canceled, res.error());
  2785. }
  2786. TEST(CancelTest, NoCancelDelete) {
  2787. Server svr;
  2788. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2789. res.set_content("Hello World!", "text/plain");
  2790. });
  2791. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2792. auto se = detail::scope_exit([&] {
  2793. svr.stop();
  2794. thread.join();
  2795. ASSERT_FALSE(svr.is_running());
  2796. });
  2797. svr.wait_until_ready();
  2798. Client cli(HOST, PORT);
  2799. cli.set_connection_timeout(std::chrono::seconds(5));
  2800. auto res =
  2801. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2802. "application/json", [](uint64_t, uint64_t) { return true; });
  2803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2804. EXPECT_EQ("Hello World!", res->body);
  2805. EXPECT_EQ(StatusCode::OK_200, res->status);
  2806. }
  2807. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2808. Server svr;
  2809. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2810. res.set_content("Hello World!", "text/plain");
  2811. });
  2812. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2813. auto se = detail::scope_exit([&] {
  2814. svr.stop();
  2815. thread.join();
  2816. ASSERT_FALSE(svr.is_running());
  2817. });
  2818. svr.wait_until_ready();
  2819. Client cli(HOST, PORT);
  2820. cli.set_connection_timeout(std::chrono::seconds(5));
  2821. auto res =
  2822. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2823. "application/json", [](uint64_t, uint64_t) { return false; });
  2824. ASSERT_TRUE(!res);
  2825. EXPECT_EQ(Error::Canceled, res.error());
  2826. }
  2827. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2828. Server svr;
  2829. svr.set_payload_max_length(200 * 1024 * 1024);
  2830. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2831. res.set_content(LARGE_DATA, "text/plain");
  2832. });
  2833. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2834. auto se = detail::scope_exit([&] {
  2835. svr.stop();
  2836. thread.join();
  2837. ASSERT_FALSE(svr.is_running());
  2838. });
  2839. svr.wait_until_ready();
  2840. Client cli(HOST, PORT);
  2841. cli.set_payload_max_length(200 * 1024 * 1024);
  2842. cli.set_connection_timeout(std::chrono::seconds(5));
  2843. auto res =
  2844. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2845. "application/json", [](uint64_t, uint64_t) { return false; });
  2846. ASSERT_TRUE(!res);
  2847. EXPECT_EQ(Error::Canceled, res.error());
  2848. }
  2849. static std::string remove_whitespace(const std::string &input) {
  2850. std::string output;
  2851. output.reserve(input.size());
  2852. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2853. [](unsigned char c) { return !std::isspace(c); });
  2854. return output;
  2855. }
  2856. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2857. auto host = "httpbingo.org";
  2858. auto path = std::string{"/basic-auth/hello/world"};
  2859. #ifdef CPPHTTPLIB_SSL_ENABLED
  2860. auto port = 443;
  2861. SSLClient cli(host, port);
  2862. #else
  2863. auto port = 80;
  2864. Client cli(host, port);
  2865. #endif
  2866. {
  2867. auto res = cli.Get(path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2870. }
  2871. {
  2872. auto res = cli.Get(
  2873. path, Headers{make_basic_authentication_header("hello", "world")});
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. auto body = remove_whitespace(res->body);
  2876. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2877. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. {
  2881. cli.set_basic_auth("hello", "world");
  2882. auto res = cli.Get(path);
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. auto body = remove_whitespace(res->body);
  2885. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2886. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2887. EXPECT_EQ(StatusCode::OK_200, res->status);
  2888. }
  2889. {
  2890. cli.set_basic_auth("hello", "bad");
  2891. auto res = cli.Get(path);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2894. }
  2895. {
  2896. cli.set_basic_auth("bad", "world");
  2897. auto res = cli.Get(path);
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2900. }
  2901. }
  2902. #ifdef CPPHTTPLIB_SSL_ENABLED
  2903. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2904. auto host = "httpbingo.org";
  2905. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2906. auto paths = std::vector<std::string>{
  2907. "/digest-auth/auth/hello/world/MD5",
  2908. "/digest-auth/auth/hello/world/SHA-256",
  2909. };
  2910. auto port = 443;
  2911. SSLClient cli(host, port);
  2912. {
  2913. auto res = cli.Get(unauth_path);
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2916. }
  2917. {
  2918. cli.set_digest_auth("hello", "world");
  2919. for (const auto &path : paths) {
  2920. auto res = cli.Get(path.c_str());
  2921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2922. auto body = remove_whitespace(res->body);
  2923. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2924. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2925. EXPECT_EQ(StatusCode::OK_200, res->status);
  2926. }
  2927. cli.set_digest_auth("hello", "bad");
  2928. for (const auto &path : paths) {
  2929. auto res = cli.Get(path.c_str());
  2930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2931. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2932. }
  2933. }
  2934. }
  2935. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2936. // comma-separated list of challenges, and each challenge may itself carry a
  2937. // comma-separated auth-param list, so a server can legally offer Basic
  2938. // before Digest, either as two field lines or packed into one. Runs one 401
  2939. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2940. // value() joins them in receipt order) and checks that the retry carries a
  2941. // well-formed Digest Authorization header naming expected_realm.
  2942. static void
  2943. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2944. const std::string &expected_realm) {
  2945. std::atomic<int> hits{0};
  2946. Server svr;
  2947. svr.Get("/x", [&](const Request &req, Response &res) {
  2948. if (++hits == 1) {
  2949. res.status = StatusCode::Unauthorized_401;
  2950. for (const auto &challenge : challenges) {
  2951. res.set_header("WWW-Authenticate", challenge);
  2952. }
  2953. } else {
  2954. auto authorization = req.get_header_value("Authorization");
  2955. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2956. EXPECT_NE(std::string::npos,
  2957. authorization.find("realm=\"" + expected_realm + "\""));
  2958. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2959. res.set_content("ok", "text/plain");
  2960. }
  2961. });
  2962. auto port = svr.bind_to_any_port(HOST);
  2963. std::thread t([&]() { svr.listen_after_bind(); });
  2964. auto se = detail::scope_exit([&] {
  2965. svr.stop();
  2966. t.join();
  2967. });
  2968. svr.wait_until_ready();
  2969. Client cli(HOST, port);
  2970. cli.set_digest_auth("hello", "world");
  2971. auto res = cli.Get("/x");
  2972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2973. EXPECT_EQ(2, hits.load());
  2974. }
  2975. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2976. static const char *kDigestChallenge =
  2977. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2978. "algorithm=MD5";
  2979. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2980. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2981. "testrealm");
  2982. }
  2983. // Same challenge list with the schemes in the opposite order, to make sure
  2984. // the fix above didn't just special-case "Basic first".
  2985. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2986. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2987. "testrealm");
  2988. }
  2989. // A comma inside a quoted auth-param value must not be mistaken for the
  2990. // separator between two challenges (or two auth-params).
  2991. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2992. run_digest_challenge_list_test(
  2993. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2994. "algorithm=MD5"},
  2995. "test,realm");
  2996. }
  2997. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2998. // the params and leaves out the fragment.
  2999. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3000. Server svr;
  3001. std::string uri, target;
  3002. svr.Get("/a b", [&](const Request &req, Response &res) {
  3003. auto auth = req.get_header_value("Authorization");
  3004. if (auth.empty()) {
  3005. res.status = StatusCode::Unauthorized_401;
  3006. res.set_header("WWW-Authenticate",
  3007. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3008. return;
  3009. }
  3010. auto b = auth.find("uri=\"") + 5;
  3011. uri = auth.substr(b, auth.find('"', b) - b);
  3012. target = req.target;
  3013. });
  3014. auto port = svr.bind_to_any_port(HOST);
  3015. std::thread t([&]() { svr.listen_after_bind(); });
  3016. auto se = detail::scope_exit([&] {
  3017. svr.stop();
  3018. t.join();
  3019. });
  3020. svr.wait_until_ready();
  3021. Client cli(HOST, port);
  3022. cli.set_digest_auth("hello", "world");
  3023. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3025. EXPECT_EQ("/a%20b?x=1", target);
  3026. EXPECT_EQ(target, uri);
  3027. }
  3028. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3029. // make_digest_authentication_header() dereferences both unconditionally, so
  3030. // a server sending a challenge missing either one must not be treated as
  3031. // usable -- doing so used to crash the client with std::out_of_range.
  3032. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3033. Server svr;
  3034. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3035. res.status = StatusCode::Unauthorized_401;
  3036. res.set_header("WWW-Authenticate", challenge);
  3037. });
  3038. auto port = svr.bind_to_any_port(HOST);
  3039. std::thread t([&]() { svr.listen_after_bind(); });
  3040. auto se = detail::scope_exit([&] {
  3041. svr.stop();
  3042. t.join();
  3043. });
  3044. svr.wait_until_ready();
  3045. Client cli(HOST, port);
  3046. cli.set_digest_auth("hello", "world");
  3047. auto res = cli.Get("/x");
  3048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3049. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3050. }
  3051. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3052. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3053. }
  3054. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3055. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3056. }
  3057. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3058. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3059. }
  3060. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3061. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3062. // when storing the values, so the header builder has to re-escape them (and
  3063. // keep algorithm a bare token); otherwise the value breaks out of its
  3064. // quoted-string and injects extra auth-params into the client's Authorization.
  3065. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3066. std::atomic<int> hits{0};
  3067. std::string authorization;
  3068. Server svr;
  3069. svr.Get("/x", [&](const Request &req, Response &res) {
  3070. if (++hits == 1) {
  3071. res.status = StatusCode::Unauthorized_401;
  3072. // On the wire the quotes embedded in the values are backslash-escaped.
  3073. res.set_header("WWW-Authenticate",
  3074. "Digest realm=\"testrealm\", "
  3075. "nonce=\"n\\\"; injected=\\\"x\", "
  3076. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3077. } else {
  3078. authorization = req.get_header_value("Authorization");
  3079. res.set_content("ok", "text/plain");
  3080. }
  3081. });
  3082. auto port = svr.bind_to_any_port(HOST);
  3083. std::thread t([&]() { svr.listen_after_bind(); });
  3084. auto se = detail::scope_exit([&] {
  3085. svr.stop();
  3086. t.join();
  3087. });
  3088. svr.wait_until_ready();
  3089. Client cli(HOST, port);
  3090. cli.set_digest_auth("hello", "world");
  3091. auto res = cli.Get("/x");
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. EXPECT_EQ(2, hits.load());
  3094. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3095. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3096. // inside its quoted-string rather than starting an "injected" auth-param.
  3097. EXPECT_NE(std::string::npos,
  3098. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3099. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3100. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3101. }
  3102. #endif
  3103. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3104. auto host = "google.com";
  3105. auto another_host = "example.com";
  3106. auto wrong_ip = "0.0.0.0";
  3107. #ifdef CPPHTTPLIB_SSL_ENABLED
  3108. SSLClient cli(host);
  3109. #else
  3110. Client cli(host);
  3111. #endif
  3112. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3113. auto res = cli.Get("/");
  3114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3115. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3116. }
  3117. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3118. auto host = "google.com";
  3119. auto wrong_ip = "0.0.0.0";
  3120. #ifdef CPPHTTPLIB_SSL_ENABLED
  3121. SSLClient cli(host);
  3122. #else
  3123. Client cli(host);
  3124. #endif
  3125. cli.set_hostname_addr_map({{host, wrong_ip}});
  3126. auto res = cli.Get("/");
  3127. ASSERT_TRUE(!res);
  3128. EXPECT_EQ(Error::Connection, res.error());
  3129. }
  3130. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3131. // A mapped value that is not an IP literal must be resolved. "localhost"
  3132. // resolves from the hosts file, so this test needs no external DNS.
  3133. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3134. auto host = "target.invalid";
  3135. Server svr;
  3136. std::string received_host;
  3137. svr.Get("/hi", [&](const Request &req, Response &res) {
  3138. received_host = req.get_header_value("Host");
  3139. res.set_content("Hello World!", "text/plain");
  3140. });
  3141. auto port = svr.bind_to_any_port(HOST);
  3142. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3143. auto se = detail::scope_exit([&] {
  3144. svr.stop();
  3145. thread.join();
  3146. ASSERT_FALSE(svr.is_running());
  3147. });
  3148. svr.wait_until_ready();
  3149. Client cli(host, port);
  3150. cli.set_hostname_addr_map({{host, HOST}});
  3151. auto res = cli.Get("/hi");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. // The mapping only redirects the connection; the identity stays host_.
  3155. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3156. }
  3157. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3158. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3159. auto host = "target.invalid";
  3160. Server svr;
  3161. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3162. res.set_content("Hello World!", "text/plain");
  3163. });
  3164. auto port = svr.bind_to_any_port("127.0.0.1");
  3165. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3166. auto se = detail::scope_exit([&] {
  3167. svr.stop();
  3168. thread.join();
  3169. ASSERT_FALSE(svr.is_running());
  3170. });
  3171. svr.wait_until_ready();
  3172. Client cli(host, port);
  3173. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3174. auto res = cli.Get("/hi");
  3175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3176. EXPECT_EQ(StatusCode::OK_200, res->status);
  3177. }
  3178. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3179. // An empty mapped value must leave host_ as the connection target. Without
  3180. // that guard the empty value would become the host argument, getaddrinfo
  3181. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3182. // loopback - silently connecting somewhere the caller never asked for.
  3183. // The server listens on loopback, so such a fallback would succeed and is
  3184. // therefore observable as a failure of this test.
  3185. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3186. Server svr;
  3187. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3188. res.set_content("Hello World!", "text/plain");
  3189. });
  3190. auto port = svr.bind_to_any_port(HOST);
  3191. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3192. auto se = detail::scope_exit([&] {
  3193. svr.stop();
  3194. thread.join();
  3195. ASSERT_FALSE(svr.is_running());
  3196. });
  3197. svr.wait_until_ready();
  3198. Client cli(blackhole, port);
  3199. cli.set_hostname_addr_map({{blackhole, ""}});
  3200. cli.set_connection_timeout(1);
  3201. auto res = cli.Get("/hi");
  3202. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3203. }
  3204. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3205. auto host = "httpbingo.org";
  3206. auto path = std::string{"/absolute-redirect/3"};
  3207. #ifdef CPPHTTPLIB_SSL_ENABLED
  3208. SSLClient cli(host);
  3209. #else
  3210. Client cli(host);
  3211. #endif
  3212. cli.set_follow_location(true);
  3213. auto res = cli.Get(path);
  3214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3215. EXPECT_EQ(StatusCode::OK_200, res->status);
  3216. }
  3217. TEST(RedirectTest, Redirect_Online) {
  3218. auto host = "httpbingo.org";
  3219. auto path = std::string{"/redirect/3"};
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(host);
  3222. #else
  3223. Client cli(host);
  3224. #endif
  3225. cli.set_follow_location(true);
  3226. auto res = cli.Get(path);
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. }
  3230. TEST(RelativeRedirectTest, Redirect_Online) {
  3231. auto host = "httpbingo.org";
  3232. auto path = std::string{"/relative-redirect/3"};
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. SSLClient cli(host);
  3235. #else
  3236. Client cli(host);
  3237. #endif
  3238. cli.set_follow_location(true);
  3239. auto res = cli.Get(path);
  3240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3241. EXPECT_EQ(StatusCode::OK_200, res->status);
  3242. }
  3243. TEST(TooManyRedirectTest, Redirect_Online) {
  3244. auto host = "httpbingo.org";
  3245. auto path = std::string{"/redirect/21"};
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. SSLClient cli(host);
  3248. #else
  3249. Client cli(host);
  3250. #endif
  3251. cli.set_follow_location(true);
  3252. auto res = cli.Get(path);
  3253. ASSERT_TRUE(!res);
  3254. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3255. }
  3256. #ifdef CPPHTTPLIB_SSL_ENABLED
  3257. TEST(YahooRedirectTest, Redirect_Online) {
  3258. Client cli("yahoo.com");
  3259. auto res = cli.Get("/");
  3260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3261. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3262. cli.set_follow_location(true);
  3263. res = cli.Get("/");
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3267. }
  3268. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3269. #define REDIR_HOST "httpbingo.org"
  3270. #define REDIR_PATH "/redirect-to"
  3271. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3272. SSLClient cli(REDIR_HOST);
  3273. cli.set_follow_location(true);
  3274. auto res =
  3275. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. }
  3279. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3280. SSLClient cli(REDIR_HOST);
  3281. cli.set_follow_location(true);
  3282. Params params;
  3283. params.emplace("url", "http://example.com");
  3284. params.emplace("status_code", "302");
  3285. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. }
  3289. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3290. SSLClient cli(REDIR_HOST);
  3291. cli.set_follow_location(true);
  3292. Params params;
  3293. params.emplace("url", "http://example.com");
  3294. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. }
  3298. TEST(UrlWithSpace, Redirect_Online) {
  3299. SSLClient cli("edge.forgecdn.net");
  3300. cli.set_follow_location(true);
  3301. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3303. EXPECT_EQ(StatusCode::OK_200, res->status);
  3304. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3305. }
  3306. #endif
  3307. #if !defined(_WIN32) && !defined(_WIN64)
  3308. TEST(ReceiveSignals, Signal) {
  3309. auto setupSignalHandlers = []() {
  3310. struct sigaction act;
  3311. sigemptyset(&act.sa_mask);
  3312. act.sa_flags = SA_SIGINFO;
  3313. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3314. switch (sig) {
  3315. case SIGINT:
  3316. default: break;
  3317. }
  3318. };
  3319. ::sigaction(SIGINT, &act, nullptr);
  3320. };
  3321. Server svr;
  3322. int port = 0;
  3323. auto thread = std::thread([&]() {
  3324. setupSignalHandlers();
  3325. port = svr.bind_to_any_port(HOST);
  3326. svr.listen_after_bind();
  3327. });
  3328. auto se = detail::scope_exit([&] {
  3329. svr.stop();
  3330. thread.join();
  3331. ASSERT_FALSE(svr.is_running());
  3332. });
  3333. svr.wait_until_ready();
  3334. ASSERT_TRUE(svr.is_running());
  3335. pthread_kill(thread.native_handle(), SIGINT);
  3336. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3337. ASSERT_TRUE(svr.is_running());
  3338. }
  3339. #endif
  3340. TEST(RedirectToDifferentPort, Redirect) {
  3341. Server svr1;
  3342. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3343. res.set_content("Hello World!", "text/plain");
  3344. });
  3345. int svr1_port = 0;
  3346. auto thread1 = std::thread([&]() {
  3347. svr1_port = svr1.bind_to_any_port(HOST);
  3348. svr1.listen_after_bind();
  3349. });
  3350. Server svr2;
  3351. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3352. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3353. });
  3354. int svr2_port = 0;
  3355. auto thread2 = std::thread([&]() {
  3356. svr2_port = svr2.bind_to_any_port(HOST);
  3357. svr2.listen_after_bind();
  3358. });
  3359. auto se = detail::scope_exit([&] {
  3360. svr2.stop();
  3361. thread2.join();
  3362. svr1.stop();
  3363. thread1.join();
  3364. ASSERT_FALSE(svr2.is_running());
  3365. ASSERT_FALSE(svr1.is_running());
  3366. });
  3367. svr1.wait_until_ready();
  3368. svr2.wait_until_ready();
  3369. Client cli("localhost", svr2_port);
  3370. cli.set_follow_location(true);
  3371. auto res = cli.Get("/2");
  3372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3373. EXPECT_EQ(StatusCode::OK_200, res->status);
  3374. EXPECT_EQ("Hello World!", res->body);
  3375. }
  3376. // GET /redir on one server redirects to /target on another port, so the
  3377. // client follows it with a new client.
  3378. static Result
  3379. GetThroughRedirectToDifferentPort(Server::Handler target,
  3380. const std::function<void(Client &)> &setup,
  3381. const Headers &headers = Headers()) {
  3382. Server target_svr;
  3383. target_svr.Get("/target", target);
  3384. int target_port = 0;
  3385. auto target_thread = std::thread([&]() {
  3386. target_port = target_svr.bind_to_any_port(HOST);
  3387. target_svr.listen_after_bind();
  3388. });
  3389. Server origin_svr;
  3390. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3391. res.set_redirect(
  3392. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3393. });
  3394. int origin_port = 0;
  3395. auto origin_thread = std::thread([&]() {
  3396. origin_port = origin_svr.bind_to_any_port(HOST);
  3397. origin_svr.listen_after_bind();
  3398. });
  3399. auto se = detail::scope_exit([&] {
  3400. origin_svr.stop();
  3401. origin_thread.join();
  3402. target_svr.stop();
  3403. target_thread.join();
  3404. });
  3405. target_svr.wait_until_ready();
  3406. origin_svr.wait_until_ready();
  3407. Client cli("localhost", origin_port);
  3408. cli.set_follow_location(true);
  3409. setup(cli);
  3410. return cli.Get("/redir", headers);
  3411. }
  3412. static void
  3413. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3414. std::string captured_authorization;
  3415. auto result = GetThroughRedirectToDifferentPort(
  3416. [&](const Request &req, Response &res) {
  3417. captured_authorization = req.get_header_value("Authorization");
  3418. res.set_content("OK", "text/plain");
  3419. },
  3420. set_auth);
  3421. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3422. EXPECT_EQ(StatusCode::OK_200, result->status);
  3423. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3424. EXPECT_TRUE(captured_authorization.empty());
  3425. }
  3426. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3427. TestDoNotForwardCredentialsOnRedirect(
  3428. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3429. }
  3430. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3431. TestDoNotForwardCredentialsOnRedirect(
  3432. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3433. }
  3434. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3435. std::string captured_cookie;
  3436. auto result = GetThroughRedirectToDifferentPort(
  3437. [&](const Request &req, Response &res) {
  3438. captured_cookie = req.get_header_value("Cookie");
  3439. res.set_content("OK", "text/plain");
  3440. },
  3441. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3442. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3443. EXPECT_EQ(StatusCode::OK_200, result->status);
  3444. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3445. EXPECT_TRUE(captured_cookie.empty());
  3446. }
  3447. TEST(RedirectToSamePort, ForwardCookie) {
  3448. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3449. // header so that ordinary session flows keep working.
  3450. Server svr;
  3451. std::string captured_cookie;
  3452. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3453. res.set_redirect("/target", 302);
  3454. });
  3455. svr.Get("/target", [&](const Request &req, Response &res) {
  3456. captured_cookie = req.get_header_value("Cookie");
  3457. res.set_content("OK", "text/plain");
  3458. });
  3459. auto port = svr.bind_to_any_port(HOST);
  3460. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3461. auto se = detail::scope_exit([&] {
  3462. svr.stop();
  3463. thread.join();
  3464. ASSERT_FALSE(svr.is_running());
  3465. });
  3466. svr.wait_until_ready();
  3467. Client cli(HOST, port);
  3468. cli.set_follow_location(true);
  3469. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3470. auto res = cli.Get("/redir", headers);
  3471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3472. EXPECT_EQ(StatusCode::OK_200, res->status);
  3473. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3474. }
  3475. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3476. std::string authorization;
  3477. std::string trace_id;
  3478. auto result = GetThroughRedirectToDifferentPort(
  3479. [&](const Request &req, Response &res) {
  3480. authorization = req.get_header_value("Authorization");
  3481. trace_id = req.get_header_value("X-Trace-Id");
  3482. res.set_content("OK", "text/plain");
  3483. },
  3484. [](Client &cli) {
  3485. cli.set_default_headers(
  3486. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3487. });
  3488. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3489. EXPECT_EQ(StatusCode::OK_200, result->status);
  3490. // Like a header given with the request, a default one goes along unless it
  3491. // carries credentials (RFC 9110 15.4).
  3492. EXPECT_TRUE(authorization.empty());
  3493. EXPECT_EQ("42", trace_id);
  3494. }
  3495. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3496. auto result = GetThroughRedirectToDifferentPort(
  3497. [](const Request &, Response &res) {
  3498. res.set_content(std::string(2048, 'x'), "text/plain");
  3499. },
  3500. [](Client &cli) { cli.set_payload_max_length(1024); });
  3501. EXPECT_FALSE(result);
  3502. }
  3503. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3504. auto result = GetThroughRedirectToDifferentPort(
  3505. [](const Request &req, Response &res) {
  3506. // Answer after a second, or once the client gives up.
  3507. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3508. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3509. }
  3510. res.set_content("late", "text/plain");
  3511. },
  3512. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3513. ASSERT_FALSE(result);
  3514. EXPECT_EQ(Error::Read, result.error());
  3515. }
  3516. #ifdef CPPHTTPLIB_SSL_ENABLED
  3517. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3518. auto result = GetThroughRedirectToDifferentPort(
  3519. [](const Request &, Response &res) {
  3520. res.status = StatusCode::Unauthorized_401;
  3521. res.set_header("WWW-Authenticate",
  3522. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3523. },
  3524. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3525. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3526. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3527. }
  3528. #endif
  3529. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3530. Server svr;
  3531. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3532. // Port number that overflows int — should not crash
  3533. res.set_redirect("http://localhost:99999999999999999999/target");
  3534. });
  3535. auto port = svr.bind_to_any_port(HOST);
  3536. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3537. auto se = detail::scope_exit([&] {
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. });
  3542. svr.wait_until_ready();
  3543. Client cli(HOST, port);
  3544. cli.set_follow_location(true);
  3545. auto res = cli.Get("/redir");
  3546. // Should fail gracefully, not crash (no valid response due to bad port)
  3547. EXPECT_FALSE(res);
  3548. }
  3549. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3550. Server svr;
  3551. auto port = svr.bind_to_any_port(HOST);
  3552. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3553. // The server's own port followed by junk must not be followed
  3554. res.set_redirect("http://" + std::string(HOST) + ":" +
  3555. std::to_string(port) + "junk/target");
  3556. });
  3557. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3558. res.set_content("target", "text/plain");
  3559. });
  3560. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3561. auto se = detail::scope_exit([&] {
  3562. svr.stop();
  3563. thread.join();
  3564. ASSERT_FALSE(svr.is_running());
  3565. });
  3566. svr.wait_until_ready();
  3567. Client cli(HOST, port);
  3568. cli.set_follow_location(true);
  3569. auto res = cli.Get("/redir");
  3570. EXPECT_FALSE(res);
  3571. }
  3572. TEST(RedirectFromPageWithContent, Redirect) {
  3573. Server svr;
  3574. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3575. res.set_content("___", "text/plain");
  3576. res.set_redirect("/2");
  3577. });
  3578. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3579. res.set_content("Hello World!", "text/plain");
  3580. });
  3581. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3582. auto se = detail::scope_exit([&] {
  3583. svr.stop();
  3584. th.join();
  3585. ASSERT_FALSE(svr.is_running());
  3586. });
  3587. svr.wait_until_ready();
  3588. {
  3589. Client cli("localhost", PORT);
  3590. cli.set_follow_location(true);
  3591. std::string body;
  3592. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3593. body.append(data, data_length);
  3594. return true;
  3595. });
  3596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3597. EXPECT_EQ(StatusCode::OK_200, res->status);
  3598. EXPECT_EQ("Hello World!", body);
  3599. }
  3600. {
  3601. Client cli("localhost", PORT);
  3602. std::string body;
  3603. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3604. body.append(data, data_length);
  3605. return true;
  3606. });
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ(StatusCode::Found_302, res->status);
  3609. EXPECT_EQ("___", body);
  3610. }
  3611. }
  3612. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3613. Server svr;
  3614. auto port_str = std::to_string(PORT);
  3615. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3616. auto expected_host = "[::1]:" + port_str;
  3617. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3618. res.set_content("___", "text/plain");
  3619. // res.set_redirect("/2");
  3620. res.set_redirect(redirect_url);
  3621. });
  3622. svr.Get("/2", [&](const Request &req, Response &res) {
  3623. auto host_header = req.headers.find("Host");
  3624. ASSERT_TRUE(host_header != req.headers.end());
  3625. EXPECT_EQ(expected_host, host_header->second);
  3626. res.set_content("Hello World!", "text/plain");
  3627. });
  3628. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3629. auto se = detail::scope_exit([&] {
  3630. svr.stop();
  3631. th.join();
  3632. ASSERT_FALSE(svr.is_running());
  3633. });
  3634. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3635. // actually starts anything, so the condition !svr.is_running() will
  3636. // always remain true, and the loop never stops.
  3637. // This basically counts how many milliseconds have passed since the
  3638. // call to svr.listen(), and if after 5 seconds nothing started yet
  3639. // aborts the test.
  3640. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3641. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3642. ASSERT_LT(milliseconds, 5000U);
  3643. }
  3644. {
  3645. Client cli("::1", PORT);
  3646. cli.set_follow_location(true);
  3647. std::string body;
  3648. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3649. body.append(data, data_length);
  3650. return true;
  3651. });
  3652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3653. EXPECT_EQ(StatusCode::OK_200, res->status);
  3654. EXPECT_EQ("Hello World!", body);
  3655. }
  3656. {
  3657. Client cli("::1", PORT);
  3658. std::string body;
  3659. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3660. body.append(data, data_length);
  3661. return true;
  3662. });
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::Found_302, res->status);
  3665. EXPECT_EQ("___", body);
  3666. }
  3667. }
  3668. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3669. Server svr;
  3670. svr.Get("/foo", [](const Request &req, Response &res) {
  3671. auto a = req.params.find("a");
  3672. if (a != req.params.end()) {
  3673. res.set_content((*a).second, "text/plain");
  3674. res.status = StatusCode::OK_200;
  3675. } else {
  3676. res.status = StatusCode::BadRequest_400;
  3677. }
  3678. });
  3679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3680. auto se = detail::scope_exit([&] {
  3681. svr.stop();
  3682. thread.join();
  3683. ASSERT_FALSE(svr.is_running());
  3684. });
  3685. svr.wait_until_ready();
  3686. {
  3687. Client cli(HOST, PORT);
  3688. cli.set_path_encode(false);
  3689. auto res = cli.Get("/foo?a=explicitly+encoded");
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. // This expects it back with a space, as the `+` won't have been
  3693. // url-encoded, and server-side the params get decoded turning `+`
  3694. // into spaces.
  3695. EXPECT_EQ("explicitly encoded", res->body);
  3696. }
  3697. }
  3698. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3699. // When path encoding is disabled the client must transmit the supplied
  3700. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3701. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3702. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3703. // than a space (0x20). Assert on the raw wire target to catch this.
  3704. Server svr;
  3705. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3706. svr.Get("/foo", [&](const Request &req, Response &res) {
  3707. EXPECT_EQ(expected_target, req.target);
  3708. res.status = StatusCode::OK_200;
  3709. });
  3710. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3711. auto se = detail::scope_exit([&] {
  3712. svr.stop();
  3713. thread.join();
  3714. ASSERT_FALSE(svr.is_running());
  3715. });
  3716. svr.wait_until_ready();
  3717. {
  3718. Client cli(HOST, PORT);
  3719. cli.set_path_encode(false);
  3720. auto res = cli.Get(expected_target.c_str());
  3721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3722. EXPECT_EQ(StatusCode::OK_200, res->status);
  3723. }
  3724. }
  3725. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3726. // `open_stream()` used to skip the path encoding that the buffered send
  3727. // path applies, so the same `path` produced different bytes in the request
  3728. // line depending on which API was used. Assert the two agree.
  3729. Server svr;
  3730. std::string target;
  3731. svr.Get(".*", [&](const Request &req, Response &res) {
  3732. target = req.target;
  3733. res.status = StatusCode::OK_200;
  3734. });
  3735. auto port = svr.bind_to_any_port(HOST);
  3736. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3737. auto se = detail::scope_exit([&] {
  3738. svr.stop();
  3739. thread.join();
  3740. ASSERT_FALSE(svr.is_running());
  3741. });
  3742. svr.wait_until_ready();
  3743. struct {
  3744. const char *path;
  3745. const char *expected;
  3746. } cases[] = {
  3747. {"/a b?x=1", "/a%20b?x=1"},
  3748. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3749. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3750. };
  3751. for (const auto &c : cases) {
  3752. Client cli(HOST, port);
  3753. target.clear();
  3754. auto res = cli.Get(c.path);
  3755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3756. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3757. auto buffered_target = target;
  3758. target.clear();
  3759. auto handle = cli.open_stream("GET", c.path);
  3760. EXPECT_TRUE(handle.is_valid())
  3761. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3762. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3763. }
  3764. }
  3765. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3766. // The `set_path_encode(false)` contract — transmit the supplied target
  3767. // verbatim — must hold for the streaming API too.
  3768. Server svr;
  3769. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3770. std::string target;
  3771. svr.Get("/foo", [&](const Request &req, Response &res) {
  3772. target = req.target;
  3773. res.status = StatusCode::OK_200;
  3774. });
  3775. auto port = svr.bind_to_any_port(HOST);
  3776. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3777. auto se = detail::scope_exit([&] {
  3778. svr.stop();
  3779. thread.join();
  3780. ASSERT_FALSE(svr.is_running());
  3781. });
  3782. svr.wait_until_ready();
  3783. {
  3784. Client cli(HOST, port);
  3785. cli.set_path_encode(false);
  3786. auto handle = cli.open_stream("GET", expected_target);
  3787. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3788. EXPECT_EQ(expected_target, target);
  3789. }
  3790. }
  3791. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3792. // With path encoding enabled a CR/LF in the target is percent-encoded
  3793. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3794. // write_request_line still backstops `set_path_encode(false)`, which is
  3795. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3796. Server svr;
  3797. // Captured before routing: the decoded path contains a newline, which a
  3798. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3799. std::string target;
  3800. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3801. target = req.target;
  3802. res.status = StatusCode::OK_200;
  3803. return Server::HandlerResponse::Handled;
  3804. });
  3805. auto port = svr.bind_to_any_port(HOST);
  3806. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3807. auto se = detail::scope_exit([&] {
  3808. svr.stop();
  3809. thread.join();
  3810. ASSERT_FALSE(svr.is_running());
  3811. });
  3812. svr.wait_until_ready();
  3813. {
  3814. Client cli(HOST, port);
  3815. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3816. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3817. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3818. }
  3819. }
  3820. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3821. // Every control character is percent-encoded, not just CR/LF, so the target
  3822. // passes the request-target check in write_request_line.
  3823. Server svr;
  3824. std::string target;
  3825. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3826. target = req.target;
  3827. res.status = StatusCode::OK_200;
  3828. return Server::HandlerResponse::Handled;
  3829. });
  3830. auto port = svr.bind_to_any_port(HOST);
  3831. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3832. auto se = detail::scope_exit([&] {
  3833. svr.stop();
  3834. thread.join();
  3835. ASSERT_FALSE(svr.is_running());
  3836. });
  3837. svr.wait_until_ready();
  3838. {
  3839. Client cli(HOST, port);
  3840. auto res = cli.Get("/a\tb\x1b\x7f");
  3841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3842. EXPECT_EQ("/a%09b%1B%7F", target);
  3843. }
  3844. }
  3845. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3846. // Nothing may reach the wire: a raw CR/LF target would split the request
  3847. // line and inject headers.
  3848. Server svr;
  3849. // Pre-routing so that "not called" means nothing reached the server at all,
  3850. // rather than merely failing to match a handler pattern.
  3851. auto handler_called = false;
  3852. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3853. handler_called = true;
  3854. res.status = StatusCode::OK_200;
  3855. return Server::HandlerResponse::Handled;
  3856. });
  3857. auto port = svr.bind_to_any_port(HOST);
  3858. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3859. auto se = detail::scope_exit([&] {
  3860. svr.stop();
  3861. thread.join();
  3862. ASSERT_FALSE(svr.is_running());
  3863. });
  3864. svr.wait_until_ready();
  3865. {
  3866. Client cli(HOST, port);
  3867. cli.set_path_encode(false);
  3868. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3869. EXPECT_FALSE(handle.is_valid());
  3870. EXPECT_EQ(Error::Write, handle.error);
  3871. EXPECT_FALSE(handler_called);
  3872. }
  3873. }
  3874. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3875. // Which of the two branches runs is decided by whether the query component
  3876. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3877. // an empty query and must still fall back to building one from
  3878. // `req.params`, while a non-empty query must win over `req.params`.
  3879. Server svr;
  3880. std::string target;
  3881. svr.Get("/foo", [&](const Request &req, Response &res) {
  3882. target = req.target;
  3883. res.status = StatusCode::OK_200;
  3884. });
  3885. auto port = svr.bind_to_any_port(HOST);
  3886. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3887. auto se = detail::scope_exit([&] {
  3888. svr.stop();
  3889. thread.join();
  3890. ASSERT_FALSE(svr.is_running());
  3891. });
  3892. svr.wait_until_ready();
  3893. {
  3894. // Trailing `?` -> empty query component -> `req.params` is used.
  3895. Client cli(HOST, port);
  3896. Request req;
  3897. req.method = "GET";
  3898. req.path = "/foo?";
  3899. req.params.emplace("a", "1");
  3900. target.clear();
  3901. auto res = cli.send(req);
  3902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3903. EXPECT_EQ("/foo?a=1", target);
  3904. }
  3905. {
  3906. // Non-empty query in `req.path` -> `req.params` is not appended.
  3907. Client cli(HOST, port);
  3908. Request req;
  3909. req.method = "GET";
  3910. req.path = "/foo?b=2";
  3911. req.params.emplace("a", "1");
  3912. target.clear();
  3913. auto res = cli.send(req);
  3914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3915. EXPECT_EQ("/foo?b=2", target);
  3916. }
  3917. }
  3918. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3919. Server svr;
  3920. svr.Get("/", [](const Request &req, Response &) {
  3921. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3922. });
  3923. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3924. auto se = detail::scope_exit([&] {
  3925. svr.stop();
  3926. thread.join();
  3927. ASSERT_FALSE(svr.is_running());
  3928. });
  3929. svr.wait_until_ready();
  3930. {
  3931. Client cli(HOST, PORT);
  3932. cli.set_path_encode(false);
  3933. auto res = cli.Get("/?something=%0A");
  3934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3935. EXPECT_EQ(StatusCode::OK_200, res->status);
  3936. }
  3937. }
  3938. TEST(BindServerTest, BindDualStack) {
  3939. Server svr;
  3940. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3941. res.set_content("Hello World!", "text/plain");
  3942. });
  3943. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3944. auto se = detail::scope_exit([&] {
  3945. svr.stop();
  3946. thread.join();
  3947. ASSERT_FALSE(svr.is_running());
  3948. });
  3949. svr.wait_until_ready();
  3950. {
  3951. Client cli("127.0.0.1", PORT);
  3952. auto res = cli.Get("/1");
  3953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. {
  3958. Client cli("::1", PORT);
  3959. auto res = cli.Get("/1");
  3960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3961. EXPECT_EQ(StatusCode::OK_200, res->status);
  3962. EXPECT_EQ("Hello World!", res->body);
  3963. }
  3964. }
  3965. TEST(BindServerTest, BindAndListenSeparately) {
  3966. Server svr;
  3967. int port = svr.bind_to_any_port("0.0.0.0");
  3968. ASSERT_TRUE(svr.is_valid());
  3969. ASSERT_TRUE(port > 0);
  3970. svr.stop();
  3971. }
  3972. // Reports whether anything is still listening on a loopback port. A plain
  3973. // connect() is used instead of a Client request because a socket left bound by
  3974. // mistake accepts the connection into its backlog and never answers, which
  3975. // would hang the test instead of failing it.
  3976. static bool is_loopback_port_accepting(int port) {
  3977. sockaddr_in addr{};
  3978. addr.sin_family = AF_INET;
  3979. addr.sin_port = htons(static_cast<uint16_t>(port));
  3980. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3981. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3982. EXPECT_NE(sock, INVALID_SOCKET);
  3983. if (sock == INVALID_SOCKET) { return false; }
  3984. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3985. static_cast<socklen_t>(sizeof(addr)));
  3986. detail::close_socket(sock);
  3987. return ret == 0;
  3988. }
  3989. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3990. Server svr;
  3991. auto port = svr.bind_to_any_port("127.0.0.1");
  3992. ASSERT_TRUE(port > 0);
  3993. svr.stop();
  3994. // bind_to_any_port() already called listen(2), so until stop() closed the
  3995. // descriptor the port kept accepting connections into the backlog. ASSERT
  3996. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3997. // below blocks forever in the accept loop.
  3998. ASSERT_FALSE(is_loopback_port_accepting(port));
  3999. // Nothing is left to accept on, so listen_after_bind() must report failure
  4000. // instead of returning success without ever serving.
  4001. EXPECT_FALSE(svr.listen_after_bind());
  4002. // The failed listen marks the server decommissioned, so a waiter returns
  4003. // instead of spinning forever.
  4004. svr.wait_until_ready();
  4005. }
  4006. #ifdef CPPHTTPLIB_SSL_ENABLED
  4007. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4009. CLIENT_CA_CERT_DIR);
  4010. int port = svr.bind_to_any_port("0.0.0.0");
  4011. ASSERT_TRUE(svr.is_valid());
  4012. ASSERT_TRUE(port > 0);
  4013. svr.stop();
  4014. }
  4015. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4016. // or a rejected CustomRoute() registration would not stop the server binding.
  4017. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4019. CLIENT_CA_CERT_DIR);
  4020. ASSERT_TRUE(svr.is_valid());
  4021. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4022. EXPECT_FALSE(svr.is_valid());
  4023. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4024. }
  4025. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4026. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4027. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4028. int port = svr.bind_to_any_port("0.0.0.0");
  4029. ASSERT_TRUE(svr.is_valid());
  4030. ASSERT_TRUE(port > 0);
  4031. svr.stop();
  4032. }
  4033. TEST(BindServerTest, UpdateCertsPem) {
  4034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4035. int port = svr.bind_to_any_port("0.0.0.0");
  4036. ASSERT_TRUE(svr.is_valid());
  4037. ASSERT_TRUE(port > 0);
  4038. // Read PEM files
  4039. std::string cert_pem, key_pem, ca_pem;
  4040. read_file(SERVER_CERT_FILE, cert_pem);
  4041. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4042. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4043. // Update server certificates using PEM API
  4044. ASSERT_TRUE(
  4045. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4046. ASSERT_TRUE(svr.is_valid());
  4047. svr.stop();
  4048. }
  4049. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4050. // Start server with client CA (enables client auth)
  4051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4052. ASSERT_TRUE(svr.is_valid());
  4053. bool handler_called = false;
  4054. svr.Get("/test", [&](const Request &req, Response &res) {
  4055. handler_called = true;
  4056. // Verify client certificate is present
  4057. auto cert = req.peer_cert();
  4058. EXPECT_TRUE(static_cast<bool>(cert));
  4059. res.set_content("ok", "text/plain");
  4060. });
  4061. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4062. auto se = detail::scope_exit([&] {
  4063. svr.stop();
  4064. t.join();
  4065. ASSERT_FALSE(svr.is_running());
  4066. });
  4067. svr.wait_until_ready();
  4068. // Read PEM files
  4069. std::string cert_pem, key_pem, ca_pem;
  4070. read_file(SERVER_CERT_FILE, cert_pem);
  4071. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4072. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4073. // Update server certificates and client CA using PEM API while server running
  4074. ASSERT_TRUE(
  4075. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4076. // Connect with client certificate
  4077. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4078. cli.enable_server_certificate_verification(false);
  4079. cli.set_connection_timeout(30);
  4080. auto res = cli.Get("/test");
  4081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4082. ASSERT_EQ(StatusCode::OK_200, res->status);
  4083. ASSERT_TRUE(handler_called);
  4084. EXPECT_EQ("ok", res->body);
  4085. }
  4086. // Puts a CA that did not sign the client's certificate in the old one's place.
  4087. static bool replace_client_ca(SSLServer &svr) {
  4088. std::string cert_pem, key_pem, ca_pem;
  4089. read_file(SERVER_CERT_FILE, cert_pem);
  4090. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4091. read_file(SERVER_CERT2_FILE, ca_pem);
  4092. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4093. ca_pem.c_str());
  4094. }
  4095. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4097. ASSERT_TRUE(svr.is_valid());
  4098. svr.Get("/test", [](const Request &, Response &res) {
  4099. res.set_content("ok", "text/plain");
  4100. });
  4101. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4102. auto se = detail::scope_exit([&] {
  4103. svr.stop();
  4104. t.join();
  4105. ASSERT_FALSE(svr.is_running());
  4106. });
  4107. svr.wait_until_ready();
  4108. auto get = [] {
  4109. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4110. cli.enable_server_certificate_verification(false);
  4111. return cli.Get("/test");
  4112. };
  4113. ASSERT_TRUE(get());
  4114. ASSERT_TRUE(replace_client_ca(svr));
  4115. EXPECT_FALSE(get());
  4116. }
  4117. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4118. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4119. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4120. ASSERT_TRUE(svr.is_valid());
  4121. tls::set_verify_callback(svr.tls_context(),
  4122. [](const tls::VerifyContext &) -> bool {
  4123. throw std::runtime_error("verify");
  4124. });
  4125. svr.Get("/test", [](const Request &, Response &res) {
  4126. res.set_content("ok", "text/plain");
  4127. });
  4128. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4129. auto se = detail::scope_exit([&] {
  4130. svr.stop();
  4131. t.join();
  4132. ASSERT_FALSE(svr.is_running());
  4133. });
  4134. svr.wait_until_ready();
  4135. auto get = [] {
  4136. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4137. cli.enable_server_certificate_verification(false);
  4138. return cli.Get("/test");
  4139. };
  4140. EXPECT_FALSE(get());
  4141. // The handshake is over, so an update does not wait for it.
  4142. std::string cert_pem, key_pem;
  4143. read_file(SERVER_CERT_FILE, cert_pem);
  4144. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4145. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4146. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4147. return v.preverify_ok;
  4148. });
  4149. auto res = get();
  4150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4151. EXPECT_EQ("ok", res->body);
  4152. }
  4153. #endif
  4154. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4155. // Sends each request over a new connection with a client certificate,
  4156. // resuming the session of the one before when there is one.
  4157. class ResumingClient {
  4158. public:
  4159. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4160. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4161. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4162. SSL_FILETYPE_PEM);
  4163. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4164. // callback, not through SSL_get1_session().
  4165. SSL_CTX_set_app_data(ctx_, this);
  4166. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4167. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4168. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4169. auto self = static_cast<ResumingClient *>(
  4170. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4171. SSL_SESSION_free(self->session_);
  4172. self->session_ = session;
  4173. return 1; // Keeps the reference
  4174. });
  4175. }
  4176. ~ResumingClient() {
  4177. SSL_SESSION_free(session_);
  4178. SSL_CTX_free(ctx_);
  4179. }
  4180. // Tells whether the request was answered.
  4181. bool get() {
  4182. auto error = Error::Success;
  4183. auto sock = detail::create_client_socket(
  4184. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4185. /*connection_timeout_sec=*/5, 0,
  4186. /*read_timeout_sec=*/5, 0,
  4187. /*write_timeout_sec=*/5, 0, std::string(), error);
  4188. if (sock == INVALID_SOCKET) { return false; }
  4189. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4190. auto ssl = SSL_new(ctx_);
  4191. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4192. SSL_set_fd(ssl, static_cast<int>(sock));
  4193. if (session_) { SSL_set_session(ssl, session_); }
  4194. if (SSL_connect(ssl) != 1) { return false; }
  4195. reused_ = SSL_session_reused(ssl) == 1;
  4196. // Reading the response also takes in a TLS 1.3 session ticket.
  4197. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4198. "Connection: close\r\n\r\n";
  4199. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4200. std::string res;
  4201. char buf[256];
  4202. int n;
  4203. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4204. res.append(buf, static_cast<size_t>(n));
  4205. }
  4206. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4207. SSL_shutdown(ssl);
  4208. return res.find("200 OK") != std::string::npos;
  4209. }
  4210. // Whether the last connection resumed a session
  4211. bool reused() const { return reused_; }
  4212. private:
  4213. SSL_CTX *ctx_;
  4214. SSL_SESSION *session_ = nullptr;
  4215. bool reused_ = false;
  4216. };
  4217. // A client that resumes its session gets through, but not once the client CA
  4218. // has changed, as a resumed session does not show the certificate again.
  4219. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4221. ASSERT_TRUE(svr.is_valid());
  4222. svr.Get("/test", [](const Request &, Response &res) {
  4223. res.set_content("ok", "text/plain");
  4224. });
  4225. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4226. auto se = detail::scope_exit([&] {
  4227. svr.stop();
  4228. t.join();
  4229. ASSERT_FALSE(svr.is_running());
  4230. });
  4231. svr.wait_until_ready();
  4232. ResumingClient cli;
  4233. ASSERT_TRUE(cli.get());
  4234. ASSERT_TRUE(cli.get());
  4235. EXPECT_TRUE(cli.reused());
  4236. ASSERT_TRUE(replace_client_ca(svr));
  4237. EXPECT_FALSE(cli.get());
  4238. }
  4239. // A resumed session does not show the certificate again, so the server does
  4240. // not resume one with a verify callback to run on it.
  4241. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4242. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4243. ASSERT_TRUE(svr.is_valid());
  4244. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4245. return v.preverify_ok;
  4246. });
  4247. svr.Get("/test", [](const Request &, Response &res) {
  4248. res.set_content("ok", "text/plain");
  4249. });
  4250. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4251. auto se = detail::scope_exit([&] {
  4252. svr.stop();
  4253. t.join();
  4254. ASSERT_FALSE(svr.is_running());
  4255. });
  4256. svr.wait_until_ready();
  4257. ResumingClient cli;
  4258. ASSERT_TRUE(cli.get());
  4259. ASSERT_TRUE(cli.get());
  4260. EXPECT_FALSE(cli.reused());
  4261. }
  4262. #endif
  4263. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4264. // wolfSSL shares its session cache between contexts, so a resumed session
  4265. // could carry a client certificate checked against another server's CA, or
  4266. // against a client CA since replaced.
  4267. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4269. ASSERT_TRUE(svr.is_valid());
  4270. // Trusts a CA that did not sign the client's certificate.
  4271. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4272. ASSERT_TRUE(other.is_valid());
  4273. for (auto s : {&svr, &other}) {
  4274. s->Get("/test", [](const Request &, Response &res) {
  4275. res.set_content("ok", "text/plain");
  4276. });
  4277. }
  4278. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4279. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4280. auto se = detail::scope_exit([&] {
  4281. other.stop();
  4282. svr.stop();
  4283. t2.join();
  4284. t.join();
  4285. });
  4286. svr.wait_until_ready();
  4287. other.wait_until_ready();
  4288. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4289. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4290. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4291. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4292. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4293. ASSERT_EQ(WOLFSSL_SUCCESS,
  4294. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4295. WOLFSSL_FILETYPE_PEM));
  4296. WOLFSSL_SESSION *session = nullptr;
  4297. auto session_se = detail::scope_exit([&] {
  4298. if (session) { wolfSSL_SESSION_free(session); }
  4299. });
  4300. // A request over a new connection, resuming `session` when there is one and
  4301. // keeping the connection's own in its place. Tells whether it was answered.
  4302. auto get = [&](int port) {
  4303. auto error = Error::Success;
  4304. auto sock = detail::create_client_socket(
  4305. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4306. /*connection_timeout_sec=*/5, 0,
  4307. /*read_timeout_sec=*/5, 0,
  4308. /*write_timeout_sec=*/5, 0, std::string(), error);
  4309. if (sock == INVALID_SOCKET) { return false; }
  4310. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4311. auto ssl = wolfSSL_new(ctx);
  4312. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4313. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4314. if (session) { wolfSSL_set_session(ssl, session); }
  4315. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4316. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4317. "Connection: close\r\n\r\n";
  4318. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4319. std::string res;
  4320. char buf[256];
  4321. int n;
  4322. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4323. res.append(buf, static_cast<size_t>(n));
  4324. }
  4325. wolfSSL_shutdown(ssl);
  4326. if (session) { wolfSSL_SESSION_free(session); }
  4327. session = wolfSSL_get1_session(ssl);
  4328. return res.find("200 OK") != std::string::npos;
  4329. };
  4330. ASSERT_TRUE(get(PORT));
  4331. EXPECT_FALSE(get(PORT + 1));
  4332. ASSERT_TRUE(get(PORT));
  4333. ASSERT_TRUE(replace_client_ca(svr));
  4334. EXPECT_FALSE(get(PORT));
  4335. }
  4336. #endif
  4337. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4339. ASSERT_TRUE(svr.is_valid());
  4340. svr.Get("/test", [](const Request &, Response &res) {
  4341. res.set_content("ok", "text/plain");
  4342. });
  4343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4344. auto se = detail::scope_exit([&] {
  4345. svr.stop();
  4346. t.join();
  4347. ASSERT_FALSE(svr.is_running());
  4348. });
  4349. svr.wait_until_ready();
  4350. // A connection that sends no ClientHello keeps its handshake in progress,
  4351. // once the server has had a moment to start it.
  4352. auto error = Error::Success;
  4353. auto sock = detail::create_client_socket(
  4354. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4355. /*connection_timeout_sec=*/5, 0,
  4356. /*read_timeout_sec=*/5, 0,
  4357. /*write_timeout_sec=*/5, 0, std::string(), error);
  4358. ASSERT_NE(INVALID_SOCKET, sock);
  4359. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4360. std::string cert_pem, key_pem;
  4361. read_file(SERVER_CERT_FILE, cert_pem);
  4362. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4363. auto update = std::async(std::launch::async, [&]() {
  4364. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4365. });
  4366. EXPECT_EQ(std::future_status::timeout,
  4367. update.wait_for(std::chrono::milliseconds(200)));
  4368. detail::close_socket(sock);
  4369. EXPECT_TRUE(update.get());
  4370. SSLClient cli(HOST, PORT);
  4371. cli.enable_server_certificate_verification(false);
  4372. auto res = cli.Get("/test");
  4373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4374. EXPECT_EQ(StatusCode::OK_200, res->status);
  4375. }
  4376. #endif
  4377. TEST(ErrorHandlerTest, ContentLength) {
  4378. Server svr;
  4379. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4380. res.status = StatusCode::OK_200;
  4381. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4382. "text/html"); // <= Content-Length still 13
  4383. });
  4384. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4385. res.set_content("Hello World!\n", "text/plain");
  4386. res.status = 524;
  4387. });
  4388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4389. auto se = detail::scope_exit([&] {
  4390. svr.stop();
  4391. thread.join();
  4392. ASSERT_FALSE(svr.is_running());
  4393. });
  4394. svr.wait_until_ready();
  4395. {
  4396. Client cli(HOST, PORT);
  4397. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4399. EXPECT_EQ(StatusCode::OK_200, res->status);
  4400. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4401. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4402. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4403. }
  4404. }
  4405. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4406. TEST(ExceptionTest, WithoutExceptionHandler) {
  4407. Server svr;
  4408. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4409. throw std::runtime_error("exception...");
  4410. });
  4411. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4412. throw std::runtime_error("exception\r\n...");
  4413. });
  4414. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4415. auto se = detail::scope_exit([&] {
  4416. svr.stop();
  4417. listen_thread.join();
  4418. ASSERT_FALSE(svr.is_running());
  4419. });
  4420. svr.wait_until_ready();
  4421. Client cli("localhost", PORT);
  4422. {
  4423. auto res = cli.Get("/exception");
  4424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4425. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4426. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4427. }
  4428. {
  4429. auto res = cli.Get("/unknown");
  4430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4431. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4432. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4433. }
  4434. }
  4435. TEST(ExceptionTest, WithExceptionHandler) {
  4436. Server svr;
  4437. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4438. std::exception_ptr ep) {
  4439. EXPECT_FALSE(ep == nullptr);
  4440. try {
  4441. std::rethrow_exception(ep);
  4442. } catch (std::exception &e) {
  4443. EXPECT_EQ("abc", std::string(e.what()));
  4444. } catch (...) {}
  4445. res.status = StatusCode::InternalServerError_500;
  4446. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4447. "text/html"); // <= Content-Length still 13 at this point
  4448. });
  4449. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4450. res.set_content("Hello World!\n", "text/plain");
  4451. throw std::runtime_error("abc");
  4452. });
  4453. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4454. auto se = detail::scope_exit([&] {
  4455. svr.stop();
  4456. thread.join();
  4457. ASSERT_FALSE(svr.is_running());
  4458. });
  4459. svr.wait_until_ready();
  4460. for (size_t i = 0; i < 10; i++) {
  4461. Client cli(HOST, PORT);
  4462. for (size_t j = 0; j < 100; j++) {
  4463. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4465. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4466. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4467. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4468. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4469. }
  4470. cli.set_keep_alive(true);
  4471. for (size_t j = 0; j < 100; j++) {
  4472. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4474. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4475. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4476. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4477. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4478. }
  4479. }
  4480. }
  4481. TEST(ExceptionTest, AndErrorHandler) {
  4482. Server svr;
  4483. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4484. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4485. });
  4486. svr.set_exception_handler(
  4487. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4488. EXPECT_FALSE(ep == nullptr);
  4489. try {
  4490. std::rethrow_exception(ep);
  4491. } catch (std::exception &e) {
  4492. res.set_content(e.what(), "text/html");
  4493. } catch (...) {}
  4494. res.status = StatusCode::InternalServerError_500;
  4495. });
  4496. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4497. throw std::runtime_error("EXCEPTION");
  4498. });
  4499. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4500. res.set_content("ERROR", "text/html");
  4501. res.status = StatusCode::InternalServerError_500;
  4502. });
  4503. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4504. auto se = detail::scope_exit([&] {
  4505. svr.stop();
  4506. thread.join();
  4507. ASSERT_FALSE(svr.is_running());
  4508. });
  4509. svr.wait_until_ready();
  4510. Client cli(HOST, PORT);
  4511. {
  4512. auto res = cli.Get("/exception");
  4513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4514. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4515. EXPECT_EQ("EXCEPTION", res->body);
  4516. }
  4517. {
  4518. auto res = cli.Get("/error");
  4519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4520. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4521. EXPECT_EQ("ERROR", res->body);
  4522. }
  4523. {
  4524. auto res = cli.Get("/invalid");
  4525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4527. EXPECT_EQ("NOT_FOUND", res->body);
  4528. }
  4529. }
  4530. #endif
  4531. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4532. // process_request() wraps only routing() in a try/catch, so an exception from
  4533. // any other user callback used to unwind into the task queue - which does not
  4534. // catch - and terminate the process. Each test below runs the server on a
  4535. // single worker thread: a guard that catches the exception but still loses the
  4536. // thread would otherwise be hidden by a spare worker serving the follow-up
  4537. // request. Note that a regression here aborts the whole test binary rather
  4538. // than failing one test.
  4539. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4540. Server svr;
  4541. svr.new_task_queue = [] { return new ThreadPool(1); };
  4542. std::atomic<int> reported{0};
  4543. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4544. if (err == Error::UserCallbackException) { reported++; }
  4545. });
  4546. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4547. res.set_content_provider(
  4548. 1024, "text/plain",
  4549. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4550. sink.write("hello", 5);
  4551. throw std::runtime_error("from the content provider");
  4552. });
  4553. });
  4554. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4555. res.set_content("ok", "text/plain");
  4556. });
  4557. auto port = svr.bind_to_any_port(HOST);
  4558. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4559. auto se = detail::scope_exit([&] {
  4560. svr.stop();
  4561. listen_thread.join();
  4562. ASSERT_FALSE(svr.is_running());
  4563. });
  4564. svr.wait_until_ready();
  4565. {
  4566. Client cli(HOST, port);
  4567. cli.set_read_timeout(5, 0);
  4568. EXPECT_FALSE(cli.Get("/throw"));
  4569. }
  4570. EXPECT_TRUE(svr.is_running());
  4571. EXPECT_EQ(1, reported.load());
  4572. // A request on a fresh connection is still served.
  4573. {
  4574. Client cli(HOST, port);
  4575. auto res = cli.Get("/ok");
  4576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4577. EXPECT_EQ(StatusCode::OK_200, res->status);
  4578. EXPECT_EQ("ok", res->body);
  4579. }
  4580. }
  4581. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4582. Server svr;
  4583. svr.new_task_queue = [] { return new ThreadPool(1); };
  4584. std::atomic<bool> should_throw{true};
  4585. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4586. res.set_content("hi", "text/plain");
  4587. });
  4588. svr.set_post_routing_handler(
  4589. [&](const Request & /*req*/, Response & /*res*/) {
  4590. if (should_throw) {
  4591. throw std::runtime_error("from the post-routing handler");
  4592. }
  4593. });
  4594. auto port = svr.bind_to_any_port(HOST);
  4595. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4596. auto se = detail::scope_exit([&] {
  4597. svr.stop();
  4598. listen_thread.join();
  4599. ASSERT_FALSE(svr.is_running());
  4600. });
  4601. svr.wait_until_ready();
  4602. {
  4603. Client cli(HOST, port);
  4604. cli.set_read_timeout(5, 0);
  4605. EXPECT_FALSE(cli.Get("/hi"));
  4606. }
  4607. EXPECT_TRUE(svr.is_running());
  4608. should_throw = false;
  4609. {
  4610. Client cli(HOST, port);
  4611. auto res = cli.Get("/hi");
  4612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("hi", res->body);
  4615. }
  4616. }
  4617. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4618. // The guard reports the caught exception through the error logger, which is
  4619. // a user callback too. A logger that throws has to be contained as well, or
  4620. // the process would terminate from inside the catch.
  4621. Server svr;
  4622. svr.new_task_queue = [] { return new ThreadPool(1); };
  4623. std::atomic<int> reported{0};
  4624. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4625. if (err == Error::UserCallbackException) {
  4626. reported++;
  4627. throw std::runtime_error("from the error logger");
  4628. }
  4629. });
  4630. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4631. res.set_content_provider(
  4632. 1024, "text/plain",
  4633. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4634. sink.write("hello", 5);
  4635. throw std::runtime_error("from the content provider");
  4636. });
  4637. });
  4638. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4639. res.set_content("ok", "text/plain");
  4640. });
  4641. auto port = svr.bind_to_any_port(HOST);
  4642. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4643. auto se = detail::scope_exit([&] {
  4644. svr.stop();
  4645. listen_thread.join();
  4646. ASSERT_FALSE(svr.is_running());
  4647. });
  4648. svr.wait_until_ready();
  4649. {
  4650. Client cli(HOST, port);
  4651. cli.set_read_timeout(5, 0);
  4652. EXPECT_FALSE(cli.Get("/throw"));
  4653. }
  4654. EXPECT_TRUE(svr.is_running());
  4655. EXPECT_EQ(1, reported.load());
  4656. {
  4657. Client cli(HOST, port);
  4658. auto res = cli.Get("/ok");
  4659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4660. EXPECT_EQ(StatusCode::OK_200, res->status);
  4661. EXPECT_EQ("ok", res->body);
  4662. }
  4663. }
  4664. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4665. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4666. // so the exception unwinds through the ws::WebSocket object on its way to
  4667. // the guard. None of the HTTP cases above cross that.
  4668. Server svr;
  4669. svr.new_task_queue = [] { return new ThreadPool(1); };
  4670. std::atomic<int> reported{0};
  4671. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4672. if (err == Error::UserCallbackException) { reported++; }
  4673. });
  4674. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4675. throw std::runtime_error("from the WebSocket handler");
  4676. });
  4677. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4678. res.set_content("ok", "text/plain");
  4679. });
  4680. auto port = svr.bind_to_any_port(HOST);
  4681. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4682. auto se = detail::scope_exit([&] {
  4683. svr.stop();
  4684. listen_thread.join();
  4685. ASSERT_FALSE(svr.is_running());
  4686. });
  4687. svr.wait_until_ready();
  4688. {
  4689. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4690. "/ws");
  4691. auto res = client.connect();
  4692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4693. // The server dropped the connection instead of dying.
  4694. std::string msg;
  4695. EXPECT_FALSE(client.read(msg));
  4696. client.close();
  4697. }
  4698. EXPECT_TRUE(svr.is_running());
  4699. EXPECT_EQ(1, reported.load());
  4700. {
  4701. Client cli(HOST, port);
  4702. auto res = cli.Get("/ok");
  4703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4704. EXPECT_EQ(StatusCode::OK_200, res->status);
  4705. EXPECT_EQ("ok", res->body);
  4706. }
  4707. }
  4708. #ifdef CPPHTTPLIB_SSL_ENABLED
  4709. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4710. // SSLServer::process_and_close_socket() is a separate overload with its own
  4711. // guard, so it is exercised on its own.
  4712. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4713. ASSERT_TRUE(svr.is_valid());
  4714. svr.new_task_queue = [] { return new ThreadPool(1); };
  4715. std::atomic<int> reported{0};
  4716. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4717. if (err == Error::UserCallbackException) { reported++; }
  4718. });
  4719. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4720. res.set_content_provider(
  4721. 1024, "text/plain",
  4722. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4723. sink.write("hello", 5);
  4724. throw std::runtime_error("from the content provider");
  4725. });
  4726. });
  4727. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4728. res.set_content("ok", "text/plain");
  4729. });
  4730. auto port = svr.bind_to_any_port(HOST);
  4731. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4732. auto se = detail::scope_exit([&] {
  4733. svr.stop();
  4734. listen_thread.join();
  4735. ASSERT_FALSE(svr.is_running());
  4736. });
  4737. svr.wait_until_ready();
  4738. {
  4739. SSLClient cli(HOST, port);
  4740. cli.enable_server_certificate_verification(false);
  4741. cli.set_read_timeout(5, 0);
  4742. EXPECT_FALSE(cli.Get("/throw"));
  4743. }
  4744. EXPECT_TRUE(svr.is_running());
  4745. EXPECT_EQ(1, reported.load());
  4746. {
  4747. SSLClient cli(HOST, port);
  4748. cli.enable_server_certificate_verification(false);
  4749. auto res = cli.Get("/ok");
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::OK_200, res->status);
  4752. EXPECT_EQ("ok", res->body);
  4753. }
  4754. }
  4755. #endif
  4756. #endif
  4757. TEST(NoContentTest, ContentLength) {
  4758. Server svr;
  4759. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4760. res.status = StatusCode::NoContent_204;
  4761. });
  4762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4763. auto se = detail::scope_exit([&] {
  4764. svr.stop();
  4765. thread.join();
  4766. ASSERT_FALSE(svr.is_running());
  4767. });
  4768. svr.wait_until_ready();
  4769. {
  4770. Client cli(HOST, PORT);
  4771. auto res = cli.Get("/hi");
  4772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4773. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4774. // RFC 9110 8.6: none in a 204 response
  4775. EXPECT_FALSE(res->has_header("Content-Length"));
  4776. }
  4777. }
  4778. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4779. Server svr;
  4780. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4781. res.set_header("Content-Length", "5");
  4782. res.set_content("hello world", "text/plain");
  4783. });
  4784. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4785. // A body that reads as the last chunk, were it taken as chunked
  4786. res.set_header("Transfer-Encoding", "chunked");
  4787. res.set_content("0\r\n\r\n", "text/plain");
  4788. });
  4789. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4790. res.set_header("Content-Length", "2");
  4791. res.set_content_provider(5, "text/plain",
  4792. [](size_t offset, size_t length, DataSink &sink) {
  4793. sink.write(&"hello"[offset], length);
  4794. return true;
  4795. });
  4796. });
  4797. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4798. res.set_header("Content-Length", "1234");
  4799. });
  4800. thread t = thread([&] { svr.listen(HOST, PORT); });
  4801. auto se = detail::scope_exit([&] {
  4802. svr.stop();
  4803. t.join();
  4804. ASSERT_FALSE(svr.is_running());
  4805. });
  4806. svr.wait_until_ready();
  4807. Client cli(HOST, PORT);
  4808. cli.set_read_timeout(1, 0);
  4809. auto expect_body = [&](const Result &res, const std::string &body) {
  4810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4811. EXPECT_EQ(body, res->body);
  4812. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4813. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4814. };
  4815. Headers identity{{"Accept-Encoding", ""}};
  4816. expect_body(cli.Get("/body", identity), "hello world");
  4817. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4818. expect_body(cli.Get("/body",
  4819. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4820. "he");
  4821. expect_body(cli.Get("/provider", identity), "hello");
  4822. expect_body(cli.Get("/empty", identity), "");
  4823. // A HEAD response may give the length of the body a GET would get.
  4824. auto res = cli.Head("/empty");
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4827. }
  4828. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4829. Server svr;
  4830. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4831. res.set_content("short", "text/plain");
  4832. });
  4833. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4834. res.body += " with a footer";
  4835. res.set_header("Transfer-Encoding", "chunked");
  4836. });
  4837. thread t = thread([&] { svr.listen(HOST, PORT); });
  4838. auto se = detail::scope_exit([&] {
  4839. svr.stop();
  4840. t.join();
  4841. ASSERT_FALSE(svr.is_running());
  4842. });
  4843. svr.wait_until_ready();
  4844. Client cli(HOST, PORT);
  4845. cli.set_read_timeout(1, 0);
  4846. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4848. EXPECT_EQ("short with a footer", res->body);
  4849. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4850. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4851. }
  4852. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4853. Server svr;
  4854. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4855. res.set_header("Content-Length", "3");
  4856. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4857. sink.write("abc", 3);
  4858. sink.done();
  4859. return true;
  4860. });
  4861. });
  4862. thread t = thread([&] { svr.listen(HOST, PORT); });
  4863. auto se = detail::scope_exit([&] {
  4864. svr.stop();
  4865. t.join();
  4866. ASSERT_FALSE(svr.is_running());
  4867. });
  4868. svr.wait_until_ready();
  4869. Client cli(HOST, PORT);
  4870. cli.set_keep_alive(true);
  4871. auto res = cli.Get("/");
  4872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4873. EXPECT_EQ("abc", res->body);
  4874. EXPECT_FALSE(res->has_header("Content-Length"));
  4875. EXPECT_EQ("close", res->get_header_value("Connection"));
  4876. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4877. // No body to delimit
  4878. auto head = cli.Head("/");
  4879. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4880. EXPECT_FALSE(head->has_header("Connection"));
  4881. }
  4882. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4883. #ifdef CPPHTTPLIB_SSL_ENABLED
  4884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4885. ASSERT_TRUE(svr.is_valid());
  4886. #else
  4887. Server svr;
  4888. #endif
  4889. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4890. if (req.path == "/routing_handler") {
  4891. res.set_header("PRE_ROUTING", "on");
  4892. res.set_content("Routing Handler", "text/plain");
  4893. return httplib::Server::HandlerResponse::Handled;
  4894. }
  4895. return httplib::Server::HandlerResponse::Unhandled;
  4896. });
  4897. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4898. res.set_content("Error", "text/html");
  4899. });
  4900. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4901. if (req.path == "/routing_handler") {
  4902. res.set_header("POST_ROUTING", "on");
  4903. }
  4904. });
  4905. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4906. res.set_content("Hello World!\n", "text/plain");
  4907. });
  4908. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4909. auto se = detail::scope_exit([&] {
  4910. svr.stop();
  4911. thread.join();
  4912. ASSERT_FALSE(svr.is_running());
  4913. });
  4914. svr.wait_until_ready();
  4915. {
  4916. #ifdef CPPHTTPLIB_SSL_ENABLED
  4917. SSLClient cli(HOST, PORT);
  4918. cli.enable_server_certificate_verification(false);
  4919. #else
  4920. Client cli(HOST, PORT);
  4921. #endif
  4922. auto res = cli.Get("/routing_handler");
  4923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4924. EXPECT_EQ(StatusCode::OK_200, res->status);
  4925. EXPECT_EQ("Routing Handler", res->body);
  4926. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4927. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4928. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4929. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4930. }
  4931. {
  4932. #ifdef CPPHTTPLIB_SSL_ENABLED
  4933. SSLClient cli(HOST, PORT);
  4934. cli.enable_server_certificate_verification(false);
  4935. #else
  4936. Client cli(HOST, PORT);
  4937. #endif
  4938. auto res = cli.Get("/hi");
  4939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4940. EXPECT_EQ(StatusCode::OK_200, res->status);
  4941. EXPECT_EQ("Hello World!\n", res->body);
  4942. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4943. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4944. }
  4945. {
  4946. #ifdef CPPHTTPLIB_SSL_ENABLED
  4947. SSLClient cli(HOST, PORT);
  4948. cli.enable_server_certificate_verification(false);
  4949. #else
  4950. Client cli(HOST, PORT);
  4951. #endif
  4952. auto res = cli.Get("/aaa");
  4953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4954. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4955. EXPECT_EQ("Error", res->body);
  4956. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4957. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4958. }
  4959. }
  4960. TEST(RequestHandlerTest, PreRequestHandler) {
  4961. auto route_path = "/user/:user";
  4962. Server svr;
  4963. svr.Get("/hi", [](const Request &, Response &res) {
  4964. res.set_content("hi", "text/plain");
  4965. });
  4966. svr.Get(route_path, [](const Request &req, Response &res) {
  4967. res.set_content(req.path_params.at("user"), "text/plain");
  4968. });
  4969. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4970. if (req.matched_route == route_path) {
  4971. auto user = req.path_params.at("user");
  4972. if (user != "john") {
  4973. res.status = StatusCode::Forbidden_403;
  4974. res.set_content("error", "text/html");
  4975. return Server::HandlerResponse::Handled;
  4976. }
  4977. }
  4978. return Server::HandlerResponse::Unhandled;
  4979. });
  4980. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4981. auto se = detail::scope_exit([&] {
  4982. svr.stop();
  4983. thread.join();
  4984. ASSERT_FALSE(svr.is_running());
  4985. });
  4986. svr.wait_until_ready();
  4987. Client cli(HOST, PORT);
  4988. {
  4989. auto res = cli.Get("/hi");
  4990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4991. EXPECT_EQ(StatusCode::OK_200, res->status);
  4992. EXPECT_EQ("hi", res->body);
  4993. }
  4994. {
  4995. auto res = cli.Get("/user/john");
  4996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4997. EXPECT_EQ(StatusCode::OK_200, res->status);
  4998. EXPECT_EQ("john", res->body);
  4999. }
  5000. {
  5001. auto res = cli.Get("/user/invalid-user");
  5002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5003. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5004. EXPECT_EQ("error", res->body);
  5005. }
  5006. }
  5007. // The pre-request handler must run before the request body is read, so a
  5008. // rejected request never forces the server to buffer a (potentially large)
  5009. // body. Here the posted body is larger than the payload limit: if the body
  5010. // were read first the server would answer 413, but because the pre-request
  5011. // handler runs first it answers 403 and the body is never read.
  5012. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5013. Server svr;
  5014. svr.set_payload_max_length(8);
  5015. auto handler_ran = false;
  5016. svr.Post("/reject", [&](const Request &req, Response &res) {
  5017. handler_ran = true;
  5018. res.set_content(req.body, "text/plain");
  5019. });
  5020. svr.Post("/accept", [](const Request &req, Response &res) {
  5021. res.set_content(req.body, "text/plain");
  5022. });
  5023. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5024. if (req.matched_route == "/reject") {
  5025. res.status = StatusCode::Forbidden_403;
  5026. res.set_content("denied", "text/plain");
  5027. return Server::HandlerResponse::Handled;
  5028. }
  5029. return Server::HandlerResponse::Unhandled;
  5030. });
  5031. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5032. auto se = detail::scope_exit([&] {
  5033. svr.stop();
  5034. thread.join();
  5035. ASSERT_FALSE(svr.is_running());
  5036. });
  5037. svr.wait_until_ready();
  5038. Client cli(HOST, PORT);
  5039. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5040. // rejects with 403 before the body is read, so 413 is never reached.
  5041. {
  5042. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5044. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5045. EXPECT_EQ("denied", res->body);
  5046. EXPECT_FALSE(handler_ran);
  5047. }
  5048. // An approved route still reads the body and enforces the payload limit.
  5049. {
  5050. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5052. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5053. }
  5054. }
  5055. TEST(UserDataTest, BasicOperations) {
  5056. httplib::UserData ud;
  5057. // Initially empty
  5058. EXPECT_FALSE(ud.has("key"));
  5059. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5060. // set and get
  5061. ud.set("key", 42);
  5062. EXPECT_TRUE(ud.has("key"));
  5063. auto *p = ud.get<int>("key");
  5064. ASSERT_NE(nullptr, p);
  5065. EXPECT_EQ(42, *p);
  5066. // Type mismatch → nullptr
  5067. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5068. // Overwrite with different type
  5069. ud.set("key", std::string("hello"));
  5070. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5071. auto *s = ud.get<std::string>("key");
  5072. ASSERT_NE(nullptr, s);
  5073. EXPECT_EQ("hello", *s);
  5074. // erase
  5075. ud.erase("key");
  5076. EXPECT_FALSE(ud.has("key"));
  5077. // clear
  5078. ud.set("a", 1);
  5079. ud.set("b", 2);
  5080. ud.clear();
  5081. EXPECT_FALSE(ud.has("a"));
  5082. EXPECT_FALSE(ud.has("b"));
  5083. }
  5084. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5085. struct AuthCtx {
  5086. std::string user_id;
  5087. };
  5088. Server svr;
  5089. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5090. res.user_data.set("auth", AuthCtx{"alice"});
  5091. return Server::HandlerResponse::Unhandled;
  5092. });
  5093. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5094. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5095. ASSERT_NE(nullptr, ctx);
  5096. res.set_content("Hello " + ctx->user_id, "text/plain");
  5097. });
  5098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5099. auto se = detail::scope_exit([&] {
  5100. svr.stop();
  5101. thread.join();
  5102. ASSERT_FALSE(svr.is_running());
  5103. });
  5104. svr.wait_until_ready();
  5105. Client cli(HOST, PORT);
  5106. auto res = cli.Get("/me");
  5107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5108. EXPECT_EQ(StatusCode::OK_200, res->status);
  5109. EXPECT_EQ("Hello alice", res->body);
  5110. }
  5111. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5112. struct RoleCtx {
  5113. std::string role;
  5114. };
  5115. Server svr;
  5116. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5117. res.user_data.set("role", RoleCtx{"admin"});
  5118. return Server::HandlerResponse::Unhandled;
  5119. });
  5120. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5121. auto *ctx = res.user_data.get<RoleCtx>("role");
  5122. ASSERT_NE(nullptr, ctx);
  5123. res.set_content(ctx->role, "text/plain");
  5124. });
  5125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5126. auto se = detail::scope_exit([&] {
  5127. svr.stop();
  5128. thread.join();
  5129. ASSERT_FALSE(svr.is_running());
  5130. });
  5131. svr.wait_until_ready();
  5132. Client cli(HOST, PORT);
  5133. auto res = cli.Get("/role");
  5134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5135. EXPECT_EQ(StatusCode::OK_200, res->status);
  5136. EXPECT_EQ("admin", res->body);
  5137. }
  5138. TEST(InvalidFormatTest, StatusCode) {
  5139. Server svr;
  5140. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5141. res.set_content("Hello World!\n", "text/plain");
  5142. res.status = 9999; // Status should be a three-digit code...
  5143. });
  5144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5145. auto se = detail::scope_exit([&] {
  5146. svr.stop();
  5147. thread.join();
  5148. ASSERT_FALSE(svr.is_running());
  5149. });
  5150. svr.wait_until_ready();
  5151. {
  5152. Client cli(HOST, PORT);
  5153. auto res = cli.Get("/hi");
  5154. ASSERT_FALSE(res);
  5155. }
  5156. }
  5157. TEST(URLFragmentTest, WithFragment) {
  5158. Server svr;
  5159. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5160. EXPECT_TRUE(req.target == "/hi");
  5161. });
  5162. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5163. auto se = detail::scope_exit([&] {
  5164. svr.stop();
  5165. thread.join();
  5166. ASSERT_FALSE(svr.is_running());
  5167. });
  5168. svr.wait_until_ready();
  5169. {
  5170. Client cli(HOST, PORT);
  5171. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5172. EXPECT_TRUE(res);
  5173. EXPECT_EQ(StatusCode::OK_200, res->status);
  5174. res = cli.Get("/hi%23key1=val1=key2=val2");
  5175. EXPECT_TRUE(res);
  5176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5177. }
  5178. }
  5179. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5180. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5181. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5182. Server svr;
  5183. std::vector<std::string> targets;
  5184. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5185. targets.push_back(req.target);
  5186. });
  5187. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5188. auto se = detail::scope_exit([&] {
  5189. svr.stop();
  5190. thread.join();
  5191. ASSERT_FALSE(svr.is_running());
  5192. });
  5193. svr.wait_until_ready();
  5194. Client cli(HOST, PORT);
  5195. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5196. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5197. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5198. // A '?' after the '#' belongs to the fragment, not to the query.
  5199. Request req;
  5200. req.method = "GET";
  5201. req.path = "/hi#f?x=1";
  5202. req.params.emplace("a", "1");
  5203. Response res;
  5204. auto error = Error::Success;
  5205. EXPECT_TRUE(cli.send(req, res, error));
  5206. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5207. "/hi?a=1"}),
  5208. targets);
  5209. }
  5210. TEST(HeaderWriter, SetHeaderWriter) {
  5211. Server svr;
  5212. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5213. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5214. return detail::write_headers(strm, hdrs);
  5215. });
  5216. svr.Get("/hi", [](const Request &req, Response &res) {
  5217. auto it = req.headers.find("CustomClientHeader");
  5218. EXPECT_TRUE(it != req.headers.end());
  5219. EXPECT_EQ(it->second, "CustomClientValue");
  5220. res.set_content("Hello World!\n", "text/plain");
  5221. });
  5222. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5223. auto se = detail::scope_exit([&] {
  5224. svr.stop();
  5225. thread.join();
  5226. ASSERT_FALSE(svr.is_running());
  5227. });
  5228. svr.wait_until_ready();
  5229. {
  5230. Client cli(HOST, PORT);
  5231. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5232. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5233. return detail::write_headers(strm, hdrs);
  5234. });
  5235. auto res = cli.Get("/hi");
  5236. EXPECT_TRUE(res);
  5237. EXPECT_EQ(StatusCode::OK_200, res->status);
  5238. auto it = res->headers.find("CustomServerHeader");
  5239. EXPECT_TRUE(it != res->headers.end());
  5240. EXPECT_EQ(it->second, "CustomServerValue");
  5241. }
  5242. }
  5243. class ServerTest : public ::testing::Test {
  5244. protected:
  5245. ServerTest()
  5246. : cli_(HOST, PORT)
  5247. #ifdef CPPHTTPLIB_SSL_ENABLED
  5248. ,
  5249. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5250. #endif
  5251. {
  5252. #ifdef CPPHTTPLIB_SSL_ENABLED
  5253. cli_.enable_server_certificate_verification(false);
  5254. #endif
  5255. // Allow LARGE_DATA (100MB) responses
  5256. cli_.set_payload_max_length(200 * 1024 * 1024);
  5257. }
  5258. virtual void SetUp() {
  5259. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5260. svr_.set_payload_max_length(200 * 1024 * 1024);
  5261. svr_.set_mount_point("/", "./www");
  5262. svr_.set_mount_point("/mount", "./www2");
  5263. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5264. svr_.Get("/hi",
  5265. [&](const Request & /*req*/, Response &res) {
  5266. res.set_content("Hello World!", "text/plain");
  5267. })
  5268. .Get("/file_content",
  5269. [&](const Request & /*req*/, Response &res) {
  5270. res.set_file_content("./www/dir/test.html");
  5271. })
  5272. .Get("/file_content_with_content_type",
  5273. [&](const Request & /*req*/, Response &res) {
  5274. res.set_file_content("./www/file", "text/plain");
  5275. })
  5276. .Get("/invalid_file_content",
  5277. [&](const Request & /*req*/, Response &res) {
  5278. res.set_file_content("./www/dir/invalid_file_path");
  5279. })
  5280. .Get("/http_response_splitting",
  5281. [&](const Request & /*req*/, Response &res) {
  5282. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5283. EXPECT_EQ(0U, res.headers.size());
  5284. EXPECT_FALSE(res.has_header("a"));
  5285. res.set_header("a", "1\nSet-Cookie: a=1");
  5286. EXPECT_EQ(0U, res.headers.size());
  5287. EXPECT_FALSE(res.has_header("a"));
  5288. res.set_header("a", "1\rSet-Cookie: a=1");
  5289. EXPECT_EQ(0U, res.headers.size());
  5290. EXPECT_FALSE(res.has_header("a"));
  5291. res.set_header("a\r\nb", "0");
  5292. EXPECT_EQ(0U, res.headers.size());
  5293. EXPECT_FALSE(res.has_header("a"));
  5294. res.set_header("a\rb", "0");
  5295. EXPECT_EQ(0U, res.headers.size());
  5296. EXPECT_FALSE(res.has_header("a"));
  5297. res.set_header("a\nb", "0");
  5298. EXPECT_EQ(0U, res.headers.size());
  5299. EXPECT_FALSE(res.has_header("a"));
  5300. res.set_redirect("1\r\nSet-Cookie: a=1");
  5301. EXPECT_EQ(0U, res.headers.size());
  5302. EXPECT_FALSE(res.has_header("Location"));
  5303. })
  5304. .Get("/slow",
  5305. [&](const Request & /*req*/, Response &res) {
  5306. std::this_thread::sleep_for(std::chrono::seconds(4));
  5307. res.set_content("slow", "text/plain");
  5308. })
  5309. #if 0
  5310. .Post("/slowpost",
  5311. [&](const Request & /*req*/, Response &res) {
  5312. std::this_thread::sleep_for(std::chrono::seconds(2));
  5313. res.set_content("slow", "text/plain");
  5314. })
  5315. #endif
  5316. .Get("/remote_addr",
  5317. [&](const Request &req, Response &res) {
  5318. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5319. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5320. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5321. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5322. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5323. #endif
  5324. res.set_content(req.remote_addr, "text/plain");
  5325. })
  5326. .Get("/local_addr",
  5327. [&](const Request &req, Response &res) {
  5328. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5329. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5330. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5331. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5332. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5333. #endif
  5334. auto local_addr = req.local_addr;
  5335. auto local_port = std::to_string(req.local_port);
  5336. res.set_content(local_addr.append(":").append(local_port),
  5337. "text/plain");
  5338. })
  5339. .Get("/endwith%",
  5340. [&](const Request & /*req*/, Response &res) {
  5341. res.set_content("Hello World!", "text/plain");
  5342. })
  5343. .Get("/a\\+\\+b",
  5344. [&](const Request &req, Response &res) {
  5345. ASSERT_TRUE(req.has_param("a +b"));
  5346. auto val = req.get_param_value("a +b");
  5347. res.set_content(val, "text/plain");
  5348. })
  5349. .Get("/", [&](const Request & /*req*/,
  5350. Response &res) { res.set_redirect("/hi"); })
  5351. .Post("/1",
  5352. [](const Request & /*req*/, Response &res) {
  5353. res.set_redirect("/2", StatusCode::SeeOther_303);
  5354. })
  5355. .Get("/2",
  5356. [](const Request & /*req*/, Response &res) {
  5357. res.set_content("redirected.", "text/plain");
  5358. res.status = StatusCode::OK_200;
  5359. })
  5360. .Post("/person",
  5361. [&](const Request &req, Response &res) {
  5362. if (req.has_param("name") && req.has_param("note")) {
  5363. persons_[req.get_param_value("name")] =
  5364. req.get_param_value("note");
  5365. } else {
  5366. res.status = StatusCode::BadRequest_400;
  5367. }
  5368. })
  5369. .Put("/person",
  5370. [&](const Request &req, Response &res) {
  5371. if (req.has_param("name") && req.has_param("note")) {
  5372. persons_[req.get_param_value("name")] =
  5373. req.get_param_value("note");
  5374. } else {
  5375. res.status = StatusCode::BadRequest_400;
  5376. }
  5377. })
  5378. .Get("/person/(.*)",
  5379. [&](const Request &req, Response &res) {
  5380. string name = req.matches[1];
  5381. if (persons_.find(name) != persons_.end()) {
  5382. auto note = persons_[name];
  5383. res.set_content(note, "text/plain");
  5384. } else {
  5385. res.status = StatusCode::NotFound_404;
  5386. }
  5387. })
  5388. .Delete("/person",
  5389. [&](const Request &req, Response &res) {
  5390. if (req.has_param("name")) {
  5391. string name = req.get_param_value("name");
  5392. if (persons_.find(name) != persons_.end()) {
  5393. persons_.erase(name);
  5394. res.set_content("DELETED", "text/plain");
  5395. } else {
  5396. res.status = StatusCode::NotFound_404;
  5397. }
  5398. } else {
  5399. res.status = StatusCode::BadRequest_400;
  5400. }
  5401. })
  5402. .Post("/x-www-form-urlencoded-json",
  5403. [&](const Request &req, Response &res) {
  5404. auto json = req.get_param_value("json");
  5405. ASSERT_EQ(JSON_DATA, json);
  5406. res.set_content(json, "appliation/json");
  5407. res.status = StatusCode::OK_200;
  5408. })
  5409. .Get("/streamed-chunked",
  5410. [&](const Request & /*req*/, Response &res) {
  5411. res.set_chunked_content_provider(
  5412. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5413. sink.os << "123";
  5414. sink.os << "456";
  5415. sink.os << "789";
  5416. sink.done();
  5417. return true;
  5418. });
  5419. })
  5420. .Get("/streamed-chunked-with-prohibited-trailer",
  5421. [&](const Request & /*req*/, Response &res) {
  5422. auto i = new int(0);
  5423. // Declare both a prohibited trailer (Content-Length) and an
  5424. // allowed one
  5425. res.set_header("Trailer", "Content-Length, X-Allowed");
  5426. res.set_chunked_content_provider(
  5427. "text/plain",
  5428. [i](size_t /*offset*/, DataSink &sink) {
  5429. switch (*i) {
  5430. case 0: sink.os << "123"; break;
  5431. case 1: sink.os << "456"; break;
  5432. case 2: sink.os << "789"; break;
  5433. case 3: {
  5434. sink.done_with_trailer(
  5435. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5436. } break;
  5437. }
  5438. (*i)++;
  5439. return true;
  5440. },
  5441. [i](bool success) {
  5442. EXPECT_TRUE(success);
  5443. delete i;
  5444. });
  5445. })
  5446. .Get("/streamed-chunked2",
  5447. [&](const Request & /*req*/, Response &res) {
  5448. auto i = new int(0);
  5449. res.set_chunked_content_provider(
  5450. "text/plain",
  5451. [i](size_t /*offset*/, DataSink &sink) {
  5452. switch (*i) {
  5453. case 0: sink.os << "123"; break;
  5454. case 1: sink.os << "456"; break;
  5455. case 2: sink.os << "789"; break;
  5456. case 3: sink.done(); break;
  5457. }
  5458. (*i)++;
  5459. return true;
  5460. },
  5461. [i](bool success) {
  5462. EXPECT_TRUE(success);
  5463. delete i;
  5464. });
  5465. })
  5466. .Get("/streamed-chunked-with-trailer",
  5467. [&](const Request & /*req*/, Response &res) {
  5468. auto i = new int(0);
  5469. res.set_header("Trailer", "Dummy1, Dummy2");
  5470. res.set_chunked_content_provider(
  5471. "text/plain",
  5472. [i](size_t /*offset*/, DataSink &sink) {
  5473. switch (*i) {
  5474. case 0: sink.os << "123"; break;
  5475. case 1: sink.os << "456"; break;
  5476. case 2: sink.os << "789"; break;
  5477. case 3: {
  5478. sink.done_with_trailer(
  5479. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5480. } break;
  5481. }
  5482. (*i)++;
  5483. return true;
  5484. },
  5485. [i](bool success) {
  5486. EXPECT_TRUE(success);
  5487. delete i;
  5488. });
  5489. })
  5490. .Get("/streamed",
  5491. [&](const Request & /*req*/, Response &res) {
  5492. res.set_content_provider(
  5493. 6, "text/plain",
  5494. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5495. sink.os << (offset < 3 ? "a" : "b");
  5496. return true;
  5497. });
  5498. })
  5499. .Get("/streamed-without-length",
  5500. [&](const Request & /*req*/, Response &res) {
  5501. auto data = new std::string("abcdefg");
  5502. res.set_content_provider(
  5503. "text/plain",
  5504. [data](size_t offset, DataSink &sink) {
  5505. if (offset < data->size()) {
  5506. sink.os << data->substr(offset);
  5507. }
  5508. sink.done();
  5509. return true;
  5510. },
  5511. [data](bool success) {
  5512. EXPECT_TRUE(success);
  5513. delete data;
  5514. });
  5515. })
  5516. .Get("/streamed-with-range",
  5517. [&](const Request &req, Response &res) {
  5518. auto data = new std::string("abcdefg");
  5519. // An explicit status keeps the server from picking the 206 it
  5520. // would otherwise choose for a ranged request, so the response
  5521. // is not a partial representation.
  5522. auto status = req.get_param_value("status");
  5523. if (status == "200") {
  5524. res.status = StatusCode::OK_200;
  5525. } else if (status == "403") {
  5526. res.status = StatusCode::Forbidden_403;
  5527. }
  5528. res.set_content_provider(
  5529. data->size(), "text/plain",
  5530. [data](size_t offset, size_t length, DataSink &sink) {
  5531. size_t DATA_CHUNK_SIZE = 4;
  5532. const auto &d = *data;
  5533. auto out_len =
  5534. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5535. auto ret =
  5536. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5537. EXPECT_TRUE(ret);
  5538. return true;
  5539. },
  5540. [data, &req](bool success) {
  5541. EXPECT_EQ(success, !req.has_param("error"));
  5542. delete data;
  5543. });
  5544. })
  5545. .Get("/streamed-cancel",
  5546. [&](const Request & /*req*/, Response &res) {
  5547. res.set_content_provider(
  5548. size_t(-1), "text/plain",
  5549. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5550. sink.os << "data_chunk";
  5551. return true;
  5552. });
  5553. })
  5554. .Get("/regex-with-delimiter",
  5555. [&](const Request &req, Response & /*res*/) {
  5556. ASSERT_TRUE(req.has_param("key"));
  5557. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5558. })
  5559. .Get("/with-range",
  5560. [&](const Request & /*req*/, Response &res) {
  5561. res.set_content("abcdefg", "text/plain");
  5562. })
  5563. .Get("/test-start-time",
  5564. [&](const Request &req, Response & /*res*/) {
  5565. EXPECT_NE(req.start_time_,
  5566. std::chrono::steady_clock::time_point::min());
  5567. })
  5568. .Get("/with-range-customized-response",
  5569. [&](const Request & /*req*/, Response &res) {
  5570. res.status = StatusCode::BadRequest_400;
  5571. res.set_content(JSON_DATA, "application/json");
  5572. })
  5573. .Post("/chunked",
  5574. [&](const Request &req, Response & /*res*/) {
  5575. EXPECT_EQ(req.body, "dechunked post body");
  5576. })
  5577. .Post("/large-chunked",
  5578. [&](const Request &req, Response & /*res*/) {
  5579. std::string expected(6 * 30 * 1024u, 'a');
  5580. EXPECT_EQ(req.body, expected);
  5581. })
  5582. .Post("/multipart",
  5583. [&](const Request &req, Response & /*res*/) {
  5584. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5585. req.form.get_field_count("text2") +
  5586. req.form.get_field_count("file3") +
  5587. req.form.get_field_count("file4"));
  5588. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5589. req.form.get_file_count("file2"));
  5590. ASSERT_TRUE(!req.form.has_file("???"));
  5591. ASSERT_TRUE(!req.form.has_field("???"));
  5592. ASSERT_TRUE(req.body.empty());
  5593. {
  5594. const auto &text = req.form.get_field("text1");
  5595. EXPECT_EQ("text default", text);
  5596. }
  5597. {
  5598. const auto &text = req.form.get_field("text2");
  5599. EXPECT_EQ("aωb", text);
  5600. }
  5601. {
  5602. const auto &file = req.form.get_file("file1");
  5603. EXPECT_EQ("hello.txt", file.filename);
  5604. EXPECT_EQ("text/plain", file.content_type);
  5605. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5606. }
  5607. {
  5608. const auto &file = req.form.get_file("file2");
  5609. EXPECT_EQ("world.json", file.filename);
  5610. EXPECT_EQ("application/json", file.content_type);
  5611. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5612. }
  5613. {
  5614. const auto &text = req.form.get_field("file3");
  5615. EXPECT_EQ(0u, text.size());
  5616. }
  5617. {
  5618. const auto &text = req.form.get_field("file4");
  5619. EXPECT_EQ(0u, text.size());
  5620. }
  5621. })
  5622. .Post("/multipart/multi_file_values",
  5623. [&](const Request &req, Response & /*res*/) {
  5624. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5625. req.form.get_field_count("multi_text1"));
  5626. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5627. ASSERT_TRUE(!req.form.has_file("???"));
  5628. ASSERT_TRUE(!req.form.has_field("???"));
  5629. ASSERT_TRUE(req.body.empty());
  5630. {
  5631. const auto &text = req.form.get_field("text");
  5632. EXPECT_EQ("default text", text);
  5633. }
  5634. {
  5635. const auto &text1_values = req.form.get_fields("multi_text1");
  5636. EXPECT_EQ(2u, text1_values.size());
  5637. EXPECT_EQ("aaaaa", text1_values[0]);
  5638. EXPECT_EQ("bbbbb", text1_values[1]);
  5639. }
  5640. {
  5641. const auto &file1_values = req.form.get_files("multi_file1");
  5642. EXPECT_EQ(2u, file1_values.size());
  5643. auto file1 = file1_values[0];
  5644. EXPECT_EQ(file1.filename, "hello.txt");
  5645. EXPECT_EQ(file1.content_type, "text/plain");
  5646. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5647. auto file2 = file1_values[1];
  5648. EXPECT_EQ(file2.filename, "world.json");
  5649. EXPECT_EQ(file2.content_type, "application/json");
  5650. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5651. }
  5652. })
  5653. .Post("/empty",
  5654. [&](const Request &req, Response &res) {
  5655. EXPECT_EQ(req.body, "");
  5656. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5657. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5658. res.set_content("empty", "text/plain");
  5659. })
  5660. .Post("/empty-no-content-type",
  5661. [&](const Request &req, Response &res) {
  5662. EXPECT_EQ(req.body, "");
  5663. EXPECT_FALSE(req.has_header("Content-Type"));
  5664. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5665. res.set_content("empty-no-content-type", "text/plain");
  5666. })
  5667. .Post("/path-only",
  5668. [&](const Request &req, Response &res) {
  5669. EXPECT_EQ(req.body, "");
  5670. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5671. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5672. res.set_content("path-only", "text/plain");
  5673. })
  5674. .Post("/path-headers-only",
  5675. [&](const Request &req, Response &res) {
  5676. EXPECT_EQ(req.body, "");
  5677. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5678. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5679. EXPECT_EQ("world", req.get_header_value("hello"));
  5680. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5681. res.set_content("path-headers-only", "text/plain");
  5682. })
  5683. .Post("/post-large",
  5684. [&](const Request &req, Response &res) {
  5685. EXPECT_EQ(req.body, LARGE_DATA);
  5686. res.set_content(req.body, "text/plain");
  5687. })
  5688. .Post("/post-loopback",
  5689. [&](const Request &, Response &res,
  5690. ContentReader const &content_reader) {
  5691. std::string body;
  5692. content_reader([&](const char *data, size_t data_length) {
  5693. body.append(data, data_length);
  5694. return true;
  5695. });
  5696. res.set_content(body, "text/plain");
  5697. })
  5698. .Put("/put-loopback",
  5699. [&](const Request &, Response &res,
  5700. ContentReader const &content_reader) {
  5701. std::string body;
  5702. content_reader([&](const char *data, size_t data_length) {
  5703. body.append(data, data_length);
  5704. return true;
  5705. });
  5706. res.set_content(body, "text/plain");
  5707. })
  5708. .Patch("/patch-loopback",
  5709. [&](const Request &, Response &res,
  5710. ContentReader const &content_reader) {
  5711. std::string body;
  5712. content_reader([&](const char *data, size_t data_length) {
  5713. body.append(data, data_length);
  5714. return true;
  5715. });
  5716. res.set_content(body, "text/plain");
  5717. })
  5718. .Put("/empty-no-content-type",
  5719. [&](const Request &req, Response &res) {
  5720. EXPECT_EQ(req.body, "");
  5721. EXPECT_FALSE(req.has_header("Content-Type"));
  5722. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5723. res.set_content("empty-no-content-type", "text/plain");
  5724. })
  5725. .Put("/put",
  5726. [&](const Request &req, Response &res) {
  5727. EXPECT_EQ(req.body, "PUT");
  5728. res.set_content(req.body, "text/plain");
  5729. })
  5730. .Put("/put-large",
  5731. [&](const Request &req, Response &res) {
  5732. EXPECT_EQ(req.body, LARGE_DATA);
  5733. res.set_content(req.body, "text/plain");
  5734. })
  5735. .Patch("/patch",
  5736. [&](const Request &req, Response &res) {
  5737. EXPECT_EQ(req.body, "PATCH");
  5738. res.set_content(req.body, "text/plain");
  5739. })
  5740. .Delete("/delete",
  5741. [&](const Request & /*req*/, Response &res) {
  5742. res.set_content("DELETE", "text/plain");
  5743. })
  5744. .Delete("/delete-body",
  5745. [&](const Request &req, Response &res) {
  5746. EXPECT_EQ(req.body, "content");
  5747. res.set_content(req.body, "text/plain");
  5748. })
  5749. .Options(R"(\*)",
  5750. [&](const Request & /*req*/, Response &res) {
  5751. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5752. })
  5753. .CustomRoute("PROPFIND", "/dav/:id",
  5754. [&](const Request &req, Response &res) {
  5755. res.set_header("x-body-size",
  5756. std::to_string(req.body.size()));
  5757. res.set_header("x-matched-route", req.matched_route);
  5758. res.set_header("x-dav-id", req.path_params.at("id"));
  5759. res.status = StatusCode::MultiStatus_207;
  5760. res.set_content(req.body, "application/xml");
  5761. })
  5762. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5763. [&](const Request &req, Response &res) {
  5764. res.set_header("x-dav-match", req.matches[1]);
  5765. res.status = StatusCode::MultiStatus_207;
  5766. })
  5767. .CustomRoute("MKCOL", "/dav-mkcol",
  5768. [&](const Request &req, Response &res) {
  5769. EXPECT_TRUE(req.body.empty());
  5770. res.status = StatusCode::Created_201;
  5771. })
  5772. .CustomRoute(
  5773. "REPORT", "/dav-report",
  5774. [&](const Request & /*req*/, Response &res,
  5775. const ContentReader &content_reader) {
  5776. std::string body;
  5777. content_reader([&](const char *data, size_t data_length) {
  5778. body.append(data, data_length);
  5779. return true;
  5780. });
  5781. res.set_header("x-body-size", std::to_string(body.size()));
  5782. res.status = StatusCode::MultiStatus_207;
  5783. res.set_content(body, "application/xml");
  5784. })
  5785. .Get("/request-target",
  5786. [&](const Request &req, Response & /*res*/) {
  5787. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5788. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5789. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5790. })
  5791. .Get("/long-query-value",
  5792. [&](const Request &req, Response & /*res*/) {
  5793. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5794. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5795. })
  5796. .Get("/too-long-query-value",
  5797. [&](const Request &req, Response & /*res*/) {
  5798. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5799. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5800. })
  5801. .Get("/array-param",
  5802. [&](const Request &req, Response & /*res*/) {
  5803. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5804. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5805. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5806. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5807. })
  5808. .Get("/array-param-values",
  5809. [&](const Request &req, Response & /*res*/) {
  5810. auto values = req.get_param_values("array");
  5811. EXPECT_EQ(3u, values.size());
  5812. EXPECT_EQ("value1", values[0]);
  5813. EXPECT_EQ("value2", values[1]);
  5814. EXPECT_EQ("value3", values[2]);
  5815. auto empty = req.get_param_values("nonexistent");
  5816. EXPECT_TRUE(empty.empty());
  5817. })
  5818. .Post("/validate-no-multiple-headers",
  5819. [&](const Request &req, Response & /*res*/) {
  5820. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5821. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5822. })
  5823. .Post("/content_receiver",
  5824. [&](const Request &req, Response &res,
  5825. const ContentReader &content_reader) {
  5826. if (req.is_multipart_form_data()) {
  5827. std::vector<FormData> items;
  5828. content_reader(
  5829. [&](const FormData &file) {
  5830. items.push_back(file);
  5831. return true;
  5832. },
  5833. [&](const char *data, size_t data_length) {
  5834. items.back().content.append(data, data_length);
  5835. return true;
  5836. });
  5837. EXPECT_EQ(5u, items.size());
  5838. {
  5839. const auto &file = get_file_value(items, "text1");
  5840. EXPECT_TRUE(file.filename.empty());
  5841. EXPECT_EQ("text default", file.content);
  5842. }
  5843. {
  5844. const auto &file = get_file_value(items, "text2");
  5845. EXPECT_TRUE(file.filename.empty());
  5846. EXPECT_EQ("aωb", file.content);
  5847. }
  5848. {
  5849. const auto &file = get_file_value(items, "file1");
  5850. EXPECT_EQ("hello.txt", file.filename);
  5851. EXPECT_EQ("text/plain", file.content_type);
  5852. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5853. }
  5854. {
  5855. const auto &file = get_file_value(items, "file2");
  5856. EXPECT_EQ("world.json", file.filename);
  5857. EXPECT_EQ("application/json", file.content_type);
  5858. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5859. }
  5860. {
  5861. const auto &file = get_file_value(items, "file3");
  5862. EXPECT_TRUE(file.filename.empty());
  5863. EXPECT_EQ("application/octet-stream", file.content_type);
  5864. EXPECT_EQ(0u, file.content.size());
  5865. }
  5866. } else {
  5867. std::string body;
  5868. content_reader([&](const char *data, size_t data_length) {
  5869. EXPECT_EQ(7U, data_length);
  5870. body.append(data, data_length);
  5871. return true;
  5872. });
  5873. EXPECT_EQ(body, "content");
  5874. res.set_content(body, "text/plain");
  5875. }
  5876. })
  5877. .Put("/content_receiver",
  5878. [&](const Request & /*req*/, Response &res,
  5879. const ContentReader &content_reader) {
  5880. std::string body;
  5881. content_reader([&](const char *data, size_t data_length) {
  5882. body.append(data, data_length);
  5883. return true;
  5884. });
  5885. EXPECT_EQ(body, "content");
  5886. res.set_content(body, "text/plain");
  5887. })
  5888. .Patch("/content_receiver",
  5889. [&](const Request & /*req*/, Response &res,
  5890. const ContentReader &content_reader) {
  5891. std::string body;
  5892. content_reader([&](const char *data, size_t data_length) {
  5893. body.append(data, data_length);
  5894. return true;
  5895. });
  5896. EXPECT_EQ(body, "content");
  5897. res.set_content(body, "text/plain");
  5898. })
  5899. .Post("/query-string-and-body",
  5900. [&](const Request &req, Response & /*res*/) {
  5901. ASSERT_TRUE(req.has_param("key"));
  5902. EXPECT_EQ(req.get_param_value("key"), "value");
  5903. EXPECT_EQ(req.body, "content");
  5904. })
  5905. .Get("/last-request",
  5906. [&](const Request &req, Response & /*res*/) {
  5907. EXPECT_EQ("close", req.get_header_value("Connection"));
  5908. })
  5909. .Get(R"(/redirect/(\d+))",
  5910. [&](const Request &req, Response &res) {
  5911. auto num = std::stoi(req.matches[1]) + 1;
  5912. std::string url = "/redirect/" + std::to_string(num);
  5913. res.set_redirect(url);
  5914. })
  5915. .Post("/binary",
  5916. [&](const Request &req, Response &res) {
  5917. EXPECT_EQ(4U, req.body.size());
  5918. EXPECT_EQ("application/octet-stream",
  5919. req.get_header_value("Content-Type"));
  5920. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5921. res.set_content(req.body, "application/octet-stream");
  5922. })
  5923. .Put("/binary",
  5924. [&](const Request &req, Response &res) {
  5925. EXPECT_EQ(4U, req.body.size());
  5926. EXPECT_EQ("application/octet-stream",
  5927. req.get_header_value("Content-Type"));
  5928. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5929. res.set_content(req.body, "application/octet-stream");
  5930. })
  5931. .Patch("/binary",
  5932. [&](const Request &req, Response &res) {
  5933. EXPECT_EQ(4U, req.body.size());
  5934. EXPECT_EQ("application/octet-stream",
  5935. req.get_header_value("Content-Type"));
  5936. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5937. res.set_content(req.body, "application/octet-stream");
  5938. })
  5939. .Delete("/binary",
  5940. [&](const Request &req, Response &res) {
  5941. EXPECT_EQ(4U, req.body.size());
  5942. EXPECT_EQ("application/octet-stream",
  5943. req.get_header_value("Content-Type"));
  5944. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5945. res.set_content(req.body, "application/octet-stream");
  5946. })
  5947. .Get("/issue1772",
  5948. [&](const Request & /*req*/, Response &res) {
  5949. res.status = 401;
  5950. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5951. })
  5952. .Delete("/issue609",
  5953. [](const httplib::Request &, httplib::Response &res,
  5954. const httplib::ContentReader &) {
  5955. res.set_content("ok", "text/plain");
  5956. })
  5957. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5958. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5959. .Get("/compress",
  5960. [&](const Request & /*req*/, Response &res) {
  5961. res.set_content(
  5962. "12345678901234567890123456789012345678901234567890123456789"
  5963. "01234567890123456789012345678901234567890",
  5964. "text/plain");
  5965. })
  5966. .Get("/compress-with-charset",
  5967. [&](const Request & /*req*/, Response &res) {
  5968. res.set_content(
  5969. "12345678901234567890123456789012345678901234567890123456789"
  5970. "01234567890123456789012345678901234567890",
  5971. "application/json; charset=utf-8");
  5972. })
  5973. .Get("/nocompress",
  5974. [&](const Request & /*req*/, Response &res) {
  5975. res.set_content(
  5976. "12345678901234567890123456789012345678901234567890123456789"
  5977. "01234567890123456789012345678901234567890",
  5978. "application/octet-stream");
  5979. })
  5980. .Post("/compress-multipart",
  5981. [&](const Request &req, Response & /*res*/) {
  5982. EXPECT_EQ(2u, req.form.fields.size());
  5983. ASSERT_TRUE(!req.form.has_field("???"));
  5984. {
  5985. const auto &text = req.form.get_field("key1");
  5986. EXPECT_EQ("test", text);
  5987. }
  5988. {
  5989. const auto &text = req.form.get_field("key2");
  5990. EXPECT_EQ("--abcdefg123", text);
  5991. }
  5992. })
  5993. #endif
  5994. ;
  5995. persons_["john"] = "programmer";
  5996. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5997. svr_.wait_until_ready();
  5998. }
  5999. virtual void TearDown() {
  6000. svr_.stop();
  6001. if (!request_threads_.empty()) {
  6002. std::this_thread::sleep_for(std::chrono::seconds(1));
  6003. for (auto &t : request_threads_) {
  6004. t.join();
  6005. }
  6006. }
  6007. t_.join();
  6008. }
  6009. map<string, string> persons_;
  6010. #ifdef CPPHTTPLIB_SSL_ENABLED
  6011. SSLClient cli_;
  6012. SSLServer svr_;
  6013. #else
  6014. Client cli_;
  6015. Server svr_;
  6016. #endif
  6017. thread t_;
  6018. std::vector<thread> request_threads_;
  6019. };
  6020. TEST_F(ServerTest, GetMethod200) {
  6021. auto res = cli_.Get("/hi");
  6022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6023. EXPECT_EQ("HTTP/1.1", res->version);
  6024. EXPECT_EQ(StatusCode::OK_200, res->status);
  6025. EXPECT_EQ("OK", res->reason);
  6026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6027. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6028. EXPECT_EQ("Hello World!", res->body);
  6029. }
  6030. TEST_F(ServerTest, GetEmptyFile) {
  6031. auto res = cli_.Get("/empty_file");
  6032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6033. EXPECT_EQ(StatusCode::OK_200, res->status);
  6034. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6035. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6036. EXPECT_EQ("", res->body);
  6037. }
  6038. TEST_F(ServerTest, GetFileContent) {
  6039. auto res = cli_.Get("/file_content");
  6040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6041. EXPECT_EQ(StatusCode::OK_200, res->status);
  6042. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6043. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6044. EXPECT_EQ("test.html", res->body);
  6045. }
  6046. TEST_F(ServerTest, GetFileContentWithRange) {
  6047. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6050. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6051. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6052. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6053. EXPECT_EQ("est", res->body);
  6054. }
  6055. TEST_F(ServerTest, GetFileContentWithContentType) {
  6056. auto res = cli_.Get("/file_content_with_content_type");
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. EXPECT_EQ(StatusCode::OK_200, res->status);
  6059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6060. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6061. EXPECT_EQ("file\n", res->body);
  6062. }
  6063. TEST_F(ServerTest, GetInvalidFileContent) {
  6064. auto res = cli_.Get("/invalid_file_content");
  6065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6066. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6067. }
  6068. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6069. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. EXPECT_EQ("HTTP/1.1", res->version);
  6072. EXPECT_EQ(StatusCode::OK_200, res->status);
  6073. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6074. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6075. EXPECT_EQ("Hello World!", res->body);
  6076. }
  6077. TEST_F(ServerTest, GetMethod302) {
  6078. auto res = cli_.Get("/");
  6079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6080. EXPECT_EQ(StatusCode::Found_302, res->status);
  6081. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6082. }
  6083. TEST_F(ServerTest, GetMethod302Redirect) {
  6084. cli_.set_follow_location(true);
  6085. auto res = cli_.Get("/");
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::OK_200, res->status);
  6088. EXPECT_EQ("Hello World!", res->body);
  6089. EXPECT_EQ("/hi", res->location);
  6090. }
  6091. TEST_F(ServerTest, GetMethod404) {
  6092. auto res = cli_.Get("/invalid");
  6093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6094. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6095. }
  6096. TEST_F(ServerTest, HeadMethod200) {
  6097. auto res = cli_.Head("/hi");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6101. EXPECT_TRUE(res->body.empty());
  6102. }
  6103. TEST_F(ServerTest, HeadMethod200Static) {
  6104. auto res = cli_.Head("/mount/dir/index.html");
  6105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6108. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6109. EXPECT_TRUE(res->body.empty());
  6110. }
  6111. TEST_F(ServerTest, HeadMethod404) {
  6112. auto res = cli_.Head("/invalid");
  6113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6114. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6115. EXPECT_TRUE(res->body.empty());
  6116. }
  6117. TEST_F(ServerTest, GetMethodPersonJohn) {
  6118. auto res = cli_.Get("/person/john");
  6119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6120. EXPECT_EQ(StatusCode::OK_200, res->status);
  6121. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6122. EXPECT_EQ("programmer", res->body);
  6123. }
  6124. TEST_F(ServerTest, PostMethod1) {
  6125. auto res = cli_.Get("/person/john1");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6128. res = cli_.Post("/person", "name=john1&note=coder",
  6129. "application/x-www-form-urlencoded");
  6130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6131. ASSERT_EQ(StatusCode::OK_200, res->status);
  6132. res = cli_.Get("/person/john1");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. ASSERT_EQ(StatusCode::OK_200, res->status);
  6135. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6136. ASSERT_EQ("coder", res->body);
  6137. }
  6138. TEST_F(ServerTest, PostMethod2) {
  6139. auto res = cli_.Get("/person/john2");
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6142. Params params;
  6143. params.emplace("name", "john2");
  6144. params.emplace("note", "coder");
  6145. res = cli_.Post("/person", params);
  6146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6147. ASSERT_EQ(StatusCode::OK_200, res->status);
  6148. res = cli_.Get("/person/john2");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. ASSERT_EQ(StatusCode::OK_200, res->status);
  6151. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6152. ASSERT_EQ("coder", res->body);
  6153. }
  6154. TEST_F(ServerTest, PutMethod3) {
  6155. auto res = cli_.Get("/person/john3");
  6156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6157. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6158. Params params;
  6159. params.emplace("name", "john3");
  6160. params.emplace("note", "coder");
  6161. res = cli_.Put("/person", params);
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. ASSERT_EQ(StatusCode::OK_200, res->status);
  6164. res = cli_.Get("/person/john3");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. ASSERT_EQ(StatusCode::OK_200, res->status);
  6167. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6168. ASSERT_EQ("coder", res->body);
  6169. }
  6170. TEST_F(ServerTest, DeleteMethod1) {
  6171. auto res = cli_.Get("/person/john4");
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6174. Params params;
  6175. params.emplace("name", "john4");
  6176. params.emplace("note", "coder");
  6177. res = cli_.Post("/person", params);
  6178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6179. ASSERT_EQ(StatusCode::OK_200, res->status);
  6180. res = cli_.Get("/person/john4");
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. ASSERT_EQ(StatusCode::OK_200, res->status);
  6183. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6184. ASSERT_EQ("coder", res->body);
  6185. Params delete_params;
  6186. delete_params.emplace("name", "john4");
  6187. res = cli_.Delete("/person", delete_params);
  6188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6189. ASSERT_EQ(StatusCode::OK_200, res->status);
  6190. ASSERT_EQ("DELETED", res->body);
  6191. res = cli_.Get("/person/john4");
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6194. }
  6195. TEST_F(ServerTest, DeleteMethod2) {
  6196. auto res = cli_.Get("/person/john5");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6199. Params params;
  6200. params.emplace("name", "john5");
  6201. params.emplace("note", "developer");
  6202. res = cli_.Post("/person", params);
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. ASSERT_EQ(StatusCode::OK_200, res->status);
  6205. res = cli_.Get("/person/john5");
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. ASSERT_EQ(StatusCode::OK_200, res->status);
  6208. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6209. ASSERT_EQ("developer", res->body);
  6210. Params delete_params;
  6211. delete_params.emplace("name", "john5");
  6212. Headers headers;
  6213. headers.emplace("Custom-Header", "test-value");
  6214. res = cli_.Delete("/person", headers, delete_params);
  6215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6216. ASSERT_EQ(StatusCode::OK_200, res->status);
  6217. ASSERT_EQ("DELETED", res->body);
  6218. res = cli_.Get("/person/john5");
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6221. }
  6222. TEST_F(ServerTest, DeleteMethod3) {
  6223. auto res = cli_.Get("/person/john6");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6226. Params params;
  6227. params.emplace("name", "john6");
  6228. params.emplace("note", "tester");
  6229. res = cli_.Post("/person", params);
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. ASSERT_EQ(StatusCode::OK_200, res->status);
  6232. res = cli_.Get("/person/john6");
  6233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6234. ASSERT_EQ(StatusCode::OK_200, res->status);
  6235. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6236. ASSERT_EQ("tester", res->body);
  6237. Params delete_params;
  6238. delete_params.emplace("name", "john6");
  6239. Headers headers;
  6240. headers.emplace("Custom-Header", "test-value");
  6241. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. ASSERT_EQ(StatusCode::OK_200, res->status);
  6244. ASSERT_EQ("DELETED", res->body);
  6245. res = cli_.Get("/person/john6");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6248. }
  6249. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6250. Params params;
  6251. params.emplace("json", JSON_DATA);
  6252. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6254. ASSERT_EQ(StatusCode::OK_200, res->status);
  6255. ASSERT_EQ(JSON_DATA, res->body);
  6256. }
  6257. TEST_F(ServerTest, PostEmptyContent) {
  6258. auto res = cli_.Post("/empty", "", "text/plain");
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. ASSERT_EQ(StatusCode::OK_200, res->status);
  6261. ASSERT_EQ("empty", res->body);
  6262. }
  6263. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6264. auto res = cli_.Post("/empty-no-content-type");
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. ASSERT_EQ(StatusCode::OK_200, res->status);
  6267. ASSERT_EQ("empty-no-content-type", res->body);
  6268. }
  6269. TEST_F(ServerTest, PostPathOnly) {
  6270. auto res = cli_.Post("/path-only");
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. ASSERT_EQ(StatusCode::OK_200, res->status);
  6273. ASSERT_EQ("path-only", res->body);
  6274. }
  6275. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6276. auto res = cli_.Post("/path-headers-only",
  6277. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. ASSERT_EQ(StatusCode::OK_200, res->status);
  6280. ASSERT_EQ("path-headers-only", res->body);
  6281. }
  6282. TEST_F(ServerTest, PostLarge) {
  6283. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. ASSERT_EQ(StatusCode::OK_200, res->status);
  6286. EXPECT_EQ(LARGE_DATA, res->body);
  6287. }
  6288. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6289. auto res = cli_.Put("/empty-no-content-type");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. ASSERT_EQ(StatusCode::OK_200, res->status);
  6292. ASSERT_EQ("empty-no-content-type", res->body);
  6293. }
  6294. TEST_F(ServerTest, GetMethodDir) {
  6295. auto res = cli_.Get("/dir/");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. EXPECT_EQ(StatusCode::OK_200, res->status);
  6298. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6299. auto body = R"(<html>
  6300. <head>
  6301. </head>
  6302. <body>
  6303. <a href="/dir/test.html">Test</a>
  6304. <a href="/hi">hi</a>
  6305. </body>
  6306. </html>
  6307. )";
  6308. EXPECT_EQ(body, res->body);
  6309. }
  6310. TEST_F(ServerTest, GetMethodDirTest) {
  6311. auto res = cli_.Get("/dir/test.html");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6315. EXPECT_EQ("test.html", res->body);
  6316. }
  6317. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6318. auto res = cli_.Get("/dir/../dir/test.html");
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6321. }
  6322. TEST_F(ServerTest, GetMethodInvalidPath) {
  6323. auto res = cli_.Get("/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, GetMethodOutOfBaseDir) {
  6328. auto res = cli_.Get("/../www/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, GetMethodOutOfBaseDir2) {
  6333. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6336. }
  6337. TEST_F(ServerTest, GetMethodDirMountTest) {
  6338. auto res = cli_.Get("/mount/dir/test.html");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::OK_200, res->status);
  6341. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6342. EXPECT_EQ("test.html", res->body);
  6343. }
  6344. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6345. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6347. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6348. }
  6349. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6350. auto res = cli_.Get("/mount/dir/../test.html");
  6351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6353. }
  6354. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6355. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6358. }
  6359. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6360. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6362. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6363. }
  6364. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6365. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6368. }
  6369. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6370. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6373. }
  6374. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6375. auto res = cli_.Get("/mount/dir");
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6378. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6379. }
  6380. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6381. auto res = cli_.Get("//dir");
  6382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6383. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6384. EXPECT_FALSE(res->has_header("Location"));
  6385. }
  6386. TEST_F(ServerTest, PostMethod303) {
  6387. auto res = cli_.Post("/1", "body", "text/plain");
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6390. EXPECT_EQ("/2", res->get_header_value("Location"));
  6391. }
  6392. TEST_F(ServerTest, PostMethod303Redirect) {
  6393. cli_.set_follow_location(true);
  6394. auto res = cli_.Post("/1", "body", "text/plain");
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. EXPECT_EQ(StatusCode::OK_200, res->status);
  6397. EXPECT_EQ("redirected.", res->body);
  6398. EXPECT_EQ("/2", res->location);
  6399. }
  6400. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6401. auto res = cli_.Get("/dir/test.abcde");
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::OK_200, res->status);
  6404. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6405. EXPECT_EQ("abcde", res->body);
  6406. }
  6407. TEST_F(ServerTest, StaticFileRange) {
  6408. auto res =
  6409. cli_.Get("/dir/test.abcde", Headers{{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. EXPECT_EQ(std::string("cd"), res->body);
  6417. }
  6418. TEST_F(ServerTest, StaticFileRanges) {
  6419. auto res = cli_.Get("/dir/test.abcde",
  6420. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6423. EXPECT_TRUE(
  6424. res->get_header_value("Content-Type")
  6425. .find(
  6426. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6427. 0);
  6428. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6429. }
  6430. TEST_F(ServerTest, StaticFileRangeHead) {
  6431. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6433. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6434. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6435. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6436. EXPECT_EQ(true, res->has_header("Content-Range"));
  6437. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6438. }
  6439. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6440. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6443. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6444. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6445. EXPECT_EQ(true, res->has_header("Content-Range"));
  6446. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6447. res->get_header_value("Content-Range"));
  6448. EXPECT_EQ("LAST\n", res->body);
  6449. }
  6450. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6451. auto res =
  6452. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6456. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6457. EXPECT_EQ(true, res->has_header("Content-Range"));
  6458. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6459. }
  6460. TEST_F(ServerTest, StaticFileBigFile) {
  6461. auto res = cli_.Get("/dir/1MB.txt");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::OK_200, res->status);
  6464. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6465. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6466. }
  6467. TEST_F(ServerTest, InvalidBaseDirMount) {
  6468. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6469. }
  6470. TEST_F(ServerTest, Binary) {
  6471. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6472. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6473. "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.data(), binary.size(),
  6478. "application/octet-stream");
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. ASSERT_EQ(StatusCode::OK_200, res->status);
  6481. ASSERT_EQ(4U, res->body.size());
  6482. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6483. "application/octet-stream");
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. ASSERT_EQ(StatusCode::OK_200, res->status);
  6486. ASSERT_EQ(4U, res->body.size());
  6487. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6488. "application/octet-stream");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. ASSERT_EQ(StatusCode::OK_200, res->status);
  6491. ASSERT_EQ(4U, res->body.size());
  6492. }
  6493. TEST_F(ServerTest, BinaryString) {
  6494. auto binary = std::string("\x00\x01\x02\x03", 4);
  6495. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6497. ASSERT_EQ(StatusCode::OK_200, res->status);
  6498. ASSERT_EQ(4U, res->body.size());
  6499. res = cli_.Put("/binary", binary, "application/octet-stream");
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. ASSERT_EQ(StatusCode::OK_200, res->status);
  6502. ASSERT_EQ(4U, res->body.size());
  6503. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. ASSERT_EQ(StatusCode::OK_200, res->status);
  6506. ASSERT_EQ(4U, res->body.size());
  6507. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. ASSERT_EQ(StatusCode::OK_200, res->status);
  6510. ASSERT_EQ(4U, res->body.size());
  6511. }
  6512. TEST_F(ServerTest, EmptyRequest) {
  6513. auto res = cli_.Get("");
  6514. ASSERT_TRUE(!res);
  6515. EXPECT_EQ(Error::Connection, res.error());
  6516. }
  6517. TEST_F(ServerTest, LongRequest) {
  6518. std::string request;
  6519. for (size_t i = 0; i < 545; i++) {
  6520. request += "/TooLongRequest";
  6521. }
  6522. request += "OK";
  6523. auto res = cli_.Get(request.c_str());
  6524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6526. }
  6527. TEST_F(ServerTest, TooLongRequest) {
  6528. std::string request;
  6529. for (size_t i = 0; i < 546; i++) {
  6530. request += "/TooLongRequest";
  6531. }
  6532. request += "_NG";
  6533. auto start = std::chrono::high_resolution_clock::now();
  6534. cli_.set_keep_alive(true);
  6535. auto res = cli_.Get(request.c_str());
  6536. auto end = std::chrono::high_resolution_clock::now();
  6537. auto elapsed =
  6538. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6539. .count();
  6540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6541. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6542. EXPECT_LE(elapsed, 1000);
  6543. EXPECT_EQ("close", res->get_header_value("Connection"));
  6544. EXPECT_FALSE(cli_.is_socket_open());
  6545. }
  6546. TEST_F(ServerTest, AlmostTooLongRequest) {
  6547. // test for #2046 - URI length check shouldn't include other content on req
  6548. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6549. // leading /, space, HTTP/1.1)
  6550. std::string request =
  6551. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6552. auto res = cli_.Get(request.c_str());
  6553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6554. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6555. }
  6556. TEST_F(ServerTest, LongHeader) {
  6557. Request req;
  6558. req.method = "GET";
  6559. req.path = "/hi";
  6560. std::string host_and_port;
  6561. host_and_port += HOST;
  6562. host_and_port += ":";
  6563. host_and_port += std::to_string(PORT);
  6564. req.headers.emplace("Host", host_and_port.c_str());
  6565. req.headers.emplace("Accept", "*/*");
  6566. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6567. req.headers.emplace(
  6568. "Header-Name",
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6594. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6595. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6596. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6597. "@@@@@@@@@@@@@@@@");
  6598. auto res = std::make_shared<Response>();
  6599. auto error = Error::Success;
  6600. auto ret = cli_.send(req, *res, error);
  6601. ASSERT_TRUE(ret);
  6602. EXPECT_EQ(StatusCode::OK_200, res->status);
  6603. }
  6604. TEST_F(ServerTest, LongQueryValue) {
  6605. auto start = std::chrono::high_resolution_clock::now();
  6606. cli_.set_keep_alive(true);
  6607. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6608. auto end = std::chrono::high_resolution_clock::now();
  6609. auto elapsed =
  6610. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6611. .count();
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6614. EXPECT_LE(elapsed, 1000);
  6615. EXPECT_EQ("close", res->get_header_value("Connection"));
  6616. EXPECT_FALSE(cli_.is_socket_open());
  6617. }
  6618. TEST_F(ServerTest, TooLongQueryValue) {
  6619. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6620. ASSERT_FALSE(res);
  6621. EXPECT_EQ(Error::Read, res.error());
  6622. }
  6623. TEST_F(ServerTest, TooLongHeader) {
  6624. Request req;
  6625. req.method = "GET";
  6626. req.path = "/hi";
  6627. std::string host_and_port;
  6628. host_and_port += HOST;
  6629. host_and_port += ":";
  6630. host_and_port += std::to_string(PORT);
  6631. req.headers.emplace("Host", host_and_port.c_str());
  6632. req.headers.emplace("Accept", "*/*");
  6633. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6634. req.headers.emplace(
  6635. "Header-Name",
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6664. "@@@@@@@@@@@@@@@@@");
  6665. auto res = std::make_shared<Response>();
  6666. auto error = Error::Success;
  6667. auto ret = cli_.send(req, *res, error);
  6668. ASSERT_TRUE(ret);
  6669. EXPECT_EQ(StatusCode::OK_200, res->status);
  6670. }
  6671. TEST_F(ServerTest, HeaderCountAtLimit) {
  6672. // Test with headers just under the 100 limit
  6673. httplib::Headers headers;
  6674. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6675. // This should keep us just under the 100 header limit
  6676. for (int i = 0; i < 95; i++) {
  6677. std::string name = "X-Test-Header-" + std::to_string(i);
  6678. std::string value = "value" + std::to_string(i);
  6679. headers.emplace(name, value);
  6680. }
  6681. // This should work fine as we're under the limit
  6682. auto res = cli_.Get("/hi", headers);
  6683. EXPECT_TRUE(res);
  6684. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6685. }
  6686. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6687. // Test with many headers to exceed the 100 limit
  6688. httplib::Headers headers;
  6689. // Add 150 headers to definitely exceed the 100 limit
  6690. for (int i = 0; i < 150; i++) {
  6691. std::string name = "X-Test-Header-" + std::to_string(i);
  6692. std::string value = "value" + std::to_string(i);
  6693. headers.emplace(name, value);
  6694. }
  6695. // This should fail due to exceeding header count limit
  6696. cli_.set_keep_alive(true);
  6697. auto res = cli_.Get("/hi", headers);
  6698. // The server should respond with 400 Bad Request
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6701. EXPECT_EQ("close", res->get_header_value("Connection"));
  6702. EXPECT_FALSE(cli_.is_socket_open());
  6703. }
  6704. TEST_F(ServerTest, PercentEncoding) {
  6705. auto res = cli_.Get("/e%6edwith%");
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ(StatusCode::OK_200, res->status);
  6708. }
  6709. TEST_F(ServerTest, PercentEncodingUnicode) {
  6710. auto res = cli_.Get("/e%u006edwith%");
  6711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6712. EXPECT_EQ(StatusCode::OK_200, res->status);
  6713. }
  6714. TEST_F(ServerTest, InvalidPercentEncoding) {
  6715. auto res = cli_.Get("/%endwith%");
  6716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6717. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6718. }
  6719. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6720. auto res = cli_.Get("/%uendwith%");
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6723. }
  6724. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6725. auto res = cli_.Get("/hello?aaa=bbb%");
  6726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6727. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6728. }
  6729. TEST_F(ServerTest, PlusSignEncoding) {
  6730. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ(StatusCode::OK_200, res->status);
  6733. EXPECT_EQ("a +b", res->body);
  6734. }
  6735. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6736. // This test simulates a potential DoS attack using many headers
  6737. // to verify our security fix prevents memory exhaustion
  6738. httplib::Headers attack_headers;
  6739. // Attempt to add many headers like an attacker would (200 headers to far
  6740. // exceed limit)
  6741. for (int i = 0; i < 200; i++) {
  6742. std::string name = "X-Attack-Header-" + std::to_string(i);
  6743. std::string value = "attack_payload_" + std::to_string(i);
  6744. attack_headers.emplace(name, value);
  6745. }
  6746. // Try to POST with excessive headers
  6747. cli_.set_keep_alive(true);
  6748. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6749. // Should either fail or return 400 Bad Request due to security limit
  6750. if (res) {
  6751. // If we get a response, it should be 400 Bad Request
  6752. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6753. EXPECT_EQ("close", res->get_header_value("Connection"));
  6754. }
  6755. EXPECT_FALSE(cli_.is_socket_open());
  6756. }
  6757. TEST_F(ServerTest, MultipartFormData) {
  6758. UploadFormDataItems items = {
  6759. {"text1", "text default", "", ""},
  6760. {"text2", "aωb", "", ""},
  6761. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6762. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6763. {"file3", "", "", "application/octet-stream"},
  6764. {"file4", "", "", " application/json tmp-string "}};
  6765. auto res = cli_.Post("/multipart", items);
  6766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6767. EXPECT_EQ(StatusCode::OK_200, res->status);
  6768. }
  6769. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6770. UploadFormDataItems items = {
  6771. {"text", "default text", "", ""},
  6772. {"multi_text1", "aaaaa", "", ""},
  6773. {"multi_text1", "bbbbb", "", ""},
  6774. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6775. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6776. "application/json"},
  6777. };
  6778. auto res = cli_.Post("/multipart/multi_file_values", items);
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. }
  6782. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6783. auto res = cli_.Get("/hi");
  6784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6785. EXPECT_EQ(StatusCode::OK_200, res->status);
  6786. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6787. EXPECT_EQ("Hello World!", res->body);
  6788. }
  6789. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6790. Request req;
  6791. req.method = "POST";
  6792. req.path = "/chunked";
  6793. std::string host_and_port;
  6794. host_and_port += HOST;
  6795. host_and_port += ":";
  6796. host_and_port += std::to_string(PORT);
  6797. req.headers.emplace("Host", host_and_port.c_str());
  6798. req.headers.emplace("Accept", "*/*");
  6799. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6800. req.headers.emplace("Content-Type", "text/plain");
  6801. req.headers.emplace("Content-Length", "0");
  6802. req.headers.emplace(
  6803. "Transfer-Encoding",
  6804. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6805. // Client does not chunk, so make a chunked body manually.
  6806. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6807. auto res = std::make_shared<Response>();
  6808. auto error = Error::Success;
  6809. auto ret = cli_.send(req, *res, error);
  6810. ASSERT_TRUE(ret);
  6811. EXPECT_EQ(StatusCode::OK_200, res->status);
  6812. }
  6813. template <typename ClientT>
  6814. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6815. int expected_status) {
  6816. Request req;
  6817. req.method = "POST";
  6818. req.path = "/chunked";
  6819. std::string host_and_port;
  6820. host_and_port += HOST;
  6821. host_and_port += ":";
  6822. host_and_port += std::to_string(PORT);
  6823. req.headers.emplace("Host", host_and_port.c_str());
  6824. req.headers.emplace("Content-Length", "0");
  6825. req.headers.emplace("Transfer-Encoding", "chunked");
  6826. req.body = body;
  6827. auto res = std::make_shared<Response>();
  6828. auto error = Error::Success;
  6829. ASSERT_TRUE(cli.send(req, *res, error));
  6830. EXPECT_EQ(expected_status, res->status);
  6831. }
  6832. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6833. // rather than treat them as valid lengths.
  6834. template <typename ClientT>
  6835. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6836. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6837. }
  6838. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6839. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6840. }
  6841. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6842. expect_chunked_body_rejected(
  6843. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6844. }
  6845. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6846. // chunk-size line carries no CR, LF or other control character ahead of its
  6847. // terminator. Such a line must be refused rather than read as extension text.
  6848. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6849. expect_chunked_body_rejected(
  6850. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6851. }
  6852. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6853. expect_chunked_body_rejected(
  6854. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6855. }
  6856. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6857. expect_chunked_body_rejected(
  6858. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6859. }
  6860. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6861. // The literal stays split: a hex escape consumes every hex digit that
  6862. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6863. expect_chunked_body_rejected(
  6864. cli_, "4;a\x01"
  6865. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6866. }
  6867. // The bytes around chunk data are no payload, so they cannot ride on the
  6868. // payload limit
  6869. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6870. // Small enough that the whole request is sent before the server turns it
  6871. // down, yet past the limit by the last chunks
  6872. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  6873. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  6874. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  6875. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6876. SCOPED_TRACE(size_line.substr(0, 2));
  6877. std::string body;
  6878. for (auto c : std::string("dechunked post body")) {
  6879. body += size_line + "\r\n" + c + "\r\n";
  6880. }
  6881. body += "0\r\n\r\n";
  6882. expect_chunked_body_rejected(cli_, body.c_str());
  6883. }
  6884. }
  6885. TEST_F(ServerTest, AcceptsChunkExtension) {
  6886. expect_chunked_body_status(cli_,
  6887. "4;name=value\r\ndech\r\n"
  6888. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6889. "0;last\r\n\r\n",
  6890. StatusCode::OK_200);
  6891. }
  6892. TEST_F(ServerTest, GetStreamed2) {
  6893. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6895. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6896. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6897. EXPECT_EQ(true, res->has_header("Content-Range"));
  6898. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6899. EXPECT_EQ(std::string("ab"), res->body);
  6900. }
  6901. TEST_F(ServerTest, GetStreamed) {
  6902. auto res = cli_.Get("/streamed");
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_EQ(StatusCode::OK_200, res->status);
  6905. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6906. EXPECT_EQ(std::string("aaabbb"), res->body);
  6907. }
  6908. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6909. auto res = cli_.Get("/streamed-without-length",
  6910. Headers{make_range_header({{0, -1}})});
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ(StatusCode::OK_200, res->status);
  6913. EXPECT_EQ(false, res->has_header("Content-Length"));
  6914. EXPECT_EQ(false, res->has_header("Content-Range"));
  6915. EXPECT_EQ(std::string("abcdefg"), res->body);
  6916. }
  6917. TEST_F(ServerTest, GetStreamedWithRange1) {
  6918. auto res =
  6919. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6922. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6923. EXPECT_EQ(true, res->has_header("Content-Range"));
  6924. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6925. EXPECT_EQ(std::string("def"), res->body);
  6926. }
  6927. TEST_F(ServerTest, GetStreamedWithRange2) {
  6928. auto res =
  6929. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6932. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6933. EXPECT_EQ(true, res->has_header("Content-Range"));
  6934. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6935. EXPECT_EQ(std::string("bcdefg"), res->body);
  6936. }
  6937. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6938. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6941. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6942. EXPECT_EQ(true, res->has_header("Content-Range"));
  6943. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6944. EXPECT_EQ(std::string("efg"), res->body);
  6945. }
  6946. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6947. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6948. // the entire representation.
  6949. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6950. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6953. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6954. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6955. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6956. }
  6957. }
  6958. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6959. auto res =
  6960. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6963. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6964. EXPECT_EQ(false, res->has_header("Content-Range"));
  6965. EXPECT_EQ(0U, res->body.size());
  6966. }
  6967. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6968. // Only a 206 is served as a partial representation. Under any other status
  6969. // `apply_ranges()` reported the full content length, so the body must match
  6970. // that header, and the content provider must never be asked for an offset
  6971. // outside the representation.
  6972. auto check = [&](int status, const char *range) {
  6973. auto path =
  6974. std::string("/streamed-with-range?status=") + std::to_string(status);
  6975. auto ctx = path + " Range: " + range;
  6976. auto res = cli_.Get(path, Headers{{"Range", range}});
  6977. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6978. EXPECT_EQ(status, res->status) << ctx;
  6979. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6980. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6981. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6982. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6983. };
  6984. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6985. check(403, "bytes=3-5");
  6986. // The offset is far past the representation.
  6987. check(403, "bytes=100000-100200");
  6988. // `first_pos` is still -1 here, and the bounds asserts in
  6989. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6990. check(403, "bytes=-3");
  6991. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6992. // multipart branch would have written one that is empty.
  6993. check(403, "bytes=1-2, 4-5");
  6994. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6995. // covers the whole representation.
  6996. check(200, "bytes=3-5");
  6997. check(200, "bytes=1-2, 4-5");
  6998. }
  6999. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7000. auto res =
  7001. cli_.Get("/streamed-with-range",
  7002. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7003. "92233720368547758079223372036854775807"}});
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7006. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7007. EXPECT_EQ(false, res->has_header("Content-Range"));
  7008. EXPECT_EQ(0U, res->body.size());
  7009. }
  7010. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7011. auto res = cli_.Get(
  7012. "/with-range",
  7013. Headers{{"Range",
  7014. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7015. {"Accept-Encoding", ""}});
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7018. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7019. EXPECT_EQ(true, res->has_header("Content-Range"));
  7020. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7021. EXPECT_EQ(std::string("abcdefg"), res->body);
  7022. }
  7023. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7024. auto res = cli_.Get("/with-range", Headers{
  7025. {"Range", "bytes=0-"},
  7026. {"Accept-Encoding", ""},
  7027. });
  7028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7029. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7030. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7031. EXPECT_EQ(true, res->has_header("Content-Range"));
  7032. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7033. EXPECT_EQ(std::string("abcdefg"), res->body);
  7034. }
  7035. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7036. auto res = cli_.Get("/streamed-with-range",
  7037. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7040. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7041. EXPECT_EQ(false, res->has_header("Content-Range"));
  7042. EXPECT_EQ(267U, res->body.size());
  7043. // Check that both range contents are present
  7044. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7045. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7046. // Check that Content-Range headers are present for both ranges
  7047. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7048. std::string::npos);
  7049. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7050. std::string::npos);
  7051. }
  7052. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7053. Ranges ranges;
  7054. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7055. ranges.emplace_back(0, -1);
  7056. }
  7057. auto res = cli_.Get("/streamed-with-range?error",
  7058. Headers{{make_range_header(ranges)}});
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7061. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7062. EXPECT_EQ(false, res->has_header("Content-Range"));
  7063. EXPECT_EQ(0U, res->body.size());
  7064. }
  7065. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7066. auto res = cli_.Get("/streamed-with-range",
  7067. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7069. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7070. EXPECT_EQ(5U, res->body.size());
  7071. // Check that overlapping ranges are coalesced into a single range
  7072. EXPECT_EQ("bcdef", res->body);
  7073. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7074. // Should be single range, not multipart
  7075. EXPECT_TRUE(res->has_header("Content-Range"));
  7076. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7077. }
  7078. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7079. auto res = cli_.Get("/streamed-with-range",
  7080. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7083. EXPECT_EQ(268U, res->body.size());
  7084. // Check that both range contents are present
  7085. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7086. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7087. // Check that Content-Range headers are present for both ranges
  7088. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7089. std::string::npos);
  7090. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7091. std::string::npos);
  7092. }
  7093. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7094. auto res = cli_.Get("/streamed-with-range",
  7095. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7098. EXPECT_EQ(269U, res->body.size());
  7099. // Check that both duplicate range contents are present
  7100. size_t first_abc = res->body.find("abc\r\n");
  7101. EXPECT_TRUE(first_abc != std::string::npos);
  7102. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7103. EXPECT_TRUE(second_abc != std::string::npos);
  7104. // Check that Content-Range headers are present for both ranges
  7105. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7106. EXPECT_TRUE(first_range != std::string::npos);
  7107. size_t second_range =
  7108. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7109. EXPECT_TRUE(second_range != std::string::npos);
  7110. }
  7111. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7112. auto res =
  7113. cli_.Get("/streamed-with-range?error",
  7114. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7117. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7118. EXPECT_EQ(false, res->has_header("Content-Range"));
  7119. EXPECT_EQ(0U, res->body.size());
  7120. }
  7121. TEST_F(ServerTest, GetStreamedEndless) {
  7122. uint64_t offset = 0;
  7123. auto res = cli_.Get("/streamed-cancel",
  7124. [&](const char * /*data*/, uint64_t data_length) {
  7125. if (offset < 100) {
  7126. offset += data_length;
  7127. return true;
  7128. }
  7129. return false;
  7130. });
  7131. ASSERT_TRUE(!res);
  7132. EXPECT_EQ(Error::Canceled, res.error());
  7133. }
  7134. TEST_F(ServerTest, ClientStop) {
  7135. std::atomic_size_t count{4};
  7136. std::vector<std::thread> threads;
  7137. for (auto i = count.load(); i != 0; --i) {
  7138. threads.emplace_back([&]() {
  7139. auto res = cli_.Get("/streamed-cancel",
  7140. [&](const char *, uint64_t) { return true; });
  7141. --count;
  7142. ASSERT_TRUE(!res);
  7143. EXPECT_TRUE(res.error() == Error::Canceled ||
  7144. res.error() == Error::Read || res.error() == Error::Write);
  7145. });
  7146. }
  7147. std::this_thread::sleep_for(std::chrono::seconds(2));
  7148. while (count != 0) {
  7149. cli_.stop();
  7150. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7151. }
  7152. for (auto &t : threads) {
  7153. t.join();
  7154. }
  7155. }
  7156. TEST_F(ServerTest, GetWithRange1) {
  7157. auto res = cli_.Get("/with-range", Headers{
  7158. make_range_header({{3, 5}}),
  7159. {"Accept-Encoding", ""},
  7160. });
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7163. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7164. EXPECT_EQ(true, res->has_header("Content-Range"));
  7165. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7166. EXPECT_EQ(std::string("def"), res->body);
  7167. }
  7168. TEST_F(ServerTest, GetWithRange2) {
  7169. auto res = cli_.Get("/with-range", Headers{
  7170. make_range_header({{1, -1}}),
  7171. {"Accept-Encoding", ""},
  7172. });
  7173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7175. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7176. EXPECT_EQ(true, res->has_header("Content-Range"));
  7177. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7178. EXPECT_EQ(std::string("bcdefg"), res->body);
  7179. }
  7180. TEST_F(ServerTest, GetWithRange3) {
  7181. auto res = cli_.Get("/with-range", Headers{
  7182. make_range_header({{0, 0}}),
  7183. {"Accept-Encoding", ""},
  7184. });
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7187. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(true, res->has_header("Content-Range"));
  7189. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7190. EXPECT_EQ(std::string("a"), res->body);
  7191. }
  7192. TEST_F(ServerTest, GetWithRange4) {
  7193. auto res = cli_.Get("/with-range", Headers{
  7194. make_range_header({{-1, 2}}),
  7195. {"Accept-Encoding", ""},
  7196. });
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7199. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7200. EXPECT_EQ(true, res->has_header("Content-Range"));
  7201. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7202. EXPECT_EQ(std::string("fg"), res->body);
  7203. }
  7204. TEST_F(ServerTest, GetWithRange5) {
  7205. auto res = cli_.Get("/with-range", Headers{
  7206. make_range_header({{0, 5}}),
  7207. {"Accept-Encoding", ""},
  7208. });
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7211. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7212. EXPECT_EQ(true, res->has_header("Content-Range"));
  7213. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7214. EXPECT_EQ(std::string("abcdef"), res->body);
  7215. }
  7216. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7217. auto res =
  7218. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7220. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7221. }
  7222. TEST_F(ServerTest, GetWithRangeMultipart) {
  7223. auto res =
  7224. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7227. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7228. EXPECT_EQ(false, res->has_header("Content-Range"));
  7229. EXPECT_EQ(267U, res->body.size());
  7230. }
  7231. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7232. auto res = cli_.Get("/with-range",
  7233. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7236. }
  7237. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7238. auto res = cli_.Get("/with-range-customized-response",
  7239. Headers{{make_range_header({{1, 2}})}});
  7240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7241. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7242. EXPECT_EQ(true, res->has_header("Content-Length"));
  7243. EXPECT_EQ(false, res->has_header("Content-Range"));
  7244. EXPECT_EQ(JSON_DATA, res->body);
  7245. }
  7246. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7247. auto res = cli_.Get("/with-range-customized-response",
  7248. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7251. EXPECT_EQ(true, res->has_header("Content-Length"));
  7252. EXPECT_EQ(false, res->has_header("Content-Range"));
  7253. EXPECT_EQ(JSON_DATA, res->body);
  7254. }
  7255. TEST_F(ServerTest, Issue1772) {
  7256. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7259. }
  7260. TEST_F(ServerTest, Issue609) {
  7261. auto res = cli_.Delete("/issue609");
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::OK_200, res->status);
  7264. EXPECT_EQ(std::string("ok"), res->body);
  7265. }
  7266. TEST_F(ServerTest, GetStreamedChunked) {
  7267. auto res = cli_.Get("/streamed-chunked");
  7268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7269. EXPECT_EQ(StatusCode::OK_200, res->status);
  7270. EXPECT_EQ(std::string("123456789"), res->body);
  7271. }
  7272. TEST_F(ServerTest, GetStreamedChunked2) {
  7273. auto res = cli_.Get("/streamed-chunked2");
  7274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7275. EXPECT_EQ(StatusCode::OK_200, res->status);
  7276. EXPECT_EQ(std::string("123456789"), res->body);
  7277. }
  7278. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7279. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ(StatusCode::OK_200, res->status);
  7282. EXPECT_EQ(std::string("123456789"), res->body);
  7283. EXPECT_TRUE(res->has_header("Trailer"));
  7284. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7285. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7286. // Trailers are now stored separately from headers (security fix)
  7287. EXPECT_EQ(2U, res->trailers.size());
  7288. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7289. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7290. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7291. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7292. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7293. // Verify trailers are NOT in headers (security verification)
  7294. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7295. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7296. }
  7297. TEST_F(ServerTest, LargeChunkedPost) {
  7298. Request req;
  7299. req.method = "POST";
  7300. req.path = "/large-chunked";
  7301. std::string host_and_port;
  7302. host_and_port += HOST;
  7303. host_and_port += ":";
  7304. host_and_port += std::to_string(PORT);
  7305. req.headers.emplace("Host", host_and_port.c_str());
  7306. req.headers.emplace("Accept", "*/*");
  7307. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7308. req.headers.emplace("Content-Type", "text/plain");
  7309. req.headers.emplace("Content-Length", "0");
  7310. req.headers.emplace("Transfer-Encoding", "chunked");
  7311. std::string long_string(30 * 1024u, 'a');
  7312. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7313. // Attempt to make a large enough post to exceed OS buffers, to test that
  7314. // the server handles short reads if the full chunk data isn't available.
  7315. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7316. auto res = std::make_shared<Response>();
  7317. auto error = Error::Success;
  7318. auto ret = cli_.send(req, *res, error);
  7319. ASSERT_TRUE(ret);
  7320. EXPECT_EQ(StatusCode::OK_200, res->status);
  7321. }
  7322. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7323. auto res = cli_.Get("/remote_addr");
  7324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7325. EXPECT_EQ(StatusCode::OK_200, res->status);
  7326. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7327. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7328. }
  7329. TEST_F(ServerTest, GetMethodLocalAddr) {
  7330. auto res = cli_.Get("/local_addr");
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::OK_200, res->status);
  7333. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7334. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7335. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7336. }
  7337. TEST_F(ServerTest, HTTPResponseSplitting) {
  7338. auto res = cli_.Get("/http_response_splitting");
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ(StatusCode::OK_200, res->status);
  7341. }
  7342. TEST_F(ServerTest, SlowRequest) {
  7343. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7344. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7345. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7346. }
  7347. #if 0
  7348. TEST_F(ServerTest, SlowPost) {
  7349. char buffer[64 * 1024];
  7350. memset(buffer, 0x42, sizeof(buffer));
  7351. auto res = cli_.Post(
  7352. "/slowpost", 64 * 1024 * 1024,
  7353. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7354. auto ret = sink.write(buffer, sizeof(buffer));
  7355. EXPECT_TRUE(ret);
  7356. return true;
  7357. },
  7358. "text/plain");
  7359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7360. EXPECT_EQ(StatusCode::OK_200, res->status);
  7361. }
  7362. TEST_F(ServerTest, SlowPostFail) {
  7363. char buffer[64 * 1024];
  7364. memset(buffer, 0x42, sizeof(buffer));
  7365. cli_.set_write_timeout(std::chrono::seconds(0));
  7366. auto res = cli_.Post(
  7367. "/slowpost", 64 * 1024 * 1024,
  7368. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7369. sink.write(buffer, sizeof(buffer));
  7370. return true;
  7371. },
  7372. "text/plain");
  7373. ASSERT_TRUE(!res);
  7374. EXPECT_EQ(Error::Write, res.error());
  7375. }
  7376. #endif
  7377. TEST_F(ServerTest, Put) {
  7378. auto res = cli_.Put("/put", "PUT", "text/plain");
  7379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7380. EXPECT_EQ(StatusCode::OK_200, res->status);
  7381. EXPECT_EQ("PUT", res->body);
  7382. }
  7383. TEST_F(ServerTest, PutWithContentProvider) {
  7384. auto res = cli_.Put(
  7385. "/put", 3,
  7386. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7387. sink.os << "PUT";
  7388. return true;
  7389. },
  7390. "text/plain");
  7391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7392. EXPECT_EQ(StatusCode::OK_200, res->status);
  7393. EXPECT_EQ("PUT", res->body);
  7394. }
  7395. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7396. auto res = cli_.Post(
  7397. "/post", 42,
  7398. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7399. return false;
  7400. },
  7401. "text/plain");
  7402. ASSERT_TRUE(!res);
  7403. EXPECT_EQ(Error::Canceled, res.error());
  7404. }
  7405. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7406. auto res = cli_.Put(
  7407. "/put",
  7408. [](size_t /*offset*/, DataSink &sink) {
  7409. sink.os << "PUT";
  7410. sink.done();
  7411. return true;
  7412. },
  7413. "text/plain");
  7414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7415. EXPECT_EQ(StatusCode::OK_200, res->status);
  7416. EXPECT_EQ("PUT", res->body);
  7417. }
  7418. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7419. auto res = cli_.Post(
  7420. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7421. "text/plain");
  7422. ASSERT_TRUE(!res);
  7423. EXPECT_EQ(Error::Canceled, res.error());
  7424. }
  7425. TEST_F(ServerTest, PostLoopBack) {
  7426. std::string body;
  7427. auto res = cli_.Post(
  7428. "/post-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, PutLoopBack) {
  7446. std::string body;
  7447. auto res = cli_.Put(
  7448. "/put-loopback", 9,
  7449. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7450. EXPECT_EQ(9u, length);
  7451. sink.write("123", 3);
  7452. sink.write("456", 3);
  7453. sink.write("789", 3);
  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. TEST_F(ServerTest, PatchLoopBack) {
  7466. std::string body;
  7467. auto res = cli_.Patch(
  7468. "/patch-loopback", 9,
  7469. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7470. EXPECT_EQ(9u, length);
  7471. sink.write("123", 3);
  7472. sink.write("456", 3);
  7473. sink.write("789", 3);
  7474. return true;
  7475. },
  7476. "text/plain",
  7477. [&body](const char *data, size_t data_length) {
  7478. body.append(data, data_length);
  7479. return true;
  7480. });
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. EXPECT_EQ("123456789", body);
  7484. }
  7485. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7486. std::string body;
  7487. auto res = cli_.Post(
  7488. "/post-loopback",
  7489. [](size_t /*offset*/, DataSink &sink) {
  7490. sink.write("123", 3);
  7491. sink.write("456", 3);
  7492. sink.write("789", 3);
  7493. sink.done();
  7494. return true;
  7495. },
  7496. "text/plain",
  7497. [&body](const char *data, size_t data_length) {
  7498. body.append(data, data_length);
  7499. return true;
  7500. });
  7501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7502. EXPECT_EQ(StatusCode::OK_200, res->status);
  7503. EXPECT_EQ("123456789", body);
  7504. }
  7505. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7506. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7507. cli_.set_compress(true);
  7508. auto res = cli_.Put(
  7509. "/put", 3,
  7510. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7511. sink.os << "PUT";
  7512. return true;
  7513. },
  7514. "text/plain");
  7515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. EXPECT_EQ("PUT", res->body);
  7518. }
  7519. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7520. cli_.set_compress(true);
  7521. auto res = cli_.Post(
  7522. "/post", 42,
  7523. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7524. return false;
  7525. },
  7526. "text/plain");
  7527. ASSERT_TRUE(!res);
  7528. EXPECT_EQ(Error::Canceled, res.error());
  7529. }
  7530. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7531. cli_.set_compress(true);
  7532. auto res = cli_.Put(
  7533. "/put",
  7534. [](size_t /*offset*/, DataSink &sink) {
  7535. sink.os << "PUT";
  7536. sink.done();
  7537. return true;
  7538. },
  7539. "text/plain");
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::OK_200, res->status);
  7542. EXPECT_EQ("PUT", res->body);
  7543. }
  7544. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7545. cli_.set_compress(true);
  7546. auto res = cli_.Post(
  7547. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7548. "text/plain");
  7549. ASSERT_TRUE(!res);
  7550. EXPECT_EQ(Error::Canceled, res.error());
  7551. }
  7552. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7553. cli_.set_compress(true);
  7554. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. EXPECT_EQ(StatusCode::OK_200, res->status);
  7557. EXPECT_EQ(LARGE_DATA, res->body);
  7558. }
  7559. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7560. #ifdef CPPHTTPLIB_SSL_ENABLED
  7561. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7562. Client cli(s.c_str());
  7563. cli.enable_server_certificate_verification(false);
  7564. #else
  7565. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7566. Client cli(s.c_str());
  7567. #endif
  7568. cli.set_compress(true);
  7569. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7571. EXPECT_EQ(StatusCode::OK_200, res->status);
  7572. EXPECT_EQ(LARGE_DATA, res->body);
  7573. // The compressed size should be less than a 10th of the original. May vary
  7574. // depending on the zlib library.
  7575. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7576. static_cast<uint64_t>(10 * 1024 * 1024));
  7577. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7578. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7579. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7580. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7581. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7582. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7583. #endif
  7584. }
  7585. TEST_F(ServerTest, PutContentWithDeflate) {
  7586. cli_.set_compress(false);
  7587. Headers headers;
  7588. headers.emplace("Content-Encoding", "deflate");
  7589. // PUT in deflate format:
  7590. auto res = cli_.Put("/put", headers,
  7591. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7593. EXPECT_EQ(StatusCode::OK_200, res->status);
  7594. EXPECT_EQ("PUT", res->body);
  7595. }
  7596. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7597. Headers headers;
  7598. headers.emplace("Accept-Encoding", "gzip, deflate");
  7599. auto res = cli_.Get("/streamed-chunked", headers);
  7600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7601. EXPECT_EQ(StatusCode::OK_200, res->status);
  7602. EXPECT_EQ(std::string("123456789"), res->body);
  7603. }
  7604. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7605. Headers headers;
  7606. headers.emplace("Accept-Encoding", "gzip, deflate");
  7607. auto res = cli_.Get("/streamed-chunked2", headers);
  7608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7609. EXPECT_EQ(StatusCode::OK_200, res->status);
  7610. EXPECT_EQ(std::string("123456789"), res->body);
  7611. }
  7612. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7613. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. }
  7617. TEST(GzipDecompressor, ChunkedDecompression) {
  7618. std::string data;
  7619. for (size_t i = 0; i < 32 * 1024; ++i) {
  7620. data.push_back(static_cast<char>('a' + i % 26));
  7621. }
  7622. std::string compressed_data;
  7623. {
  7624. httplib::detail::gzip_compressor compressor;
  7625. bool result = compressor.compress(
  7626. data.data(), data.size(),
  7627. /*last=*/true,
  7628. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7629. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7630. compressed_data_size);
  7631. return true;
  7632. });
  7633. ASSERT_TRUE(result);
  7634. }
  7635. std::string decompressed_data;
  7636. {
  7637. httplib::detail::gzip_decompressor decompressor;
  7638. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7639. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7640. size_t chunk_size = 130;
  7641. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7642. chunk_begin += chunk_size) {
  7643. size_t current_chunk_size =
  7644. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7645. bool result = decompressor.decompress(
  7646. compressed_data.data() + chunk_begin, current_chunk_size,
  7647. [&](const char *decompressed_data_chunk,
  7648. size_t decompressed_data_chunk_size) {
  7649. decompressed_data.insert(decompressed_data.size(),
  7650. decompressed_data_chunk,
  7651. decompressed_data_chunk_size);
  7652. return true;
  7653. });
  7654. ASSERT_TRUE(result);
  7655. }
  7656. }
  7657. ASSERT_EQ(data, decompressed_data);
  7658. }
  7659. TEST(GzipDecompressor, DeflateDecompression) {
  7660. std::string original_text = "Raw deflate without gzip";
  7661. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7662. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7663. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7664. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7665. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7666. std::string decompressed_data;
  7667. {
  7668. httplib::detail::gzip_decompressor decompressor;
  7669. bool result = decompressor.decompress(
  7670. compressed_data.data(), compressed_data.size(),
  7671. [&](const char *decompressed_data_chunk,
  7672. size_t decompressed_data_chunk_size) {
  7673. decompressed_data.insert(decompressed_data.size(),
  7674. decompressed_data_chunk,
  7675. decompressed_data_chunk_size);
  7676. return true;
  7677. });
  7678. ASSERT_TRUE(result);
  7679. }
  7680. ASSERT_EQ(original_text, decompressed_data);
  7681. }
  7682. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7683. std::string original_text = "Raw deflate without gzip";
  7684. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7685. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7686. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7687. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7688. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7689. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7690. std::string decompressed_data;
  7691. {
  7692. httplib::detail::gzip_decompressor decompressor;
  7693. bool result = decompressor.decompress(
  7694. compressed_data.data(), compressed_data.size(),
  7695. [&](const char *decompressed_data_chunk,
  7696. size_t decompressed_data_chunk_size) {
  7697. decompressed_data.insert(decompressed_data.size(),
  7698. decompressed_data_chunk,
  7699. decompressed_data_chunk_size);
  7700. return true;
  7701. });
  7702. ASSERT_TRUE(result);
  7703. }
  7704. ASSERT_EQ(original_text, decompressed_data);
  7705. }
  7706. #endif
  7707. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7708. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7709. Headers headers;
  7710. headers.emplace("Accept-Encoding", "br");
  7711. auto res = cli_.Get("/streamed-chunked", headers);
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. EXPECT_EQ(std::string("123456789"), res->body);
  7715. }
  7716. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7717. Headers headers;
  7718. headers.emplace("Accept-Encoding", "br");
  7719. auto res = cli_.Get("/streamed-chunked2", headers);
  7720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7721. EXPECT_EQ(StatusCode::OK_200, res->status);
  7722. EXPECT_EQ(std::string("123456789"), res->body);
  7723. }
  7724. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7725. cli_.set_compress(true);
  7726. auto res = cli_.Put(
  7727. "/put", 3,
  7728. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7729. sink.os << "PUT";
  7730. return true;
  7731. },
  7732. "text/plain");
  7733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7734. EXPECT_EQ(StatusCode::OK_200, res->status);
  7735. EXPECT_EQ("PUT", res->body);
  7736. }
  7737. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7738. cli_.set_compress(true);
  7739. auto res = cli_.Put(
  7740. "/put",
  7741. [](size_t /*offset*/, DataSink &sink) {
  7742. sink.os << "PUT";
  7743. sink.done();
  7744. return true;
  7745. },
  7746. "text/plain");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. EXPECT_EQ("PUT", res->body);
  7750. }
  7751. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7752. cli_.set_compress(true);
  7753. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7755. EXPECT_EQ(StatusCode::OK_200, res->status);
  7756. EXPECT_EQ(LARGE_DATA, res->body);
  7757. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7758. }
  7759. #endif
  7760. TEST_F(ServerTest, Patch) {
  7761. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7763. EXPECT_EQ(StatusCode::OK_200, res->status);
  7764. EXPECT_EQ("PATCH", res->body);
  7765. }
  7766. TEST_F(ServerTest, Delete) {
  7767. auto res = cli_.Delete("/delete");
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. EXPECT_EQ("DELETE", res->body);
  7771. }
  7772. TEST_F(ServerTest, DeleteContentReceiver) {
  7773. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7775. EXPECT_EQ(StatusCode::OK_200, res->status);
  7776. EXPECT_EQ("content", res->body);
  7777. }
  7778. TEST_F(ServerTest, Options) {
  7779. auto res = cli_.Options("*");
  7780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7781. EXPECT_EQ(StatusCode::OK_200, res->status);
  7782. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7783. EXPECT_TRUE(res->body.empty());
  7784. }
  7785. TEST_F(ServerTest, URL) {
  7786. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7788. EXPECT_EQ(StatusCode::OK_200, res->status);
  7789. }
  7790. TEST_F(ServerTest, ArrayParam) {
  7791. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7793. EXPECT_EQ(StatusCode::OK_200, res->status);
  7794. }
  7795. TEST_F(ServerTest, ArrayParamValues) {
  7796. auto res =
  7797. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7799. EXPECT_EQ(StatusCode::OK_200, res->status);
  7800. }
  7801. TEST_F(ServerTest, NoMultipleHeaders) {
  7802. Headers headers = {{"Content-Length", "5"}};
  7803. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7804. "text/plain");
  7805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7806. EXPECT_EQ(StatusCode::OK_200, res->status);
  7807. }
  7808. TEST_F(ServerTest, PostContentReceiver) {
  7809. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7811. ASSERT_EQ(StatusCode::OK_200, res->status);
  7812. ASSERT_EQ("content", res->body);
  7813. }
  7814. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7815. UploadFormDataItems items = {
  7816. {"text1", "text default", "", ""},
  7817. {"text2", "aωb", "", ""},
  7818. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7819. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7820. {"file3", "", "", "application/octet-stream"},
  7821. };
  7822. auto res = cli_.Post("/content_receiver", items);
  7823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7824. EXPECT_EQ(StatusCode::OK_200, res->status);
  7825. }
  7826. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7827. UploadFormDataItems items = {
  7828. {"text1", "text default", "", ""},
  7829. {"text2", "aωb", "", ""},
  7830. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7831. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7832. {"file3", "", "", "application/octet-stream"},
  7833. };
  7834. auto boundary = std::string("+++++");
  7835. std::string body;
  7836. for (const auto &item : items) {
  7837. body += "--" + boundary + "\r\n";
  7838. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7839. if (!item.filename.empty()) {
  7840. body += "; filename=\"" + item.filename + "\"";
  7841. }
  7842. body += "\r\n";
  7843. if (!item.content_type.empty()) {
  7844. body += "Content-Type: " + item.content_type + "\r\n";
  7845. }
  7846. body += "\r\n";
  7847. body += item.content + "\r\n";
  7848. }
  7849. body += "--" + boundary + "--\r\n";
  7850. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7851. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7853. EXPECT_EQ(StatusCode::OK_200, res->status);
  7854. }
  7855. TEST(MultipartFormDataTest, FieldEscaping) {
  7856. Server svr;
  7857. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7858. const ContentReader &content_reader) {
  7859. ASSERT_TRUE(req.is_multipart_form_data());
  7860. std::vector<FormData> received;
  7861. content_reader(
  7862. [&](const FormData &file) {
  7863. received.push_back(file);
  7864. return true;
  7865. },
  7866. [&](const char *data, size_t data_length) {
  7867. received.back().content.append(data, data_length);
  7868. return true;
  7869. });
  7870. // '"', CR and LF in names and filenames are escaped following the
  7871. // WHATWG HTML standard, so each part still parses as a single part
  7872. // with no injected headers. Content types get CR/LF escaped too,
  7873. // while '"' (legal there, e.g. quoted charset) is preserved.
  7874. ASSERT_EQ(4U, received.size());
  7875. EXPECT_EQ("na%22me", received[0].name);
  7876. EXPECT_EQ("quoted name", received[0].content);
  7877. EXPECT_EQ("file", received[1].name);
  7878. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7879. received[1].filename);
  7880. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7881. EXPECT_EQ("injected", received[1].content);
  7882. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7883. EXPECT_EQ("my%22file.txt", received[2].filename);
  7884. EXPECT_EQ("cr lf name", received[2].content);
  7885. EXPECT_EQ("typed", received[3].name);
  7886. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7887. received[3].content_type);
  7888. EXPECT_EQ("typed content", received[3].content);
  7889. });
  7890. auto port = svr.bind_to_any_port("localhost");
  7891. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7892. auto se = detail::scope_exit([&] {
  7893. svr.stop();
  7894. t.join();
  7895. ASSERT_FALSE(svr.is_running());
  7896. });
  7897. svr.wait_until_ready();
  7898. Client cli("localhost", port);
  7899. UploadFormDataItems items = {
  7900. {"na\"me", "quoted name", "", ""},
  7901. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7902. "application/octet-stream"},
  7903. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7904. {"typed", "typed content", "",
  7905. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7906. };
  7907. auto res = cli.Post("/post", items);
  7908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7909. EXPECT_EQ(StatusCode::OK_200, res->status);
  7910. }
  7911. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7912. const UploadFormDataItems items = {
  7913. {"name1", "Content 1", "", ""},
  7914. {"name2", "Content 2", "file2.txt", "text/plain"},
  7915. };
  7916. Server svr;
  7917. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7918. const ContentReader &content_reader) {
  7919. ASSERT_TRUE(req.is_multipart_form_data());
  7920. std::vector<FormData> received;
  7921. content_reader(
  7922. [&](const FormData &file) {
  7923. received.push_back(file);
  7924. return true;
  7925. },
  7926. [&](const char *data, size_t data_length) {
  7927. received.back().content.append(data, data_length);
  7928. return true;
  7929. });
  7930. ASSERT_EQ(2U, received.size());
  7931. EXPECT_EQ("name1", received[0].name);
  7932. EXPECT_EQ("Content 1", received[0].content);
  7933. EXPECT_EQ("name2", received[1].name);
  7934. EXPECT_EQ("Content 2", received[1].content);
  7935. EXPECT_EQ("file2.txt", received[1].filename);
  7936. EXPECT_EQ("text/plain", received[1].content_type);
  7937. });
  7938. auto port = svr.bind_to_any_port("localhost");
  7939. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7940. auto se = detail::scope_exit([&] {
  7941. svr.stop();
  7942. t.join();
  7943. ASSERT_FALSE(svr.is_running());
  7944. });
  7945. svr.wait_until_ready();
  7946. Client cli("localhost", port);
  7947. // Whole-body serialization with a generated boundary
  7948. {
  7949. MultipartFormDataWriter writer;
  7950. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7951. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7952. writer.content_type());
  7953. auto body = writer.serialize(items);
  7954. EXPECT_EQ(body.size(), writer.content_length(items));
  7955. auto res = cli.Post("/post", body, writer.content_type());
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. }
  7959. // Per-part framing with a custom boundary via a content provider
  7960. {
  7961. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7962. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7963. MultipartFormDataWriter writer("custom-boundary_123");
  7964. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7965. std::string body;
  7966. for (const auto &item : items) {
  7967. body += writer.item_begin(item);
  7968. body += item.content;
  7969. body += MultipartFormDataWriter::item_end();
  7970. }
  7971. body += writer.finish();
  7972. EXPECT_EQ(body.size(), writer.content_length(items));
  7973. auto res = cli.Post(
  7974. "/post", body.size(),
  7975. [&](size_t offset, size_t length, DataSink &sink) {
  7976. sink.write(body.data() + offset, length);
  7977. return true;
  7978. },
  7979. writer.content_type());
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ(StatusCode::OK_200, res->status);
  7982. }
  7983. }
  7984. TEST_F(ServerTest, PostContentReceiverGzip) {
  7985. cli_.set_compress(true);
  7986. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7988. ASSERT_EQ(StatusCode::OK_200, res->status);
  7989. ASSERT_EQ("content", res->body);
  7990. }
  7991. TEST_F(ServerTest, PutContentReceiver) {
  7992. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7994. ASSERT_EQ(StatusCode::OK_200, res->status);
  7995. ASSERT_EQ("content", res->body);
  7996. }
  7997. TEST_F(ServerTest, PatchContentReceiver) {
  7998. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8000. ASSERT_EQ(StatusCode::OK_200, res->status);
  8001. ASSERT_EQ("content", res->body);
  8002. }
  8003. template <typename ClientType>
  8004. void TestWithHeadersAndContentReceiver(
  8005. ClientType &cli,
  8006. std::function<Result(ClientType &, const std::string &, const Headers &,
  8007. const std::string &, const std::string &,
  8008. ContentReceiver, DownloadProgress)>
  8009. request_func) {
  8010. Headers headers;
  8011. headers.emplace("X-Custom-Header", "test-value");
  8012. std::string received_body;
  8013. auto res = request_func(
  8014. cli, "/content_receiver", headers, "content", "application/json",
  8015. [&](const char *data, size_t data_length) {
  8016. received_body.append(data, data_length);
  8017. return true;
  8018. },
  8019. nullptr);
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_EQ(StatusCode::OK_200, res->status);
  8022. EXPECT_EQ("content", received_body);
  8023. }
  8024. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8025. #ifdef CPPHTTPLIB_SSL_ENABLED
  8026. using ClientT = SSLClient;
  8027. #else
  8028. using ClientT = Client;
  8029. #endif
  8030. TestWithHeadersAndContentReceiver<ClientT>(
  8031. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8032. const std::string &body, const std::string &content_type,
  8033. ContentReceiver receiver, DownloadProgress progress) {
  8034. return cli.Post(path, headers, body, content_type, receiver, progress);
  8035. });
  8036. }
  8037. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8038. #ifdef CPPHTTPLIB_SSL_ENABLED
  8039. using ClientT = SSLClient;
  8040. #else
  8041. using ClientT = Client;
  8042. #endif
  8043. TestWithHeadersAndContentReceiver<ClientT>(
  8044. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8045. const std::string &body, const std::string &content_type,
  8046. ContentReceiver receiver, DownloadProgress progress) {
  8047. return cli.Put(path, headers, body, content_type, receiver, progress);
  8048. });
  8049. }
  8050. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8051. #ifdef CPPHTTPLIB_SSL_ENABLED
  8052. using ClientT = SSLClient;
  8053. #else
  8054. using ClientT = Client;
  8055. #endif
  8056. TestWithHeadersAndContentReceiver<ClientT>(
  8057. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8058. const std::string &body, const std::string &content_type,
  8059. ContentReceiver receiver, DownloadProgress progress) {
  8060. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8061. });
  8062. }
  8063. template <typename ClientType>
  8064. void TestWithHeadersAndContentReceiverWithProgress(
  8065. ClientType &cli,
  8066. std::function<Result(ClientType &, const std::string &, const Headers &,
  8067. const std::string &, const std::string &,
  8068. ContentReceiver, DownloadProgress)>
  8069. request_func) {
  8070. Headers headers;
  8071. headers.emplace("X-Test-Header", "progress-test");
  8072. std::string received_body;
  8073. auto progress_called = false;
  8074. auto res = request_func(
  8075. cli, "/content_receiver", headers, "content", "text/plain",
  8076. [&](const char *data, size_t data_length) {
  8077. received_body.append(data, data_length);
  8078. return true;
  8079. },
  8080. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8081. progress_called = true;
  8082. return true;
  8083. });
  8084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8085. EXPECT_EQ(StatusCode::OK_200, res->status);
  8086. EXPECT_EQ("content", received_body);
  8087. EXPECT_TRUE(progress_called);
  8088. }
  8089. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8090. #ifdef CPPHTTPLIB_SSL_ENABLED
  8091. using ClientT = SSLClient;
  8092. #else
  8093. using ClientT = Client;
  8094. #endif
  8095. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8096. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8097. const std::string &body, const std::string &content_type,
  8098. ContentReceiver receiver, DownloadProgress progress) {
  8099. return cli.Post(path, headers, body, content_type, receiver, progress);
  8100. });
  8101. }
  8102. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8103. #ifdef CPPHTTPLIB_SSL_ENABLED
  8104. using ClientT = SSLClient;
  8105. #else
  8106. using ClientT = Client;
  8107. #endif
  8108. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8109. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8110. const std::string &body, const std::string &content_type,
  8111. ContentReceiver receiver, DownloadProgress progress) {
  8112. return cli.Put(path, headers, body, content_type, receiver, progress);
  8113. });
  8114. }
  8115. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8116. #ifdef CPPHTTPLIB_SSL_ENABLED
  8117. using ClientT = SSLClient;
  8118. #else
  8119. using ClientT = Client;
  8120. #endif
  8121. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8122. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8123. const std::string &body, const std::string &content_type,
  8124. ContentReceiver receiver, DownloadProgress progress) {
  8125. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8126. });
  8127. }
  8128. template <typename ClientType>
  8129. void TestWithHeadersAndContentReceiverError(
  8130. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8131. const Headers &, const std::string &,
  8132. const std::string &, ContentReceiver)>
  8133. request_func) {
  8134. Headers headers;
  8135. headers.emplace("X-Error-Test", "true");
  8136. std::string received_body;
  8137. auto receiver_failed = false;
  8138. auto res =
  8139. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8140. [&](const char *data, size_t data_length) {
  8141. received_body.append(data, data_length);
  8142. receiver_failed = true;
  8143. return false;
  8144. });
  8145. ASSERT_FALSE(res);
  8146. EXPECT_TRUE(receiver_failed);
  8147. }
  8148. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8149. #ifdef CPPHTTPLIB_SSL_ENABLED
  8150. using ClientT = SSLClient;
  8151. #else
  8152. using ClientT = Client;
  8153. #endif
  8154. TestWithHeadersAndContentReceiverError<ClientT>(
  8155. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8156. const std::string &body, const std::string &content_type,
  8157. ContentReceiver receiver) {
  8158. return cli.Post(path, headers, body, content_type, receiver);
  8159. });
  8160. }
  8161. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8162. #ifdef CPPHTTPLIB_SSL_ENABLED
  8163. using ClientT = SSLClient;
  8164. #else
  8165. using ClientT = Client;
  8166. #endif
  8167. TestWithHeadersAndContentReceiverError<ClientT>(
  8168. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8169. const std::string &body, const std::string &content_type,
  8170. ContentReceiver receiver) {
  8171. return cli.Put(path, headers, body, content_type, receiver);
  8172. });
  8173. }
  8174. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8175. #ifdef CPPHTTPLIB_SSL_ENABLED
  8176. using ClientT = SSLClient;
  8177. #else
  8178. using ClientT = Client;
  8179. #endif
  8180. TestWithHeadersAndContentReceiverError<ClientT>(
  8181. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8182. const std::string &body, const std::string &content_type,
  8183. ContentReceiver receiver) {
  8184. return cli.Patch(path, headers, body, content_type, receiver);
  8185. });
  8186. }
  8187. TEST_F(ServerTest, PostQueryStringAndBody) {
  8188. auto res =
  8189. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8191. ASSERT_EQ(StatusCode::OK_200, res->status);
  8192. }
  8193. TEST_F(ServerTest, HTTP2Magic) {
  8194. Request req;
  8195. req.method = "PRI";
  8196. req.path = "*";
  8197. req.body = "SM";
  8198. auto res = std::make_shared<Response>();
  8199. auto error = Error::Success;
  8200. auto ret = cli_.send(req, *res, error);
  8201. ASSERT_TRUE(ret);
  8202. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8203. }
  8204. TEST_F(ServerTest, KeepAlive) {
  8205. auto res = cli_.Get("/hi");
  8206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8207. EXPECT_EQ(StatusCode::OK_200, res->status);
  8208. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8209. EXPECT_EQ("Hello World!", res->body);
  8210. res = cli_.Get("/hi");
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8214. EXPECT_EQ("Hello World!", res->body);
  8215. res = cli_.Get("/hi");
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::OK_200, res->status);
  8218. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8219. EXPECT_EQ("Hello World!", res->body);
  8220. res = cli_.Get("/not-exist");
  8221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8223. res = cli_.Post("/empty", "", "text/plain");
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ(StatusCode::OK_200, res->status);
  8226. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8227. EXPECT_EQ("empty", res->body);
  8228. EXPECT_EQ("close", res->get_header_value("Connection"));
  8229. res = cli_.Post(
  8230. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8231. "text/plain");
  8232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8233. EXPECT_EQ(StatusCode::OK_200, res->status);
  8234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8235. EXPECT_EQ("empty", res->body);
  8236. cli_.set_keep_alive(false);
  8237. res = cli_.Get("/last-request");
  8238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8239. EXPECT_EQ(StatusCode::OK_200, res->status);
  8240. EXPECT_EQ("close", res->get_header_value("Connection"));
  8241. }
  8242. TEST_F(ServerTest, TooManyRedirect) {
  8243. cli_.set_follow_location(true);
  8244. auto res = cli_.Get("/redirect/0");
  8245. ASSERT_TRUE(!res);
  8246. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8247. }
  8248. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8249. Request req;
  8250. req.method = "FOOBAR";
  8251. req.path = "/hi";
  8252. cli_.set_keep_alive(true);
  8253. auto res = cli_.send(req);
  8254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8255. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8256. EXPECT_EQ("close", res->get_header_value("Connection"));
  8257. EXPECT_FALSE(cli_.is_socket_open());
  8258. }
  8259. TEST_F(ServerTest, CustomRouteReadsBody) {
  8260. const std::string xml =
  8261. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8262. Request req;
  8263. req.method = "PROPFIND";
  8264. req.path = "/dav/dir";
  8265. req.set_header("Depth", "1");
  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. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8272. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8273. }
  8274. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8275. Request req;
  8276. req.method = "PROPFIND";
  8277. req.path = "/dav/42";
  8278. auto res = cli_.send(req);
  8279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8280. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8281. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8282. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8283. }
  8284. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8285. Request req;
  8286. req.method = "PROPFIND";
  8287. req.path = "/dav-re/123";
  8288. auto res = cli_.send(req);
  8289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8290. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8291. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8292. }
  8293. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8294. Request req;
  8295. req.method = "MKCOL";
  8296. req.path = "/dav-mkcol";
  8297. auto res = cli_.send(req);
  8298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8299. EXPECT_EQ(StatusCode::Created_201, res->status);
  8300. }
  8301. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8302. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8303. Request req;
  8304. req.method = "REPORT";
  8305. req.path = "/dav-report";
  8306. req.body = xml;
  8307. auto res = cli_.send(req);
  8308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8309. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8310. EXPECT_EQ(xml, res->body);
  8311. }
  8312. // A content reader route must fire even when the request carries no body,
  8313. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8314. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8315. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8316. Request req;
  8317. req.method = "REPORT";
  8318. req.path = "/dav-report";
  8319. auto res = cli_.send(req);
  8320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8321. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8322. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8323. }
  8324. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8325. Request req;
  8326. req.method = "PROPFIND";
  8327. req.path = "/not-dav";
  8328. auto res = cli_.send(req);
  8329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8331. }
  8332. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8333. Request req;
  8334. req.method = "UNLOCK";
  8335. req.path = "/dav/dir";
  8336. cli_.set_keep_alive(true);
  8337. auto res = cli_.send(req);
  8338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8339. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8340. EXPECT_EQ("close", res->get_header_value("Connection"));
  8341. EXPECT_FALSE(cli_.is_socket_open());
  8342. }
  8343. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8344. // The mount point serves this path, but only for GET and HEAD.
  8345. auto get_res = cli_.Get("/dir/index.html");
  8346. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8347. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8348. Request req;
  8349. req.method = "PROPFIND";
  8350. req.path = "/dir/index.html";
  8351. auto res = cli_.send(req);
  8352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8353. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8354. }
  8355. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8356. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8357. cli_.set_keep_alive(true);
  8358. for (auto i = 0; i < 2; i++) {
  8359. Request req;
  8360. req.method = "PROPFIND";
  8361. req.path = "/dav/dir";
  8362. req.body = xml;
  8363. auto res = cli_.send(req);
  8364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8365. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8366. EXPECT_EQ(xml, res->body);
  8367. EXPECT_TRUE(cli_.is_socket_open());
  8368. }
  8369. // A built-in method must still be served on the same connection.
  8370. cli_.set_keep_alive(false);
  8371. auto res = cli_.Get("/hi");
  8372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8373. EXPECT_EQ(StatusCode::OK_200, res->status);
  8374. EXPECT_EQ("close", res->get_header_value("Connection"));
  8375. }
  8376. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8377. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8378. Request req;
  8379. req.method = "PROPFIND";
  8380. req.path = "/dav/dir";
  8381. req.set_header("Expect", "100-continue");
  8382. req.body = xml;
  8383. auto res = cli_.send(req);
  8384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8385. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8386. EXPECT_EQ(xml, res->body);
  8387. }
  8388. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8389. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8390. TEST_F(ServerTest, Gzip) {
  8391. Headers headers;
  8392. headers.emplace("Accept-Encoding", "gzip, deflate");
  8393. auto res = cli_.Get("/compress", headers);
  8394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8395. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8396. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8397. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8398. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8399. "7890123456789012345678901234567890",
  8400. res->body);
  8401. EXPECT_EQ(StatusCode::OK_200, res->status);
  8402. }
  8403. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8404. Headers headers;
  8405. headers.emplace("Accept-Encoding", "gzip, deflate");
  8406. auto res = cli_.Get("/compress-with-charset", headers);
  8407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8408. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8409. EXPECT_EQ("application/json; charset=utf-8",
  8410. res->get_header_value("Content-Type"));
  8411. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8412. "7890123456789012345678901234567890",
  8413. res->body);
  8414. EXPECT_EQ(StatusCode::OK_200, res->status);
  8415. }
  8416. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8417. Headers headers;
  8418. headers.emplace("Accept-Encoding", "");
  8419. auto res = cli_.Get("/compress", headers);
  8420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8421. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8422. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8423. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8424. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8425. "7890123456789012345678901234567890",
  8426. res->body);
  8427. EXPECT_EQ(StatusCode::OK_200, res->status);
  8428. }
  8429. TEST_F(ServerTest, GzipWithContentReceiver) {
  8430. Headers headers;
  8431. headers.emplace("Accept-Encoding", "gzip, deflate");
  8432. std::string body;
  8433. auto res =
  8434. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8435. EXPECT_EQ(100U, data_length);
  8436. body.append(data, data_length);
  8437. return true;
  8438. });
  8439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8440. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8441. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8442. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8443. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8444. "7890123456789012345678901234567890",
  8445. body);
  8446. EXPECT_EQ(StatusCode::OK_200, res->status);
  8447. }
  8448. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8449. Headers headers;
  8450. headers.emplace("Accept-Encoding", "gzip, deflate");
  8451. cli_.set_decompress(false);
  8452. auto res = cli_.Get("/compress", headers);
  8453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8454. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8456. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8457. EXPECT_EQ(33U, res->body.size());
  8458. EXPECT_EQ(StatusCode::OK_200, res->status);
  8459. }
  8460. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8461. Headers headers;
  8462. headers.emplace("Accept-Encoding", "");
  8463. std::string body;
  8464. auto res =
  8465. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8466. EXPECT_EQ(100U, data_length);
  8467. body.append(data, data_length);
  8468. return true;
  8469. });
  8470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8471. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8472. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8473. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8474. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8475. "7890123456789012345678901234567890",
  8476. body);
  8477. EXPECT_EQ(StatusCode::OK_200, res->status);
  8478. }
  8479. TEST_F(ServerTest, NoGzip) {
  8480. Headers headers;
  8481. headers.emplace("Accept-Encoding", "gzip, deflate");
  8482. auto res = cli_.Get("/nocompress", headers);
  8483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8484. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8485. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8486. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8487. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8488. "7890123456789012345678901234567890",
  8489. res->body);
  8490. EXPECT_EQ(StatusCode::OK_200, res->status);
  8491. }
  8492. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8493. Headers headers;
  8494. headers.emplace("Accept-Encoding", "gzip, deflate");
  8495. std::string body;
  8496. auto res = cli_.Get("/nocompress", headers,
  8497. [&](const char *data, size_t data_length) {
  8498. EXPECT_EQ(100U, data_length);
  8499. body.append(data, data_length);
  8500. return true;
  8501. });
  8502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8503. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8504. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8505. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8506. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8507. "7890123456789012345678901234567890",
  8508. body);
  8509. EXPECT_EQ(StatusCode::OK_200, res->status);
  8510. }
  8511. TEST_F(ServerTest, MultipartFormDataGzip) {
  8512. UploadFormDataItems items = {
  8513. {"key1", "test", "", ""},
  8514. {"key2", "--abcdefg123", "", ""},
  8515. };
  8516. cli_.set_compress(true);
  8517. auto res = cli_.Post("/compress-multipart", items);
  8518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8519. EXPECT_EQ(StatusCode::OK_200, res->status);
  8520. }
  8521. #endif
  8522. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8523. // Static file compression is opt-in, so these run their own server rather than
  8524. // flipping it on for the shared ServerTest fixture, which would silently
  8525. // rewrite what every other static file test is asserting.
  8526. class StaticFileCompressionTest : public ::testing::Test {
  8527. protected:
  8528. void TearDown() override {
  8529. if (t_.joinable()) {
  8530. svr_.stop();
  8531. t_.join();
  8532. }
  8533. }
  8534. int start(const std::function<void(Server &)> &configure = nullptr) {
  8535. // Serves the same tree as a directory of build-time compressed assets
  8536. // would be served: the mount point names the coding the files are already
  8537. // stored in. Registered before "/" so it is the one that matches.
  8538. svr_.set_mount_point("/pre-encoded", "./www",
  8539. {{"Content-Encoding", "gzip"}});
  8540. svr_.set_mount_point("/", "./www");
  8541. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8542. res.set_file_content("./www/dir/index.html", "text/html");
  8543. });
  8544. svr_.Get("/pre-encoded-file-content",
  8545. [](const Request & /*req*/, Response &res) {
  8546. res.set_header("Content-Encoding", "gzip");
  8547. res.set_file_content("./www/dir/index.html", "text/html");
  8548. });
  8549. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8550. res.set_content_provider(
  8551. 6, "text/plain",
  8552. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8553. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8554. return true;
  8555. });
  8556. });
  8557. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8558. res.set_content_provider(
  8559. 1000, "text/plain",
  8560. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8561. if (offset < 100) {
  8562. std::string data(100, 'A');
  8563. sink.write(data.data(), data.size());
  8564. return true;
  8565. }
  8566. std::this_thread::sleep_for(std::chrono::seconds(2));
  8567. std::string data(900, 'B');
  8568. sink.write(data.data(), data.size());
  8569. return true;
  8570. });
  8571. });
  8572. if (configure) { configure(svr_); }
  8573. auto port = svr_.bind_to_any_port(HOST);
  8574. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8575. svr_.wait_until_ready();
  8576. return port;
  8577. }
  8578. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8579. // Every file under ./www except 1MB.txt is smaller than the default
  8580. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8581. // it out of the way.
  8582. static void enable_without_floor(Server &svr) {
  8583. svr.set_static_file_compression(true);
  8584. svr.set_static_file_compression_min_length(0);
  8585. }
  8586. Server svr_;
  8587. std::thread t_;
  8588. };
  8589. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8590. auto port = start();
  8591. Client cli(HOST, port);
  8592. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8594. EXPECT_EQ(StatusCode::OK_200, res->status);
  8595. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8596. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8597. EXPECT_EQ(1048576U, res->body.size());
  8598. }
  8599. TEST_F(StaticFileCompressionTest, MountPoint) {
  8600. auto port = start(enable);
  8601. Client cli(HOST, port);
  8602. cli.set_decompress(false);
  8603. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8605. EXPECT_EQ(StatusCode::OK_200, res->status);
  8606. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8607. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8608. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8609. // The response stays self-delimiting: a length, not a chunked body.
  8610. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8611. EXPECT_EQ(std::to_string(res->body.size()),
  8612. res->get_header_value("Content-Length"));
  8613. EXPECT_LT(res->body.size(), 1048576U);
  8614. EXPECT_FALSE(res->body.empty());
  8615. }
  8616. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8617. auto port = start(enable);
  8618. Client cli(HOST, port);
  8619. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8621. EXPECT_EQ(StatusCode::OK_200, res->status);
  8622. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8623. EXPECT_EQ(1048576U, res->body.size());
  8624. }
  8625. TEST_F(StaticFileCompressionTest, FileContent) {
  8626. auto port = start(enable_without_floor);
  8627. Client cli(HOST, port);
  8628. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8630. EXPECT_EQ(StatusCode::OK_200, res->status);
  8631. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8632. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8633. EXPECT_EQ(104U, res->body.size());
  8634. }
  8635. // A handler that serves an already-encoded file names the coding itself. The
  8636. // file-backed path decided its coding from Accept-Encoding and the content
  8637. // type alone, so it compressed the stored bytes a second time and appended a
  8638. // second Content-Encoding field line.
  8639. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8640. auto port = start(enable_without_floor);
  8641. Client cli(HOST, port);
  8642. cli.set_decompress(false);
  8643. auto res = cli.Get("/pre-encoded-file-content",
  8644. Headers{{"Accept-Encoding", "gzip"}});
  8645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8646. EXPECT_EQ(StatusCode::OK_200, res->status);
  8647. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8648. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8649. // Vary belongs to a coding the server chose, and it chose none here.
  8650. EXPECT_FALSE(res->has_header("Vary"));
  8651. // The file travels exactly as it is stored on disk.
  8652. EXPECT_EQ(104U, res->body.size());
  8653. }
  8654. // The 1MB file clears the default floor, so this one runs the configuration a
  8655. // deployment would actually have.
  8656. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8657. auto port = start(enable);
  8658. Client cli(HOST, port);
  8659. cli.set_decompress(false);
  8660. auto res =
  8661. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8663. EXPECT_EQ(StatusCode::OK_200, res->status);
  8664. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8665. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8666. EXPECT_FALSE(res->has_header("Vary"));
  8667. EXPECT_EQ(1048576U, res->body.size());
  8668. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8669. }
  8670. TEST_F(StaticFileCompressionTest, Head) {
  8671. auto port = start(enable);
  8672. Client cli(HOST, port);
  8673. cli.set_decompress(false);
  8674. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8675. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8676. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8678. EXPECT_EQ(StatusCode::OK_200, res->status);
  8679. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8680. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8681. // HEAD still reports the size a GET would return.
  8682. EXPECT_EQ(get->get_header_value("Content-Length"),
  8683. res->get_header_value("Content-Length"));
  8684. EXPECT_TRUE(res->body.empty());
  8685. }
  8686. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8687. auto port = start(enable);
  8688. Client cli(HOST, port);
  8689. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8690. {"Accept-Encoding", "gzip"}});
  8691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8693. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8694. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8695. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8696. EXPECT_EQ("cd", res->body);
  8697. }
  8698. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8699. auto port = start(enable);
  8700. Client cli(HOST, port);
  8701. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8703. EXPECT_EQ(StatusCode::OK_200, res->status);
  8704. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8705. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8706. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8707. }
  8708. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8709. auto port = start(enable);
  8710. Client cli(HOST, port);
  8711. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8713. EXPECT_EQ(StatusCode::OK_200, res->status);
  8714. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8715. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8716. EXPECT_TRUE(res->body.empty());
  8717. }
  8718. TEST_F(StaticFileCompressionTest, MinLength) {
  8719. auto port = start(enable);
  8720. Client cli(HOST, port);
  8721. // 104 bytes, well under the default floor. Compressing it would add the
  8722. // gzip header and trailer to a body that already fits in one packet.
  8723. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8725. EXPECT_EQ(StatusCode::OK_200, res->status);
  8726. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8727. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8728. }
  8729. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8730. auto port = start([](Server &svr) {
  8731. svr.set_static_file_compression(true);
  8732. svr.set_static_file_compression_min_length(1);
  8733. });
  8734. Client cli(HOST, port);
  8735. cli.set_decompress(false);
  8736. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8738. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8739. // A 9-byte file comes back larger than it went in, because gzip's header and
  8740. // trailer outweigh anything deflate can save. That is the end of the range
  8741. // the floor exists to keep out.
  8742. EXPECT_GT(res->body.size(), 9U);
  8743. }
  8744. TEST_F(StaticFileCompressionTest, MaxLength) {
  8745. auto port = start([](Server &svr) {
  8746. svr.set_static_file_compression(true);
  8747. svr.set_static_file_compression_min_length(0);
  8748. svr.set_static_file_compression_max_length(1024);
  8749. });
  8750. Client cli(HOST, port);
  8751. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8752. // defines `small` as a macro on Windows.
  8753. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8754. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8755. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8756. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8757. // Under it: compressed.
  8758. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8759. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8760. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8761. }
  8762. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8763. auto port = start(enable_without_floor);
  8764. Client cli(HOST, port);
  8765. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8766. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8767. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8768. auto identity_etag = identity->get_header_value("ETag");
  8769. ASSERT_FALSE(identity_etag.empty());
  8770. auto gzipped =
  8771. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8772. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8773. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8774. auto gzip_etag = gzipped->get_header_value("ETag");
  8775. ASSERT_FALSE(gzip_etag.empty());
  8776. // Two representations, two validators.
  8777. EXPECT_NE(identity_etag, gzip_etag);
  8778. // Each one revalidates against the request that would produce it...
  8779. auto fresh =
  8780. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8781. {"If-None-Match", gzip_etag}});
  8782. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8783. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8784. auto fresh_identity =
  8785. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8786. {"If-None-Match", identity_etag}});
  8787. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8788. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8789. // ...and not against the other representation.
  8790. auto crossed =
  8791. cli.Get("/dir/index.html",
  8792. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8793. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8794. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8795. }
  8796. // The opt-in covers responses the server reads off disk itself. A caller's own
  8797. // known-length provider keeps its Content-Length and, more importantly, keeps
  8798. // delivering incrementally: routing it through a compressor would hold every
  8799. // write back until zlib's window filled.
  8800. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8801. auto port = start(enable);
  8802. Client cli(HOST, port);
  8803. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8805. EXPECT_EQ(StatusCode::OK_200, res->status);
  8806. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8807. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8808. EXPECT_EQ("aaabbb", res->body);
  8809. }
  8810. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8811. auto port = start(enable);
  8812. Client cli(HOST, port);
  8813. cli.set_read_timeout(1, 0);
  8814. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8815. Headers{{"Accept-Encoding", "gzip"}});
  8816. ASSERT_TRUE(handle.is_valid());
  8817. // The provider writes 100 bytes and then stalls for longer than the read
  8818. // timeout. Those first bytes have to arrive anyway: run the response through
  8819. // a compressor and zlib holds them until its window fills, so the read would
  8820. // come back empty instead.
  8821. char buf[256];
  8822. auto n = handle.read(buf, sizeof(buf));
  8823. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8824. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8825. }
  8826. #endif
  8827. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8828. TEST_F(ServerTest, Brotli) {
  8829. Headers headers;
  8830. headers.emplace("Accept-Encoding", "br");
  8831. auto res = cli_.Get("/compress", headers);
  8832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8833. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8834. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8835. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8836. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8837. "7890123456789012345678901234567890",
  8838. res->body);
  8839. EXPECT_EQ(StatusCode::OK_200, res->status);
  8840. }
  8841. #endif
  8842. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8843. TEST_F(ServerTest, Zstd) {
  8844. Headers headers;
  8845. headers.emplace("Accept-Encoding", "zstd");
  8846. auto res = cli_.Get("/compress", headers);
  8847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8848. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8850. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8851. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8852. "7890123456789012345678901234567890",
  8853. res->body);
  8854. EXPECT_EQ(StatusCode::OK_200, res->status);
  8855. }
  8856. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8857. Headers headers;
  8858. headers.emplace("Accept-Encoding", "");
  8859. auto res = cli_.Get("/compress", headers);
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8862. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8863. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8864. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8865. "7890123456789012345678901234567890",
  8866. res->body);
  8867. EXPECT_EQ(StatusCode::OK_200, res->status);
  8868. }
  8869. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8870. Headers headers;
  8871. headers.emplace("Accept-Encoding", "zstd");
  8872. std::string body;
  8873. auto res =
  8874. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8875. EXPECT_EQ(100U, data_length);
  8876. body.append(data, data_length);
  8877. return true;
  8878. });
  8879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8880. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8881. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8882. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8883. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8884. "7890123456789012345678901234567890",
  8885. body);
  8886. EXPECT_EQ(StatusCode::OK_200, res->status);
  8887. }
  8888. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8889. Headers headers;
  8890. headers.emplace("Accept-Encoding", "zstd");
  8891. cli_.set_decompress(false);
  8892. auto res = cli_.Get("/compress", headers);
  8893. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8894. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8895. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8896. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8898. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8899. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8900. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8901. EXPECT_EQ(StatusCode::OK_200, res->status);
  8902. ASSERT_EQ(26U, res->body.size());
  8903. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8904. 0);
  8905. }
  8906. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8907. Headers headers;
  8908. headers.emplace("Accept-Encoding", "");
  8909. std::string body;
  8910. auto res =
  8911. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8912. EXPECT_EQ(100U, data_length);
  8913. body.append(data, data_length);
  8914. return true;
  8915. });
  8916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8917. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8919. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8920. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8921. "7890123456789012345678901234567890",
  8922. body);
  8923. EXPECT_EQ(StatusCode::OK_200, res->status);
  8924. }
  8925. TEST_F(ServerTest, NoZstd) {
  8926. Headers headers;
  8927. headers.emplace("Accept-Encoding", "zstd");
  8928. auto res = cli_.Get("/nocompress", headers);
  8929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8930. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8931. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8932. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8933. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8934. "7890123456789012345678901234567890",
  8935. res->body);
  8936. EXPECT_EQ(StatusCode::OK_200, res->status);
  8937. }
  8938. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8939. Headers headers;
  8940. headers.emplace("Accept-Encoding", "zstd");
  8941. std::string body;
  8942. auto res = cli_.Get("/nocompress", headers,
  8943. [&](const char *data, size_t data_length) {
  8944. EXPECT_EQ(100U, data_length);
  8945. body.append(data, data_length);
  8946. return true;
  8947. });
  8948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8949. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8950. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8951. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8952. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8953. "7890123456789012345678901234567890",
  8954. body);
  8955. EXPECT_EQ(StatusCode::OK_200, res->status);
  8956. }
  8957. // TODO: How to enable zstd ??
  8958. TEST_F(ServerTest, MultipartFormDataZstd) {
  8959. UploadFormDataItems items = {
  8960. {"key1", "test", "", ""},
  8961. {"key2", "--abcdefg123", "", ""},
  8962. };
  8963. Headers headers;
  8964. headers.emplace("Accept-Encoding", "zstd");
  8965. cli_.set_compress(true);
  8966. auto res = cli_.Post("/compress-multipart", headers, items);
  8967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8968. EXPECT_EQ(StatusCode::OK_200, res->status);
  8969. }
  8970. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8971. Headers headers;
  8972. headers.emplace("Accept-Encoding", "zstd");
  8973. cli_.set_compress(true);
  8974. auto res = cli_.Put(
  8975. "/put", headers, 3,
  8976. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8977. sink.os << "PUT";
  8978. return true;
  8979. },
  8980. "text/plain");
  8981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8982. EXPECT_EQ(StatusCode::OK_200, res->status);
  8983. EXPECT_EQ("PUT", res->body);
  8984. }
  8985. // Pre-compression logging tests
  8986. TEST_F(ServerTest, PreCompressionLogging) {
  8987. // Test data for compression (matches the actual /compress endpoint content)
  8988. const std::string test_content =
  8989. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8990. "3456789012345678901234567890";
  8991. // Variables to capture logging data
  8992. std::string pre_compression_body;
  8993. std::string pre_compression_content_type;
  8994. std::string pre_compression_content_encoding;
  8995. std::string post_compression_body;
  8996. std::string post_compression_content_type;
  8997. std::string post_compression_content_encoding;
  8998. // Set up pre-compression logger
  8999. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9000. const Response &res) {
  9001. pre_compression_body = res.body;
  9002. pre_compression_content_type = res.get_header_value("Content-Type");
  9003. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9004. });
  9005. // Set up post-compression logger
  9006. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9007. post_compression_body = res.body;
  9008. post_compression_content_type = res.get_header_value("Content-Type");
  9009. post_compression_content_encoding =
  9010. res.get_header_value("Content-Encoding");
  9011. });
  9012. // Test with gzip compression
  9013. Headers headers;
  9014. headers.emplace("Accept-Encoding", "gzip");
  9015. auto res = cli_.Get("/compress", headers);
  9016. // Verify response was compressed
  9017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9018. EXPECT_EQ(StatusCode::OK_200, res->status);
  9019. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9020. // Verify pre-compression logger captured uncompressed content
  9021. EXPECT_EQ(test_content, pre_compression_body);
  9022. EXPECT_EQ("text/plain", pre_compression_content_type);
  9023. EXPECT_TRUE(pre_compression_content_encoding
  9024. .empty()); // No encoding header before compression
  9025. // Verify post-compression logger captured compressed content
  9026. EXPECT_NE(test_content,
  9027. post_compression_body); // Should be different after compression
  9028. EXPECT_EQ("text/plain", post_compression_content_type);
  9029. EXPECT_EQ("gzip", post_compression_content_encoding);
  9030. // Verify compressed content is smaller
  9031. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9032. }
  9033. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9034. const std::string test_content =
  9035. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9036. "3456789012345678901234567890";
  9037. std::string pre_compression_body;
  9038. std::string post_compression_body;
  9039. svr_.set_pre_compression_logger(
  9040. [&](const Request & /*req*/, const Response &res) {
  9041. pre_compression_body = res.body;
  9042. });
  9043. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9044. post_compression_body = res.body;
  9045. });
  9046. Headers headers;
  9047. headers.emplace("Accept-Encoding", "br");
  9048. auto res = cli_.Get("/compress", headers);
  9049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9050. EXPECT_EQ(StatusCode::OK_200, res->status);
  9051. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9052. // Verify pre-compression content is uncompressed
  9053. EXPECT_EQ(test_content, pre_compression_body);
  9054. // Verify post-compression content is compressed
  9055. EXPECT_NE(test_content, post_compression_body);
  9056. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9057. }
  9058. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9059. const std::string test_content =
  9060. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9061. "3456789012345678901234567890";
  9062. std::string pre_compression_body;
  9063. std::string post_compression_body;
  9064. svr_.set_pre_compression_logger(
  9065. [&](const Request & /*req*/, const Response &res) {
  9066. pre_compression_body = res.body;
  9067. });
  9068. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9069. post_compression_body = res.body;
  9070. });
  9071. // Request without compression (use /nocompress endpoint)
  9072. Headers headers;
  9073. auto res = cli_.Get("/nocompress", headers);
  9074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9075. EXPECT_EQ(StatusCode::OK_200, res->status);
  9076. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9077. // Pre-compression logger should not be called when no compression is applied
  9078. EXPECT_TRUE(
  9079. pre_compression_body.empty()); // Pre-compression logger not called
  9080. EXPECT_EQ(
  9081. test_content,
  9082. post_compression_body); // Post-compression logger captures final content
  9083. }
  9084. TEST_F(ServerTest, LoggerSeesContentLength) {
  9085. size_t logged_content_length = 0;
  9086. std::string logged_content_length_header;
  9087. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9088. logged_content_length = res.content_length_;
  9089. logged_content_length_header = res.get_header_value("Content-Length");
  9090. });
  9091. auto res = cli_.Get("/nocompress");
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_EQ(StatusCode::OK_200, res->status);
  9094. EXPECT_EQ(res->body.size(), logged_content_length);
  9095. EXPECT_EQ(std::to_string(logged_content_length),
  9096. logged_content_length_header);
  9097. }
  9098. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9099. const std::string test_content =
  9100. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9101. "3456789012345678901234567890";
  9102. std::string pre_compression_body;
  9103. bool pre_logger_called = false;
  9104. // Set only pre-compression logger
  9105. svr_.set_pre_compression_logger(
  9106. [&](const Request & /*req*/, const Response &res) {
  9107. pre_compression_body = res.body;
  9108. pre_logger_called = true;
  9109. });
  9110. Headers headers;
  9111. headers.emplace("Accept-Encoding", "gzip");
  9112. auto res = cli_.Get("/compress", headers);
  9113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9114. EXPECT_EQ(StatusCode::OK_200, res->status);
  9115. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9116. // Verify pre-compression logger was called
  9117. EXPECT_TRUE(pre_logger_called);
  9118. EXPECT_EQ(test_content, pre_compression_body);
  9119. }
  9120. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9121. {
  9122. // Test with Expect: 100-continue header - success case
  9123. // Server returns 100 Continue, client sends body, server returns 200 OK
  9124. Request req;
  9125. req.method = "POST";
  9126. req.path = "/post-large";
  9127. req.set_header("Expect", "100-continue");
  9128. req.body = LARGE_DATA;
  9129. Response res;
  9130. auto error = Error::Success;
  9131. cli_.set_keep_alive(true);
  9132. auto ret = cli_.send(req, res, error);
  9133. EXPECT_TRUE(ret);
  9134. EXPECT_EQ(StatusCode::OK_200, res.status);
  9135. EXPECT_EQ(LARGE_DATA, res.body);
  9136. }
  9137. {
  9138. // Test with Expect: 100-continue header - error case
  9139. // Client should not send the body when server returns an error
  9140. Request req;
  9141. req.method = "POST";
  9142. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9143. req.set_header("Expect", "100-continue");
  9144. req.body = LARGE_DATA;
  9145. Response res;
  9146. auto error = Error::Success;
  9147. auto start = std::chrono::high_resolution_clock::now();
  9148. cli_.set_keep_alive(true);
  9149. auto ret = cli_.send(req, res, error);
  9150. auto end = std::chrono::high_resolution_clock::now();
  9151. auto elapsed =
  9152. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9153. .count();
  9154. // With Expect: 100-continue, request completes successfully but with error
  9155. EXPECT_TRUE(ret);
  9156. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9157. EXPECT_EQ("close", res.get_header_value("Connection"));
  9158. EXPECT_FALSE(cli_.is_socket_open());
  9159. EXPECT_LE(elapsed, 2000);
  9160. }
  9161. {
  9162. // Send an extra GET request to ensure error recovery without hanging
  9163. Request req;
  9164. req.method = "GET";
  9165. req.path = "/hi";
  9166. auto start = std::chrono::high_resolution_clock::now();
  9167. auto res = cli_.send(req);
  9168. auto end = std::chrono::high_resolution_clock::now();
  9169. auto elapsed =
  9170. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9171. .count();
  9172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9173. EXPECT_EQ(StatusCode::OK_200, res->status);
  9174. EXPECT_EQ("Hello World!", res->body);
  9175. EXPECT_LE(elapsed, 500);
  9176. }
  9177. }
  9178. TEST(ZstdDecompressor, ChunkedDecompression) {
  9179. std::string data;
  9180. for (size_t i = 0; i < 32 * 1024; ++i) {
  9181. data.push_back(static_cast<char>('a' + i % 26));
  9182. }
  9183. std::string compressed_data;
  9184. {
  9185. httplib::detail::zstd_compressor compressor;
  9186. bool result = compressor.compress(
  9187. data.data(), data.size(),
  9188. /*last=*/true,
  9189. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9190. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9191. compressed_data_size);
  9192. return true;
  9193. });
  9194. ASSERT_TRUE(result);
  9195. }
  9196. std::string decompressed_data;
  9197. {
  9198. httplib::detail::zstd_decompressor decompressor;
  9199. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9200. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9201. size_t chunk_size = 130;
  9202. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9203. chunk_begin += chunk_size) {
  9204. size_t current_chunk_size =
  9205. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9206. bool result = decompressor.decompress(
  9207. compressed_data.data() + chunk_begin, current_chunk_size,
  9208. [&](const char *decompressed_data_chunk,
  9209. size_t decompressed_data_chunk_size) {
  9210. decompressed_data.insert(decompressed_data.size(),
  9211. decompressed_data_chunk,
  9212. decompressed_data_chunk_size);
  9213. return true;
  9214. });
  9215. ASSERT_TRUE(result);
  9216. }
  9217. }
  9218. ASSERT_EQ(data, decompressed_data);
  9219. }
  9220. TEST(ZstdDecompressor, Decompress) {
  9221. std::string original_text = "Compressed with ZSTD";
  9222. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9223. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9224. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9225. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9226. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9227. std::string decompressed_data;
  9228. {
  9229. httplib::detail::zstd_decompressor decompressor;
  9230. bool result = decompressor.decompress(
  9231. compressed_data.data(), compressed_data.size(),
  9232. [&](const char *decompressed_data_chunk,
  9233. size_t decompressed_data_chunk_size) {
  9234. decompressed_data.insert(decompressed_data.size(),
  9235. decompressed_data_chunk,
  9236. decompressed_data_chunk_size);
  9237. return true;
  9238. });
  9239. ASSERT_TRUE(result);
  9240. }
  9241. ASSERT_EQ(original_text, decompressed_data);
  9242. }
  9243. #endif
  9244. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9245. // separate chunks so that the server sees each part in its own read(). Used to
  9246. // place a read boundary at a specific offset of a request body.
  9247. static bool send_request_in_parts(time_t read_timeout_sec,
  9248. const std::vector<std::string> &parts,
  9249. std::string *resp = nullptr,
  9250. int port = PORT) {
  9251. auto error = Error::Success;
  9252. auto client_sock = detail::create_client_socket(
  9253. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9254. /*connection_timeout_sec=*/5, 0,
  9255. /*read_timeout_sec=*/5, 0,
  9256. /*write_timeout_sec=*/5, 0, std::string(), error);
  9257. if (client_sock == INVALID_SOCKET) { return false; }
  9258. auto ret = detail::process_client_socket(
  9259. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9260. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9261. for (size_t i = 0; i < parts.size(); i++) {
  9262. const auto &part = parts[i];
  9263. if (part.size() !=
  9264. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9265. return false;
  9266. }
  9267. if (i + 1 < parts.size()) {
  9268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9269. }
  9270. }
  9271. char buf[512];
  9272. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9273. while (line_reader.getline()) {
  9274. if (resp) { *resp += line_reader.ptr(); }
  9275. }
  9276. return true;
  9277. });
  9278. detail::close_socket(client_sock);
  9279. return ret;
  9280. }
  9281. // Sends a raw request to a server listening at HOST:PORT.
  9282. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9283. std::string *resp = nullptr, int port = PORT) {
  9284. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9285. }
  9286. #ifdef CPPHTTPLIB_SSL_ENABLED
  9287. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9289. ASSERT_TRUE(svr.is_valid());
  9290. svr.set_read_timeout(1, 0);
  9291. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9292. auto se = detail::scope_exit([&] {
  9293. svr.stop();
  9294. t.join();
  9295. ASSERT_FALSE(svr.is_running());
  9296. });
  9297. svr.wait_until_ready();
  9298. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9299. // keeps each wait well within the read timeout. The server gives up a
  9300. // second in, so the bytes sent after that fail.
  9301. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9302. parts.resize(26, std::string(1, '\0'));
  9303. EXPECT_FALSE(send_request_in_parts(5, parts));
  9304. }
  9305. #endif
  9306. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9307. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9308. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9309. const std::vector<std::string> &parts,
  9310. std::string *resp = nullptr,
  9311. int port = PORT) {
  9312. auto error = Error::Success;
  9313. auto sock = detail::create_client_socket(
  9314. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9315. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9316. /*write_timeout_sec=*/5, 0, std::string(), error);
  9317. if (sock == INVALID_SOCKET) { return false; }
  9318. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9319. auto ctx = SSL_CTX_new(TLS_client_method());
  9320. auto ssl = SSL_new(ctx);
  9321. auto ssl_se = detail::scope_exit([&] {
  9322. SSL_free(ssl);
  9323. SSL_CTX_free(ctx);
  9324. });
  9325. SSL_set_fd(ssl, static_cast<int>(sock));
  9326. if (SSL_connect(ssl) != 1) { return false; }
  9327. for (size_t i = 0; i < parts.size(); i++) {
  9328. const auto &part = parts[i];
  9329. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9330. static_cast<int>(part.size())) {
  9331. return false;
  9332. }
  9333. if (i + 1 < parts.size()) {
  9334. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9335. }
  9336. }
  9337. char buf[512];
  9338. int n;
  9339. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9340. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9341. }
  9342. return true;
  9343. }
  9344. #endif
  9345. // The request line, then a header value a byte at a time.
  9346. static std::vector<std::string> slow_request_head_parts() {
  9347. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9348. parts.resize(26, "a");
  9349. parts.emplace_back("\r\n\r\n");
  9350. return parts;
  9351. }
  9352. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9353. // within the one-second read timeout. The server gives up a second in, before
  9354. // the head is complete.
  9355. static void
  9356. expect_slow_request_head_dropped(Server &svr,
  9357. const std::function<std::string()> &send) {
  9358. std::atomic<bool> handled(false);
  9359. svr.Get("/", [&](const Request &, Response &res) {
  9360. handled = true;
  9361. res.set_content("ok", "text/plain");
  9362. });
  9363. svr.set_read_timeout(1, 0);
  9364. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9365. auto se = detail::scope_exit([&] {
  9366. svr.stop();
  9367. t.join();
  9368. ASSERT_FALSE(svr.is_running());
  9369. });
  9370. svr.wait_until_ready();
  9371. auto resp = send();
  9372. EXPECT_FALSE(handled);
  9373. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9374. }
  9375. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9376. Server svr;
  9377. expect_slow_request_head_dropped(svr, [] {
  9378. std::string resp;
  9379. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9380. return resp;
  9381. });
  9382. }
  9383. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9384. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9385. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9386. ASSERT_TRUE(svr.is_valid());
  9387. expect_slow_request_head_dropped(svr, [] {
  9388. std::string resp;
  9389. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9390. return resp;
  9391. });
  9392. }
  9393. #endif
  9394. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9395. Server svr;
  9396. std::string header_value;
  9397. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9398. header_value = req.get_header_value("foo");
  9399. res.set_content("ok", "text/plain");
  9400. });
  9401. thread t = thread([&] { svr.listen(HOST, PORT); });
  9402. auto se = detail::scope_exit([&] {
  9403. svr.stop();
  9404. t.join();
  9405. ASSERT_FALSE(svr.is_running());
  9406. });
  9407. svr.wait_until_ready();
  9408. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9409. // like characters are not treated the same - use vertical tab and escape.
  9410. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9411. "foo: \t \v bar \x1B\t \r\n"
  9412. "Connection: close\r\n"
  9413. "\r\n";
  9414. std::string res;
  9415. ASSERT_TRUE(send_request(5, req, &res));
  9416. EXPECT_EQ(header_value, "");
  9417. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9418. }
  9419. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9420. Server svr;
  9421. std::string received;
  9422. svr.Get("/order", [&](const Request &req, Response &res) {
  9423. received = entries_to_string(req.headers);
  9424. res.set_content("ok", "text/plain");
  9425. });
  9426. auto port = svr.bind_to_any_port(HOST);
  9427. thread t = thread([&] { svr.listen_after_bind(); });
  9428. auto se = detail::scope_exit([&] {
  9429. svr.stop();
  9430. t.join();
  9431. ASSERT_FALSE(svr.is_running());
  9432. });
  9433. svr.wait_until_ready();
  9434. const std::string req = "GET /order HTTP/1.1\r\n"
  9435. "Host: localhost\r\n"
  9436. "X-First: 1\r\n"
  9437. "X-Dup: a\r\n"
  9438. "X-Second: 2\r\n"
  9439. "X-Dup: b\r\n"
  9440. "Connection: close\r\n"
  9441. "\r\n";
  9442. std::string res;
  9443. ASSERT_TRUE(send_request(5, req, &res, port));
  9444. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9445. EXPECT_EQ(
  9446. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9447. received);
  9448. }
  9449. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9450. Server svr;
  9451. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9452. res.set_header("Set-Cookie", "first=1");
  9453. res.set_header("X-Between", "y");
  9454. res.set_header("Set-Cookie", "second=2");
  9455. res.set_content("ok", "text/plain");
  9456. });
  9457. auto port = svr.bind_to_any_port(HOST);
  9458. thread t = thread([&] { svr.listen_after_bind(); });
  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. Client cli(HOST, port);
  9466. auto res = cli.Get("/cookies");
  9467. ASSERT_TRUE(res);
  9468. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9469. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9470. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9471. }
  9472. // A stream may send a byte at a time with a small extension on each chunk,
  9473. // however long it runs
  9474. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9475. Server svr;
  9476. svr.Post("/count", [](const Request &req, Response &res) {
  9477. res.set_content(std::to_string(req.body.size()), "text/plain");
  9478. });
  9479. auto port = svr.bind_to_any_port(HOST);
  9480. ASSERT_LT(0, port);
  9481. thread t = thread([&] { svr.listen_after_bind(); });
  9482. auto se = detail::scope_exit([&] {
  9483. svr.stop();
  9484. t.join();
  9485. ASSERT_FALSE(svr.is_running());
  9486. });
  9487. svr.wait_until_ready();
  9488. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9489. "\r\nTransfer-Encoding: chunked\r\n"
  9490. "Connection: close\r\n\r\n";
  9491. for (auto i = 0; i < 4096; i++) {
  9492. req += "1;a=b\r\nx\r\n";
  9493. }
  9494. req += "0\r\n\r\n";
  9495. std::string res;
  9496. ASSERT_TRUE(send_request(5, req, &res, port));
  9497. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9498. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9499. }
  9500. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9501. Server svr;
  9502. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9503. auto i = new int(0);
  9504. res.set_header("Trailer", "X-Safe, X-Reflected");
  9505. res.set_chunked_content_provider(
  9506. "text/plain",
  9507. [i](size_t /*offset*/, DataSink &sink) {
  9508. if (*i == 0) {
  9509. sink.os << "body";
  9510. } else {
  9511. Headers trailer;
  9512. // A valid trailer that must survive.
  9513. trailer.emplace("X-Safe", "safe");
  9514. // Attacker-controlled value carrying CR/LF (response splitting).
  9515. trailer.emplace("X-Reflected",
  9516. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9517. // Attacker-controlled name carrying CR/LF.
  9518. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9519. sink.done_with_trailer(trailer);
  9520. }
  9521. (*i)++;
  9522. return true;
  9523. },
  9524. [i](bool /*success*/) { delete i; });
  9525. });
  9526. thread t = thread([&] { svr.listen(HOST, PORT); });
  9527. auto se = detail::scope_exit([&] {
  9528. svr.stop();
  9529. t.join();
  9530. ASSERT_FALSE(svr.is_running());
  9531. });
  9532. svr.wait_until_ready();
  9533. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9534. "Host: " + HOST +
  9535. "\r\n"
  9536. "Connection: close\r\n"
  9537. "\r\n";
  9538. std::string res;
  9539. ASSERT_TRUE(send_request(5, req, &res));
  9540. // The injected fields must not appear anywhere in the raw response.
  9541. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9542. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9543. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9544. // Invalid trailers are dropped entirely, matching set_header().
  9545. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9546. // The valid trailer still passes through.
  9547. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9548. }
  9549. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9550. // A custom header writer gets only the fields the default one writes
  9551. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9552. std::string s;
  9553. for (const auto &h : hdrs) {
  9554. s += h.first + ": " + h.second + "\r\n";
  9555. }
  9556. s += "\r\n";
  9557. return strm.write(s.data(), s.size());
  9558. };
  9559. for (auto custom_writer : {false, true}) {
  9560. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9561. Server svr;
  9562. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9563. svr.set_post_routing_handler([](const Request &, Response &res) {
  9564. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9565. });
  9566. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9567. // res.headers is a public field an application can populate directly,
  9568. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9569. // A valid header that must survive.
  9570. res.headers.emplace("X-Safe", "safe");
  9571. // Attacker-controlled value carrying CR/LF (response splitting).
  9572. res.headers.emplace("X-Reflected",
  9573. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9574. // Attacker-controlled name carrying CR/LF.
  9575. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9576. res.set_content("body", "text/plain");
  9577. });
  9578. thread t = thread([&] { svr.listen(HOST, PORT); });
  9579. auto se = detail::scope_exit([&] {
  9580. svr.stop();
  9581. t.join();
  9582. ASSERT_FALSE(svr.is_running());
  9583. });
  9584. svr.wait_until_ready();
  9585. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9586. "Host: " + HOST +
  9587. "\r\n"
  9588. "Connection: close\r\n"
  9589. "\r\n";
  9590. std::string res;
  9591. ASSERT_TRUE(send_request(5, req, &res));
  9592. // The injected fields must not appear anywhere in the raw response.
  9593. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9594. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9595. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9596. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9597. // Invalid headers are dropped entirely, matching set_header().
  9598. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9599. // The valid header still passes through.
  9600. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9601. }
  9602. }
  9603. // Forward declaration: in split builds split.py strips `inline` and moves the
  9604. // definition into httplib.cc, so detail::write_request_line is not visible from
  9605. // the public httplib.h. Re-declaring it here lets the tests link against the
  9606. // symbol in both header-only and split builds.
  9607. namespace httplib {
  9608. namespace detail {
  9609. ssize_t write_request_line(Stream &strm, const std::string &method,
  9610. const std::string &path);
  9611. } // namespace detail
  9612. } // namespace httplib
  9613. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9614. // A well-formed target is written verbatim.
  9615. {
  9616. detail::BufferStream strm;
  9617. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9618. EXPECT_GT(n, 0);
  9619. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9620. }
  9621. // A target carrying CR/LF, SP or other control octets must be rejected
  9622. // before anything reaches the wire, otherwise it splits the request line and
  9623. // injects a header or a whole request.
  9624. const std::string evil_targets[] = {
  9625. "/a\r\nInjected: pwned",
  9626. "/a\rInjected",
  9627. "/a\nInjected",
  9628. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9629. "/a b",
  9630. "/a\tb",
  9631. "/a\x7f",
  9632. };
  9633. for (const auto &evil : evil_targets) {
  9634. detail::BufferStream strm;
  9635. auto n = detail::write_request_line(strm, "GET", evil);
  9636. EXPECT_LT(n, 0);
  9637. EXPECT_TRUE(strm.get_buffer().empty());
  9638. }
  9639. }
  9640. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9641. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9642. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9643. // target reaches write_request. The client must fail cleanly with
  9644. // Error::Write instead of putting a request-line-less, header-injecting
  9645. // request on the wire.
  9646. Server svr;
  9647. svr.Get("/a", [](const Request &, Response &res) {
  9648. res.set_content("ok", "text/plain");
  9649. });
  9650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9651. auto se = detail::scope_exit([&] {
  9652. svr.stop();
  9653. thread.join();
  9654. ASSERT_FALSE(svr.is_running());
  9655. });
  9656. svr.wait_until_ready();
  9657. {
  9658. Client cli(HOST, PORT);
  9659. cli.set_path_encode(false);
  9660. // The request is rejected before anything is written, so the connection
  9661. // stays silent and the subsequent response read would otherwise block for
  9662. // the full default read timeout. Shorten it -- the assertion is on the
  9663. // error, not the timeout.
  9664. cli.set_read_timeout(1, 0);
  9665. auto res = cli.Get("/a\r\nInjected: pwned");
  9666. EXPECT_FALSE(res);
  9667. EXPECT_EQ(Error::Write, res.error());
  9668. }
  9669. }
  9670. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9671. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9672. // including extension methods.
  9673. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9674. for (const auto &method : good_methods) {
  9675. detail::BufferStream strm;
  9676. auto n = detail::write_request_line(strm, method, "/");
  9677. EXPECT_GT(n, 0);
  9678. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9679. }
  9680. // A method carrying CR/LF would split the request line and smuggle a whole
  9681. // request ahead of the real one. A space or an empty method corrupts the
  9682. // request line. All must be rejected before anything reaches the wire.
  9683. const std::string evil_methods[] = {
  9684. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9685. "GET\r\nInjected: pwned",
  9686. "GET\r",
  9687. "GET\n",
  9688. "GE T",
  9689. "",
  9690. };
  9691. for (const auto &evil : evil_methods) {
  9692. detail::BufferStream strm;
  9693. auto n = detail::write_request_line(strm, evil, "/");
  9694. EXPECT_LT(n, 0);
  9695. EXPECT_TRUE(strm.get_buffer().empty());
  9696. }
  9697. }
  9698. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9699. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9700. // through Client::send must fail with Error::Write and no request, neither
  9701. // the smuggled one nor the real one, may reach the server.
  9702. Server svr;
  9703. std::atomic<int> request_count(0);
  9704. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9705. request_count++;
  9706. res.status = StatusCode::OK_200;
  9707. return Server::HandlerResponse::Handled;
  9708. });
  9709. auto port = svr.bind_to_any_port(HOST);
  9710. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9711. auto se = detail::scope_exit([&] {
  9712. svr.stop();
  9713. thread.join();
  9714. ASSERT_FALSE(svr.is_running());
  9715. });
  9716. svr.wait_until_ready();
  9717. {
  9718. Client cli(HOST, port);
  9719. const std::string evil_methods[] = {
  9720. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9721. "GE T",
  9722. "",
  9723. };
  9724. for (const auto &evil : evil_methods) {
  9725. Request req;
  9726. req.method = evil;
  9727. req.path = "/";
  9728. auto res = cli.send(req);
  9729. EXPECT_FALSE(res);
  9730. EXPECT_EQ(Error::Write, res.error());
  9731. }
  9732. auto handle =
  9733. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9734. EXPECT_FALSE(handle.is_valid());
  9735. EXPECT_EQ(Error::Write, handle.error);
  9736. // A valid request on the same client still goes through.
  9737. auto res = cli.Get("/");
  9738. ASSERT_TRUE(res);
  9739. EXPECT_EQ(StatusCode::OK_200, res->status);
  9740. }
  9741. EXPECT_EQ(1, request_count.load());
  9742. }
  9743. // Sends a raw request and verifies that there isn't a crash or exception.
  9744. static void test_raw_request(const std::string &req,
  9745. std::string *out = nullptr) {
  9746. Server svr;
  9747. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9748. res.set_content("ok", "text/plain");
  9749. });
  9750. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9751. res.set_content("ok", "text/plain");
  9752. });
  9753. svr.Get("/header_field_value_check",
  9754. [&](const Request & /*req*/, Response &res) {
  9755. res.set_content("ok", "text/plain");
  9756. });
  9757. svr.CustomRoute("PROPFIND", "/dav",
  9758. [&](const Request & /*req*/, Response &res) {
  9759. res.status = StatusCode::MultiStatus_207;
  9760. });
  9761. // Server read timeout must be longer than the client read timeout for the
  9762. // bug to reproduce, probably to force the server to process a request
  9763. // without a trailing blank line.
  9764. const time_t client_read_timeout_sec = 1;
  9765. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9766. bool listen_thread_ok = false;
  9767. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9768. auto se = detail::scope_exit([&] {
  9769. svr.stop();
  9770. t.join();
  9771. ASSERT_FALSE(svr.is_running());
  9772. EXPECT_TRUE(listen_thread_ok);
  9773. });
  9774. svr.wait_until_ready();
  9775. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9776. }
  9777. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9778. // A certain header line causes an exception if the header property is parsed
  9779. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9780. test_raw_request(
  9781. "GET /hi HTTP/1.1\r\n"
  9782. " : "
  9783. " "
  9784. " ");
  9785. }
  9786. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9787. // A certain header line causes an exception if the header property *name* is
  9788. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9789. // greedy matcher and requires backtracking when there are a lot of ":"
  9790. // characters.
  9791. // This occurs with libc++ but not libstdc++.
  9792. test_raw_request(
  9793. "GET /hi HTTP/1.1\r\n"
  9794. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9795. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9796. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9797. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9798. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9799. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9800. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9801. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9802. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9803. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9804. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9805. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9806. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9807. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9808. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9809. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9810. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9811. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9812. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9813. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9814. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9815. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9816. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9817. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9818. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9819. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9820. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9821. "&&&%%%");
  9822. }
  9823. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9824. // Make sure this doesn't crash the server.
  9825. // In a previous version of the header line regex, the "\r" rendered the line
  9826. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9827. // a new position where the leading white space ended and the field value
  9828. // began.
  9829. // The crash occurs with libc++ but not libstdc++.
  9830. test_raw_request("GET /hi HTTP/1.1\r\n"
  9831. "a:" +
  9832. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9833. "\r\n"
  9834. "\r\n");
  9835. }
  9836. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9837. const char *rejected[] = {
  9838. // RFC 9112 §3: one SP between the parts, and nothing else
  9839. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9840. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9841. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9842. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9843. // A request-target has no fragment
  9844. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9845. // An HTTP/1.1 request needs a Host
  9846. "GET /hi HTTP/1.1\r\n\r\n",
  9847. };
  9848. for (auto request : rejected) {
  9849. std::string out;
  9850. test_raw_request(request, &out);
  9851. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9852. }
  9853. std::string out;
  9854. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9855. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9856. }
  9857. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9858. // RFC 9112 §6.1
  9859. const char *requests[] = {
  9860. "PUT /put_hi HTTP/1.1\r\n"
  9861. "Host: localhost\r\n"
  9862. "Content-Length: 0\r\n"
  9863. "Transfer-Encoding: chunked\r\n"
  9864. "\r\n"
  9865. "0\r\n\r\n",
  9866. "PUT /put_hi HTTP/1.0\r\n"
  9867. "Connection: keep-alive\r\n"
  9868. "Transfer-Encoding: chunked\r\n"
  9869. "\r\n"
  9870. "0\r\n\r\n",
  9871. };
  9872. for (auto request : requests) {
  9873. std::string out;
  9874. test_raw_request(request, &out);
  9875. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9876. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9877. }
  9878. }
  9879. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9880. std::string out;
  9881. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9882. "Content-Type: text/plain\r\n"
  9883. "Transfer-Encoding: chunked\r\n"
  9884. "\r\n"
  9885. "nothex\r\n",
  9886. &out);
  9887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9888. }
  9889. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9890. std::string out;
  9891. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9892. "Content-Type: text/plain\r\n"
  9893. "Transfer-Encoding: chunked\r\n"
  9894. "\r\n"
  9895. "3\r\n"
  9896. "xyz\r\n"
  9897. "NaN\r\n",
  9898. &out);
  9899. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9900. }
  9901. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9902. std::string out;
  9903. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9904. "Content-Type: text/plain\r\n"
  9905. "Transfer-Encoding: chunked\r\n"
  9906. "\r\n"
  9907. // Length is too large for 64 bits.
  9908. "1ffffffffffffffff\r\n"
  9909. "xyz\r\n",
  9910. &out);
  9911. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9912. }
  9913. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9914. test_raw_request("GET /hi HTTP/1.1\r\n"
  9915. "Content-Type: text/plain\r\n\r");
  9916. }
  9917. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9918. std::string out;
  9919. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9920. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9921. }
  9922. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9923. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9924. std::string out;
  9925. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9926. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9927. }
  9928. }
  9929. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9930. std::string out;
  9931. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9932. "Host: localhost\r\n"
  9933. "Connection: close\r\n\r\n",
  9934. &out);
  9935. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9936. }
  9937. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9938. Server svr;
  9939. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9940. EXPECT_TRUE(!req.remote_addr.empty());
  9941. });
  9942. thread t = thread([&] { svr.listen(HOST, PORT); });
  9943. auto se = detail::scope_exit([&] {
  9944. svr.stop();
  9945. t.join();
  9946. ASSERT_FALSE(svr.is_running());
  9947. });
  9948. svr.wait_until_ready();
  9949. // Send an invalid request line to trigger Bad Request
  9950. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9951. std::string out;
  9952. ASSERT_TRUE(send_request(5, bad_req, &out));
  9953. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9954. }
  9955. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9956. // answered right away rather than blocking on a read that waits for EOF.
  9957. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9958. std::string out;
  9959. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9960. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9961. }
  9962. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9963. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9964. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9965. for (const auto *method : methods) {
  9966. Server svr;
  9967. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9968. EXPECT_FALSE(svr.is_valid()) << method;
  9969. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9970. }
  9971. }
  9972. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9973. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9974. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9975. for (const auto *method : methods) {
  9976. Server svr;
  9977. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9978. EXPECT_FALSE(svr.is_valid()) << method;
  9979. }
  9980. }
  9981. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9982. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9983. "COPY", "MOVE", "LOCK",
  9984. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9985. Server svr;
  9986. for (const auto *method : methods) {
  9987. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9988. }
  9989. EXPECT_TRUE(svr.is_valid());
  9990. }
  9991. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9992. Server svr;
  9993. svr.CustomRoute("POST", "/x",
  9994. [](const Request &, Response &, const ContentReader &) {});
  9995. EXPECT_FALSE(svr.is_valid());
  9996. }
  9997. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9998. Server svr;
  9999. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10000. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10001. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10002. EXPECT_FALSE(svr.is_valid());
  10003. }
  10004. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10005. Server svr;
  10006. auto captured = Error::Success;
  10007. svr.set_error_logger(
  10008. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10009. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10010. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10011. }
  10012. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10013. std::string out;
  10014. std::string request(
  10015. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10016. test_raw_request(request, &out);
  10017. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10018. }
  10019. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10020. std::string out;
  10021. std::string request(
  10022. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10023. test_raw_request(request, &out);
  10024. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10025. }
  10026. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10027. std::string out;
  10028. std::string request(
  10029. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10030. test_raw_request(request, &out);
  10031. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10032. }
  10033. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10034. std::string out;
  10035. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10036. "Host: localhost\r\n"
  10037. "Test: \r\n\r\n",
  10038. &out);
  10039. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10040. }
  10041. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10042. Server svr;
  10043. std::string x_custom;
  10044. std::string cookie;
  10045. std::string xff;
  10046. std::string x_unicode;
  10047. std::string x_iis;
  10048. svr.Get("/check", [&](const Request &req, Response &res) {
  10049. x_custom = req.get_header_value("X-Custom");
  10050. cookie = req.get_header_value("Cookie");
  10051. xff = req.get_header_value("X-Forwarded-For");
  10052. x_unicode = req.get_header_value("X-Unicode");
  10053. x_iis = req.get_header_value("X-IIS");
  10054. res.set_content("ok", "text/plain");
  10055. });
  10056. thread t = thread([&] { svr.listen(HOST, PORT); });
  10057. auto se = detail::scope_exit([&] {
  10058. svr.stop();
  10059. t.join();
  10060. ASSERT_FALSE(svr.is_running());
  10061. });
  10062. svr.wait_until_ready();
  10063. const std::string req = "GET /check HTTP/1.1\r\n"
  10064. "Host: localhost\r\n"
  10065. "X-Custom: a%0D%0AInjected: b\r\n"
  10066. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10067. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10068. "X-Unicode: %E3%81%82\r\n"
  10069. "X-IIS: %u00E9\r\n"
  10070. "Connection: close\r\n"
  10071. "\r\n";
  10072. std::string res;
  10073. ASSERT_TRUE(send_request(5, req, &res));
  10074. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10075. // Every value must be returned verbatim (wire form), with no decoding.
  10076. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10077. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10078. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10079. EXPECT_EQ("%E3%81%82", x_unicode);
  10080. EXPECT_EQ("%u00E9", x_iis);
  10081. }
  10082. // Applications that previously relied on automatic percent-decoding can
  10083. // reproduce the old behavior by explicitly calling decode_path_component()
  10084. // or, for RFC 3986 conformance, decode_uri_component().
  10085. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10086. Server svr;
  10087. std::string decoded;
  10088. svr.Get("/check", [&](const Request &req, Response &res) {
  10089. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10090. res.set_content("ok", "text/plain");
  10091. });
  10092. thread t = thread([&] { svr.listen(HOST, PORT); });
  10093. auto se = detail::scope_exit([&] {
  10094. svr.stop();
  10095. t.join();
  10096. ASSERT_FALSE(svr.is_running());
  10097. });
  10098. svr.wait_until_ready();
  10099. const std::string req = "GET /check HTTP/1.1\r\n"
  10100. "Host: localhost\r\n"
  10101. "X-Custom: hello%20world\r\n"
  10102. "Connection: close\r\n"
  10103. "\r\n";
  10104. std::string res;
  10105. ASSERT_TRUE(send_request(5, req, &res));
  10106. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10107. EXPECT_EQ("hello world", decoded);
  10108. }
  10109. // Regression test for #2033. Browsers send Referer values that include
  10110. // percent-encoded characters such as %0A inside the URL. Decoding the
  10111. // header value would either trip the post-decode CR/LF/NUL guard (the
  10112. // original bug, returning 400) or, after that guard was relaxed, silently
  10113. // store a literal LF — both unacceptable. The wire form must round-trip.
  10114. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10115. Server svr;
  10116. std::string referer;
  10117. svr.Get("/check", [&](const Request &req, Response &res) {
  10118. referer = req.get_header_value("Referer");
  10119. res.set_content("ok", "text/plain");
  10120. });
  10121. thread t = thread([&] { svr.listen(HOST, PORT); });
  10122. auto se = detail::scope_exit([&] {
  10123. svr.stop();
  10124. t.join();
  10125. ASSERT_FALSE(svr.is_running());
  10126. });
  10127. svr.wait_until_ready();
  10128. const std::string req = "GET /check HTTP/1.1\r\n"
  10129. "Host: localhost\r\n"
  10130. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10131. "Connection: close\r\n"
  10132. "\r\n";
  10133. std::string res;
  10134. ASSERT_TRUE(send_request(5, req, &res));
  10135. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10136. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10137. }
  10138. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10139. Server svr;
  10140. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10141. res.set_header("Cache-Control", "no-cache");
  10142. res.set_chunked_content_provider(
  10143. "text/event-stream", [](size_t offset, DataSink &sink) {
  10144. std::string s = "data:";
  10145. s += std::to_string(offset);
  10146. s += "\n\n";
  10147. auto ret = sink.write(s.data(), s.size());
  10148. EXPECT_TRUE(ret);
  10149. std::this_thread::sleep_for(std::chrono::seconds(1));
  10150. return true;
  10151. });
  10152. });
  10153. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10154. svr.wait_until_ready();
  10155. Client client(HOST, PORT);
  10156. const Headers headers = {{"Accept", "text/event-stream"}};
  10157. auto get_thread = std::thread([&client, &headers]() {
  10158. auto res = client.Get(
  10159. "/events", headers,
  10160. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10161. });
  10162. auto se = detail::scope_exit([&] {
  10163. svr.stop();
  10164. get_thread.join();
  10165. listen_thread.join();
  10166. ASSERT_FALSE(svr.is_running());
  10167. });
  10168. // Give GET time to get a few messages.
  10169. std::this_thread::sleep_for(std::chrono::seconds(2));
  10170. }
  10171. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10172. httplib::Server svr;
  10173. svr.Post("/hi",
  10174. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10175. res.status = StatusCode::OK_200;
  10176. });
  10177. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10178. svr.wait_until_ready();
  10179. Client cli(HOST, PORT);
  10180. auto res = cli.Post("/hi", "data", "text/plain");
  10181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10182. EXPECT_EQ(StatusCode::OK_200, res->status);
  10183. svr.stop();
  10184. thread.join();
  10185. ASSERT_FALSE(svr.is_running());
  10186. res = cli.Post("/hi", "data", "text/plain");
  10187. ASSERT_FALSE(res);
  10188. }
  10189. TEST(ServerStopTest, ListenFailure) {
  10190. Server svr;
  10191. auto t = thread([&]() {
  10192. auto ret = svr.listen("????", PORT);
  10193. EXPECT_FALSE(ret);
  10194. });
  10195. svr.wait_until_ready();
  10196. svr.stop();
  10197. t.join();
  10198. }
  10199. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10200. TEST(ServerStopTest, Decommision) {
  10201. Server svr;
  10202. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10203. for (int i = 0; i < 4; i++) {
  10204. auto is_even = !(i % 2);
  10205. std::thread t{[&] {
  10206. try {
  10207. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10208. if (is_even) {
  10209. throw std::runtime_error("Some thing that happens to go wrong.");
  10210. }
  10211. svr.listen(HOST, PORT);
  10212. } catch (...) { svr.decommission(); }
  10213. }};
  10214. svr.wait_until_ready();
  10215. // Server is up
  10216. {
  10217. Client cli(HOST, PORT);
  10218. auto res = cli.Get("/hi");
  10219. if (is_even) {
  10220. EXPECT_FALSE(res);
  10221. } else {
  10222. EXPECT_TRUE(res);
  10223. EXPECT_EQ("hi...", res->body);
  10224. }
  10225. }
  10226. svr.stop();
  10227. t.join();
  10228. // Server is down...
  10229. {
  10230. Client cli(HOST, PORT);
  10231. auto res = cli.Get("/hi");
  10232. EXPECT_FALSE(res);
  10233. }
  10234. }
  10235. }
  10236. #endif
  10237. // Helper function for string body upload progress tests
  10238. template <typename SetupHandler, typename ClientCall>
  10239. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10240. ClientCall &&client_call,
  10241. const string &body) {
  10242. Server svr;
  10243. setup_handler(svr);
  10244. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10245. auto se = detail::scope_exit([&] {
  10246. svr.stop();
  10247. t.join();
  10248. });
  10249. svr.wait_until_ready();
  10250. Client cli(HOST, PORT);
  10251. vector<uint64_t> progress_values;
  10252. bool progress_called = false;
  10253. auto res =
  10254. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10255. progress_values.push_back(current);
  10256. progress_called = true;
  10257. return true;
  10258. });
  10259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10260. EXPECT_EQ(200, res->status);
  10261. EXPECT_TRUE(progress_called);
  10262. }
  10263. TEST(UploadProgressTest, PostStringBodyBasic) {
  10264. TestStringBodyUploadProgress(
  10265. [](Server &svr) {
  10266. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10267. res.set_content("received", "text/plain");
  10268. });
  10269. },
  10270. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10271. return cli.Post("/test", body, "text/plain", progress_callback);
  10272. },
  10273. "test data for upload progress");
  10274. }
  10275. TEST(UploadProgressTest, PutStringBodyBasic) {
  10276. TestStringBodyUploadProgress(
  10277. [](Server &svr) {
  10278. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10279. res.set_content("put received", "text/plain");
  10280. });
  10281. },
  10282. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10283. return cli.Put("/test", body, "text/plain", progress_callback);
  10284. },
  10285. "put test data for upload progress");
  10286. }
  10287. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10288. TestStringBodyUploadProgress(
  10289. [](Server &svr) {
  10290. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10291. res.set_content("patch received", "text/plain");
  10292. });
  10293. },
  10294. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10295. return cli.Patch("/test", body, "text/plain", progress_callback);
  10296. },
  10297. "patch test data for upload progress");
  10298. }
  10299. // Helper function for content provider upload progress tests
  10300. template <typename SetupHandler, typename ClientCall>
  10301. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10302. ClientCall &&client_call) {
  10303. Server svr;
  10304. setup_handler(svr);
  10305. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10306. auto se = detail::scope_exit([&] {
  10307. svr.stop();
  10308. t.join();
  10309. });
  10310. svr.wait_until_ready();
  10311. Client cli(HOST, PORT);
  10312. vector<uint64_t> progress_values;
  10313. auto res =
  10314. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10315. progress_values.push_back(current);
  10316. return true;
  10317. });
  10318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10319. EXPECT_EQ(200, res->status);
  10320. EXPECT_FALSE(progress_values.empty());
  10321. }
  10322. TEST(UploadProgressTest, PostContentProviderProgress) {
  10323. TestContentProviderUploadProgress(
  10324. [](Server &svr) {
  10325. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10326. res.set_content("provider received", "text/plain");
  10327. });
  10328. },
  10329. [](Client &cli, UploadProgress progress_callback) {
  10330. return cli.Post(
  10331. "/test", 9,
  10332. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10333. sink.os << "test data";
  10334. return true;
  10335. },
  10336. "text/plain", progress_callback);
  10337. });
  10338. }
  10339. // Helper function for multipart upload progress tests
  10340. template <typename SetupHandler, typename ClientCall>
  10341. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10342. ClientCall &&client_call,
  10343. const string &endpoint) {
  10344. Server svr;
  10345. setup_handler(svr);
  10346. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10347. auto se = detail::scope_exit([&] {
  10348. svr.stop();
  10349. t.join();
  10350. });
  10351. svr.wait_until_ready();
  10352. Client cli(HOST, PORT);
  10353. vector<uint64_t> progress_values;
  10354. UploadFormDataItems items = {
  10355. {"field1", "value1", "", ""},
  10356. {"field2", "longer value for progress tracking test", "", ""},
  10357. {"file1", "file content data for upload progress", "test.txt",
  10358. "text/plain"}};
  10359. auto res = client_call(cli, endpoint, items,
  10360. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10361. progress_values.push_back(current);
  10362. return true;
  10363. });
  10364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10365. EXPECT_EQ(200, res->status);
  10366. EXPECT_FALSE(progress_values.empty());
  10367. }
  10368. TEST(UploadProgressTest, PostMultipartProgress) {
  10369. TestMultipartUploadProgress(
  10370. [](Server &svr) {
  10371. svr.Post("/multipart", [](const Request &req, Response &res) {
  10372. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10373. res.set_content("multipart received", "text/plain");
  10374. });
  10375. },
  10376. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10377. UploadProgress progress_callback) {
  10378. return cli.Post(endpoint, items, progress_callback);
  10379. },
  10380. "/multipart");
  10381. }
  10382. // Helper function for basic download progress tests
  10383. template <typename SetupHandler, typename ClientCall>
  10384. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10385. ClientCall &&client_call, const string &endpoint,
  10386. size_t expected_content_size) {
  10387. Server svr;
  10388. setup_handler(svr);
  10389. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10390. auto se = detail::scope_exit([&] {
  10391. svr.stop();
  10392. t.join();
  10393. });
  10394. svr.wait_until_ready();
  10395. Client cli(HOST, PORT);
  10396. vector<uint64_t> progress_values;
  10397. auto res = client_call(cli, endpoint,
  10398. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10399. progress_values.push_back(current);
  10400. return true;
  10401. });
  10402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10403. EXPECT_EQ(200, res->status);
  10404. EXPECT_FALSE(progress_values.empty());
  10405. EXPECT_EQ(expected_content_size, res->body.size());
  10406. }
  10407. TEST(DownloadProgressTest, GetBasic) {
  10408. TestBasicDownloadProgress(
  10409. [](Server &svr) {
  10410. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10411. string content(1000, 'D');
  10412. res.set_content(content, "text/plain");
  10413. });
  10414. },
  10415. [](Client &cli, const string &endpoint,
  10416. DownloadProgress progress_callback) {
  10417. return cli.Get(endpoint, progress_callback);
  10418. },
  10419. "/download", 1000u);
  10420. }
  10421. // Helper function for content receiver download progress tests
  10422. template <typename SetupHandler, typename ClientCall>
  10423. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10424. ClientCall &&client_call,
  10425. const string &endpoint,
  10426. size_t expected_content_size) {
  10427. Server svr;
  10428. setup_handler(svr);
  10429. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10430. auto se = detail::scope_exit([&] {
  10431. svr.stop();
  10432. t.join();
  10433. });
  10434. svr.wait_until_ready();
  10435. Client cli(HOST, PORT);
  10436. vector<uint64_t> progress_values;
  10437. string received_body;
  10438. auto res = client_call(
  10439. cli, endpoint,
  10440. [&](const char *data, size_t data_length) -> bool {
  10441. received_body.append(data, data_length);
  10442. return true;
  10443. },
  10444. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10445. progress_values.push_back(current);
  10446. return true;
  10447. });
  10448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10449. EXPECT_EQ(200, res->status);
  10450. EXPECT_FALSE(progress_values.empty());
  10451. EXPECT_EQ(expected_content_size, received_body.size());
  10452. EXPECT_TRUE(res->body.empty());
  10453. }
  10454. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10455. TestContentReceiverDownloadProgress(
  10456. [](Server &svr) {
  10457. svr.Get("/download-receiver",
  10458. [](const Request & /*req*/, Response &res) {
  10459. string content(2000, 'R');
  10460. res.set_content(content, "text/plain");
  10461. });
  10462. },
  10463. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10464. DownloadProgress progress_callback) {
  10465. return cli.Get(endpoint, content_receiver, progress_callback);
  10466. },
  10467. "/download-receiver", 2000u);
  10468. }
  10469. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10470. // A provider reaching a pass with nothing to hand over - an empty buffer
  10471. // popped off a queue, say - must not be taken to mean the body is finished.
  10472. // It used to end the loop with the terminating chunk unwritten while the
  10473. // server still considered the response complete, so the peer waited for an
  10474. // end that never arrived.
  10475. Server svr;
  10476. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10477. auto step = std::make_shared<int>(0);
  10478. res.set_chunked_content_provider("text/plain",
  10479. [step](size_t /*offset*/, DataSink &sink) {
  10480. switch ((*step)++) {
  10481. case 0: sink.write("", 0); break;
  10482. case 1: sink.write("hello", 5); break;
  10483. default: sink.done(); break;
  10484. }
  10485. return true;
  10486. });
  10487. });
  10488. auto port = svr.bind_to_any_port(HOST);
  10489. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10490. auto listen_se = detail::scope_exit([&] {
  10491. svr.stop();
  10492. listen_thread.join();
  10493. ASSERT_FALSE(svr.is_running());
  10494. });
  10495. svr.wait_until_ready();
  10496. Client cli(HOST, port);
  10497. // Without the fix the body is never terminated, so bound the wait rather
  10498. // than letting the test hang on the default read timeout.
  10499. cli.set_read_timeout(5, 0);
  10500. auto res = cli.Get("/stream");
  10501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10502. EXPECT_EQ(StatusCode::OK_200, res->status);
  10503. EXPECT_EQ("hello", res->body);
  10504. }
  10505. TEST(StreamingTest, NoContentLengthStreaming) {
  10506. Server svr;
  10507. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10508. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10509. if (offset < 6) {
  10510. sink.os << (offset < 3 ? "a" : "b");
  10511. } else {
  10512. sink.done();
  10513. }
  10514. return true;
  10515. });
  10516. });
  10517. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10518. auto listen_se = detail::scope_exit([&] {
  10519. svr.stop();
  10520. listen_thread.join();
  10521. ASSERT_FALSE(svr.is_running());
  10522. });
  10523. svr.wait_until_ready();
  10524. Client client(HOST, PORT);
  10525. auto get_thread = std::thread([&client]() {
  10526. std::string s;
  10527. auto res =
  10528. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10529. s += std::string(data, len);
  10530. return true;
  10531. });
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(StatusCode::OK_200, res->status);
  10534. EXPECT_EQ("aaabbb", s);
  10535. });
  10536. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10537. // Give GET time to get a few messages.
  10538. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10539. }
  10540. TEST(MountTest, Unmount) {
  10541. Server svr;
  10542. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10543. auto se = detail::scope_exit([&] {
  10544. svr.stop();
  10545. listen_thread.join();
  10546. ASSERT_FALSE(svr.is_running());
  10547. });
  10548. svr.wait_until_ready();
  10549. Client cli("localhost", PORT);
  10550. svr.set_mount_point("/mount2", "./www2");
  10551. auto res = cli.Get("/");
  10552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10554. res = cli.Get("/mount2/dir/test.html");
  10555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10556. EXPECT_EQ(StatusCode::OK_200, res->status);
  10557. svr.set_mount_point("/", "./www");
  10558. res = cli.Get("/dir/");
  10559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10560. EXPECT_EQ(StatusCode::OK_200, res->status);
  10561. svr.remove_mount_point("/");
  10562. res = cli.Get("/dir/");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10565. svr.remove_mount_point("/mount2");
  10566. res = cli.Get("/mount2/dir/test.html");
  10567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10569. }
  10570. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10571. Server svr;
  10572. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10573. svr.Get("/api/hello", [](const Request &, Response &res) {
  10574. res.set_content("api", "text/plain");
  10575. });
  10576. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10577. auto se = detail::scope_exit([&] {
  10578. svr.stop();
  10579. listen_thread.join();
  10580. ASSERT_FALSE(svr.is_running());
  10581. });
  10582. svr.wait_until_ready();
  10583. Client cli(HOST, PORT);
  10584. auto res = cli.Get("/dir/test.html");
  10585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10586. EXPECT_EQ(StatusCode::OK_200, res->status);
  10587. res = cli.Get("/api/hello");
  10588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10589. EXPECT_EQ(StatusCode::OK_200, res->status);
  10590. EXPECT_EQ("api", res->body);
  10591. }
  10592. TEST(MountTest, PathSegmentBoundary) {
  10593. Server svr;
  10594. svr.set_mount_point("/mount2", "./www2");
  10595. svr.set_mount_point("/", "./www");
  10596. auto port = svr.bind_to_any_port(HOST);
  10597. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10598. auto se = detail::scope_exit([&] {
  10599. svr.stop();
  10600. listen_thread.join();
  10601. ASSERT_FALSE(svr.is_running());
  10602. });
  10603. svr.wait_until_ready();
  10604. Client cli(HOST, port);
  10605. auto res = cli.Get("/mount2/dir/test.html");
  10606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10607. EXPECT_EQ(StatusCode::OK_200, res->status);
  10608. // "/mount2" must not match part-way through a path segment.
  10609. res = cli.Get("/mount2dir/test.html");
  10610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10611. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10612. // A mount point ending in '/' keeps matching every path below it.
  10613. res = cli.Get("/dir/test.html");
  10614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10615. EXPECT_EQ(StatusCode::OK_200, res->status);
  10616. }
  10617. TEST(MountTest, Redicect) {
  10618. Server svr;
  10619. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10620. auto se = detail::scope_exit([&] {
  10621. svr.stop();
  10622. listen_thread.join();
  10623. ASSERT_FALSE(svr.is_running());
  10624. });
  10625. svr.set_mount_point("/", "./www");
  10626. svr.wait_until_ready();
  10627. Client cli("localhost", PORT);
  10628. auto res = cli.Get("/dir/");
  10629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10630. EXPECT_EQ(StatusCode::OK_200, res->status);
  10631. res = cli.Get("/dir");
  10632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10633. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10634. res = cli.Get("/file");
  10635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10636. EXPECT_EQ(StatusCode::OK_200, res->status);
  10637. res = cli.Get("/file/");
  10638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10639. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10640. cli.set_follow_location(true);
  10641. res = cli.Get("/dir");
  10642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10643. EXPECT_EQ(StatusCode::OK_200, res->status);
  10644. }
  10645. TEST(MountTest, MultibytesPathName) {
  10646. Server svr;
  10647. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10648. auto se = detail::scope_exit([&] {
  10649. svr.stop();
  10650. listen_thread.join();
  10651. ASSERT_FALSE(svr.is_running());
  10652. });
  10653. svr.set_mount_point("/", "./www");
  10654. svr.wait_until_ready();
  10655. Client cli("localhost", PORT);
  10656. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10658. EXPECT_EQ(StatusCode::OK_200, res->status);
  10659. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10660. }
  10661. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10662. // in the pre-routing handler sees the path of every file that is served
  10663. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10664. Server svr;
  10665. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10666. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10667. if (req.path == "/dir/test.html") {
  10668. res.status = StatusCode::Unauthorized_401;
  10669. return Server::HandlerResponse::Handled;
  10670. }
  10671. return Server::HandlerResponse::Unhandled;
  10672. });
  10673. auto port = svr.bind_to_any_port(HOST);
  10674. ASSERT_LT(0, port);
  10675. thread t = thread([&] { svr.listen_after_bind(); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. t.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. Client cli(HOST, port);
  10683. for (auto path :
  10684. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10685. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10686. SCOPED_TRACE(path);
  10687. auto res = cli.Get(path);
  10688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10689. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10690. }
  10691. }
  10692. #ifdef _WIN32
  10693. // Issue #2435: mmap::open() must succeed even when another handle holds
  10694. // the file open for writing (e.g. an active log file).
  10695. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10696. const char *path = "mmap_concurrent_writer_test.txt";
  10697. const char *content = "hello";
  10698. {
  10699. std::ofstream f(path, std::ios::binary);
  10700. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10701. }
  10702. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10703. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10704. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10705. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10706. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10707. detail::mmap m(path);
  10708. ASSERT_TRUE(m.is_open());
  10709. EXPECT_EQ(strlen(content), m.size());
  10710. char buf[8];
  10711. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10712. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10713. }
  10714. #endif
  10715. #ifndef _WIN32
  10716. // A directory or a device has no size to serve.
  10717. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10718. const char *path = "./mmap_not_regular_test_dir";
  10719. ASSERT_EQ(0, ::mkdir(path, 0755));
  10720. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10721. for (auto p : {path, "/dev/null"}) {
  10722. detail::mmap m(p);
  10723. EXPECT_FALSE(m.is_open()) << p;
  10724. EXPECT_EQ(0U, m.size()) << p;
  10725. }
  10726. Server svr;
  10727. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10728. res.set_file_content("/dev/null");
  10729. });
  10730. auto port = svr.bind_to_any_port(HOST);
  10731. thread t = thread([&] { svr.listen_after_bind(); });
  10732. auto se = detail::scope_exit([&] {
  10733. svr.stop();
  10734. t.join();
  10735. });
  10736. svr.wait_until_ready();
  10737. auto res = Client(HOST, port).Get("/null");
  10738. ASSERT_TRUE(res);
  10739. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10740. }
  10741. #endif
  10742. #ifdef __linux__
  10743. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10744. TEST(MmapTest, FileIsNotMapped) {
  10745. const char *path = "mmap_not_mapped_test.txt";
  10746. {
  10747. std::ofstream f(path, std::ios::binary);
  10748. f << "hello";
  10749. }
  10750. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10751. detail::mmap m(path);
  10752. ASSERT_TRUE(m.is_open());
  10753. std::ifstream maps("/proc/self/maps");
  10754. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10755. std::istreambuf_iterator<char>());
  10756. EXPECT_EQ(std::string::npos, mappings.find(path));
  10757. }
  10758. #endif
  10759. TEST(KeepAliveTest, ReadTimeout) {
  10760. Server svr;
  10761. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10762. std::this_thread::sleep_for(std::chrono::seconds(2));
  10763. res.set_content("a", "text/plain");
  10764. });
  10765. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10766. res.set_content("b", "text/plain");
  10767. });
  10768. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10769. auto se = detail::scope_exit([&] {
  10770. svr.stop();
  10771. listen_thread.join();
  10772. ASSERT_FALSE(svr.is_running());
  10773. });
  10774. svr.wait_until_ready();
  10775. Client cli("localhost", PORT);
  10776. cli.set_keep_alive(true);
  10777. cli.set_read_timeout(std::chrono::seconds(1));
  10778. auto resa = cli.Get("/a");
  10779. ASSERT_FALSE(resa);
  10780. EXPECT_EQ(Error::Read, resa.error());
  10781. auto resb = cli.Get("/b");
  10782. ASSERT_TRUE(resb);
  10783. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10784. EXPECT_EQ("b", resb->body);
  10785. }
  10786. TEST(KeepAliveTest, MaxCount) {
  10787. size_t keep_alive_max_count = 3;
  10788. Server svr;
  10789. svr.set_keep_alive_max_count(keep_alive_max_count);
  10790. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10791. res.set_content("Hello World!", "text/plain");
  10792. });
  10793. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10794. auto se = detail::scope_exit([&] {
  10795. svr.stop();
  10796. listen_thread.join();
  10797. ASSERT_FALSE(svr.is_running());
  10798. });
  10799. svr.wait_until_ready();
  10800. Client cli(HOST, PORT);
  10801. cli.set_keep_alive(true);
  10802. for (size_t i = 0; i < 5; i++) {
  10803. auto result = cli.Get("/hi");
  10804. ASSERT_TRUE(result);
  10805. EXPECT_EQ(StatusCode::OK_200, result->status);
  10806. if (i == keep_alive_max_count - 1) {
  10807. EXPECT_EQ("close", result->get_header_value("Connection"));
  10808. } else {
  10809. EXPECT_FALSE(result->has_header("Connection"));
  10810. }
  10811. }
  10812. }
  10813. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10814. // can pull the next one into the server's buffer. The server must serve it
  10815. // without waiting for the socket to become readable again. The keep-alive
  10816. // timeout outlasts the client's read timeout, so a request left waiting for it
  10817. // shows up as a missing response.
  10818. static void serve_pipelining_routes(Server &svr,
  10819. const std::function<void(int)> &client) {
  10820. svr.set_keep_alive_timeout(5);
  10821. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10822. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10823. });
  10824. svr.Post("/echo", [](const Request &req, Response &res) {
  10825. res.set_content("echo " + req.body, "text/plain");
  10826. });
  10827. auto port = svr.bind_to_any_port(HOST);
  10828. thread t = thread([&] { svr.listen_after_bind(); });
  10829. auto se = detail::scope_exit([&] {
  10830. svr.stop();
  10831. t.join();
  10832. });
  10833. svr.wait_until_ready();
  10834. client(port);
  10835. }
  10836. static std::string
  10837. send_pipelined_requests(const std::vector<std::string> &parts) {
  10838. Server svr;
  10839. std::string res;
  10840. serve_pipelining_routes(svr, [&](int port) {
  10841. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10842. });
  10843. return res;
  10844. }
  10845. static void expect_in_order(const std::string &res,
  10846. const std::vector<std::string> &bodies) {
  10847. size_t pos = 0;
  10848. for (const auto &body : bodies) {
  10849. pos = res.find(body, pos);
  10850. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10851. pos += body.size();
  10852. }
  10853. }
  10854. TEST(KeepAliveTest, PipelinedRequests) {
  10855. auto res = send_pipelined_requests(
  10856. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10857. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10858. "Content-Length: 4\r\n\r\nbody"
  10859. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10860. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10861. }
  10862. // The second request starts in the server's buffer and ends on the socket.
  10863. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10864. auto res =
  10865. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10866. "GET /hi/2 HTTP/1.1\r\nHo",
  10867. "st: localhost\r\nConnection: close\r\n\r\n"});
  10868. expect_in_order(res, {"hi 1", "hi 2"});
  10869. }
  10870. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10871. // CRLF after a body does not turn into a 400 for the next request.
  10872. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10873. auto res = send_pipelined_requests(
  10874. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10875. "Content-Length: 4\r\n\r\nbody\r\n"
  10876. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10877. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10878. expect_in_order(res, {"echo body", "hi 2"});
  10879. }
  10880. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10881. // must not be served as the next request.
  10882. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10883. auto res = send_pipelined_requests(
  10884. {"INVALID REQUEST LINE\r\n\r\n"
  10885. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10886. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10887. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10888. }
  10889. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10890. // Over TLS, the next request is held by the TLS library as already decrypted
  10891. // data rather than on the socket.
  10892. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10894. std::string res;
  10895. serve_pipelining_routes(svr, [&](int port) {
  10896. // One part, so all three requests arrive in one TLS record
  10897. EXPECT_TRUE(send_ssl_request_in_parts(
  10898. 2,
  10899. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10900. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10901. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10902. &res, port));
  10903. });
  10904. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10905. }
  10906. #endif
  10907. TEST(KeepAliveTest, Issue1041) {
  10908. Server svr;
  10909. svr.set_keep_alive_timeout(3);
  10910. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10911. res.set_content("Hello World!", "text/plain");
  10912. });
  10913. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10914. auto se = detail::scope_exit([&] {
  10915. svr.stop();
  10916. listen_thread.join();
  10917. ASSERT_FALSE(svr.is_running());
  10918. });
  10919. svr.wait_until_ready();
  10920. Client cli(HOST, PORT);
  10921. cli.set_keep_alive(true);
  10922. auto result = cli.Get("/hi");
  10923. ASSERT_TRUE(result);
  10924. EXPECT_EQ(StatusCode::OK_200, result->status);
  10925. std::this_thread::sleep_for(std::chrono::seconds(5));
  10926. result = cli.Get("/hi");
  10927. ASSERT_TRUE(result);
  10928. EXPECT_EQ(StatusCode::OK_200, result->status);
  10929. }
  10930. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10931. Server svr;
  10932. svr.set_keep_alive_max_count(0);
  10933. std::set<int> remote_ports;
  10934. svr.Get("/hi", [&](const Request &req, Response &res) {
  10935. remote_ports.insert(req.remote_port);
  10936. res.set_content("hi", "text/plain");
  10937. });
  10938. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10939. auto se = detail::scope_exit([&] {
  10940. svr.stop();
  10941. listen_thread.join();
  10942. ASSERT_FALSE(svr.is_running());
  10943. });
  10944. svr.wait_until_ready();
  10945. Client cli(HOST, PORT);
  10946. cli.set_keep_alive(true);
  10947. for (int i = 0; i < 3; i++) {
  10948. auto res = cli.Get("/hi");
  10949. ASSERT_TRUE(res);
  10950. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10951. }
  10952. // All three over one connection
  10953. EXPECT_EQ(1u, remote_ports.size());
  10954. }
  10955. TEST(KeepAliveTest, Issue1959) {
  10956. Server svr;
  10957. svr.set_keep_alive_timeout(5);
  10958. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10959. res.set_content("a", "text/plain");
  10960. });
  10961. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10962. auto se = detail::scope_exit([&] {
  10963. if (!svr.is_running()) return;
  10964. svr.stop();
  10965. listen_thread.join();
  10966. ASSERT_FALSE(svr.is_running());
  10967. });
  10968. svr.wait_until_ready();
  10969. Client cli("localhost", PORT);
  10970. cli.set_keep_alive(true);
  10971. using namespace std::chrono;
  10972. auto start = steady_clock::now();
  10973. cli.Get("/a");
  10974. svr.stop();
  10975. listen_thread.join();
  10976. auto end = steady_clock::now();
  10977. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10978. EXPECT_LT(elapsed, 5000);
  10979. }
  10980. #ifdef CPPHTTPLIB_SSL_ENABLED
  10981. TEST(KeepAliveTest, SSLClientReconnection) {
  10982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10983. ASSERT_TRUE(svr.is_valid());
  10984. svr.set_keep_alive_timeout(1);
  10985. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10986. res.set_content("Hello World!", "text/plain");
  10987. });
  10988. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10989. auto se = detail::scope_exit([&] {
  10990. svr.stop();
  10991. listen_thread.join();
  10992. ASSERT_FALSE(svr.is_running());
  10993. });
  10994. svr.wait_until_ready();
  10995. SSLClient cli(HOST, PORT);
  10996. cli.enable_server_certificate_verification(false);
  10997. cli.set_keep_alive(true);
  10998. auto result = cli.Get("/hi");
  10999. ASSERT_TRUE(result);
  11000. EXPECT_EQ(StatusCode::OK_200, result->status);
  11001. result = cli.Get("/hi");
  11002. ASSERT_TRUE(result);
  11003. EXPECT_EQ(StatusCode::OK_200, result->status);
  11004. std::this_thread::sleep_for(std::chrono::seconds(2));
  11005. // Recoonect
  11006. result = cli.Get("/hi");
  11007. ASSERT_TRUE(result);
  11008. EXPECT_EQ(StatusCode::OK_200, result->status);
  11009. result = cli.Get("/hi");
  11010. ASSERT_TRUE(result);
  11011. EXPECT_EQ(StatusCode::OK_200, result->status);
  11012. }
  11013. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11015. ASSERT_TRUE(svr.is_valid());
  11016. svr.set_keep_alive_timeout(1);
  11017. std::string content = "reconnect";
  11018. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11019. res.set_content("Hello World!", "text/plain");
  11020. });
  11021. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11022. auto se = detail::scope_exit([&] {
  11023. svr.stop();
  11024. listen_thread.join();
  11025. ASSERT_FALSE(svr.is_running());
  11026. });
  11027. svr.wait_until_ready();
  11028. SSLClient cli(HOST, PORT);
  11029. cli.enable_server_certificate_verification(false);
  11030. cli.set_keep_alive(true);
  11031. auto result = cli.Post(
  11032. "/hi", content.size(),
  11033. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11034. sink.write(content.c_str(), content.size());
  11035. return true;
  11036. },
  11037. "text/plain");
  11038. ASSERT_TRUE(result);
  11039. EXPECT_EQ(200, result->status);
  11040. std::this_thread::sleep_for(std::chrono::seconds(2));
  11041. // Recoonect
  11042. result = cli.Post(
  11043. "/hi", content.size(),
  11044. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11045. sink.write(content.c_str(), content.size());
  11046. return true;
  11047. },
  11048. "text/plain");
  11049. ASSERT_TRUE(result);
  11050. EXPECT_EQ(200, result->status);
  11051. result = cli.Post(
  11052. "/hi", content.size(),
  11053. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11054. sink.write(content.c_str(), content.size());
  11055. return true;
  11056. },
  11057. "text/plain");
  11058. ASSERT_TRUE(result);
  11059. EXPECT_EQ(200, result->status);
  11060. }
  11061. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11062. using namespace httplib::tls;
  11063. {
  11064. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11065. ASSERT_TRUE(svr.is_valid());
  11066. svr.Get("/sni", [&](const Request &req, Response &res) {
  11067. std::string expected = req.sni();
  11068. EXPECT_EQ(expected, req.get_param_value("expected"));
  11069. res.set_content("ok", "text/plain");
  11070. });
  11071. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11072. auto se = detail::scope_exit([&] {
  11073. svr.stop();
  11074. listen_thread.join();
  11075. ASSERT_FALSE(svr.is_running());
  11076. });
  11077. svr.wait_until_ready();
  11078. {
  11079. SSLClient cli("localhost", PORT);
  11080. cli.enable_server_certificate_verification(false);
  11081. auto res = cli.Get("/sni?expected=localhost");
  11082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11083. }
  11084. {
  11085. SSLClient cli("::1", PORT);
  11086. cli.enable_server_certificate_verification(false);
  11087. auto res = cli.Get("/sni?expected=");
  11088. // NOTE: This may fail if the server is listening on IPv4 only
  11089. // (e.g., when localhost resolves to 127.0.0.1 only)
  11090. if (res) {
  11091. EXPECT_EQ(StatusCode::OK_200, res->status);
  11092. } else {
  11093. EXPECT_EQ(Error::Connection, res.error());
  11094. }
  11095. }
  11096. }
  11097. }
  11098. // The SNI of a failed handshake does not reach the next connection that the
  11099. // same worker thread serves
  11100. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11102. ASSERT_TRUE(svr.is_valid());
  11103. svr.new_task_queue = [] { return new ThreadPool(1); };
  11104. svr.Get("/sni", [](const Request &req, Response &res) {
  11105. res.set_content(req.sni(), "text/plain");
  11106. });
  11107. auto port = svr.bind_to_any_port("127.0.0.1");
  11108. ASSERT_LT(0, port);
  11109. thread t = thread([&] { svr.listen_after_bind(); });
  11110. auto se = detail::scope_exit([&] {
  11111. svr.stop();
  11112. t.join();
  11113. ASSERT_FALSE(svr.is_running());
  11114. });
  11115. svr.wait_until_ready();
  11116. {
  11117. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11118. SSLClient cli("localhost", port);
  11119. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11120. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11121. auto res = cli.Get("/sni");
  11122. ASSERT_FALSE(res);
  11123. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11124. }
  11125. // An IP host sends no SNI (RFC 6066)
  11126. SSLClient cli("127.0.0.1", port);
  11127. cli.enable_server_certificate_verification(false);
  11128. auto res = cli.Get("/sni");
  11129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11130. EXPECT_EQ("", res->body);
  11131. }
  11132. #endif
  11133. TEST(ClientProblemDetectionTest, ContentProvider) {
  11134. Server svr;
  11135. size_t content_length = 1024 * 1024;
  11136. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11137. res.set_content_provider(
  11138. content_length, "text/plain",
  11139. [&](size_t offset, size_t length, DataSink &sink) {
  11140. auto out_len = std::min(length, static_cast<size_t>(1024));
  11141. std::string out(out_len, '@');
  11142. sink.write(out.data(), out_len);
  11143. return offset < 4096;
  11144. },
  11145. [](bool success) { ASSERT_FALSE(success); });
  11146. });
  11147. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11148. res.set_content_provider(
  11149. 0, "text/plain",
  11150. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11151. EXPECT_TRUE(false);
  11152. return true;
  11153. },
  11154. [](bool success) { ASSERT_FALSE(success); });
  11155. });
  11156. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  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("localhost", PORT);
  11164. {
  11165. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11166. size_t /*data_length*/) { return false; });
  11167. ASSERT_FALSE(res);
  11168. }
  11169. {
  11170. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11171. size_t /*data_length*/) { return false; });
  11172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11173. }
  11174. }
  11175. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11176. // A provider that reports success without writing anything and without
  11177. // calling done() used to be handed the same offset and length again on every
  11178. // pass, so it spun for as long as the peer stayed connected.
  11179. Server svr;
  11180. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11181. res.set_content("ok", "text/plain");
  11182. });
  11183. auto port = svr.bind_to_any_port(HOST);
  11184. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11185. auto se = detail::scope_exit([&] {
  11186. svr.stop();
  11187. listen_thread.join();
  11188. ASSERT_FALSE(svr.is_running());
  11189. });
  11190. svr.wait_until_ready();
  11191. std::atomic<int> call_count{0};
  11192. Client cli(HOST, port);
  11193. auto res = cli.Post(
  11194. "/", 1024,
  11195. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11196. // Give up after enough passes to show the spin, so that losing the
  11197. // check below fails this test instead of hanging it.
  11198. return ++call_count < 100;
  11199. },
  11200. "text/plain");
  11201. ASSERT_FALSE(res);
  11202. EXPECT_EQ(Error::Write, res.error());
  11203. EXPECT_EQ(1, call_count.load());
  11204. }
  11205. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11206. // A writer only has to assign `write`. The other three used to be left as
  11207. // empty std::functions, so a provider calling one threw
  11208. // std::bad_function_call out of the thread running it and took the whole
  11209. // process down.
  11210. DataSink sink;
  11211. std::string written;
  11212. sink.write = [&](const char *data, size_t data_len) {
  11213. written.append(data, data_len);
  11214. return true;
  11215. };
  11216. EXPECT_TRUE(sink.is_writable());
  11217. sink.done();
  11218. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11219. EXPECT_TRUE(written.empty());
  11220. }
  11221. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11222. // A sink that cannot carry trailers still has to finish.
  11223. DataSink sink;
  11224. auto done_count = 0;
  11225. sink.done = [&]() { done_count++; };
  11226. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11227. EXPECT_EQ(1, done_count);
  11228. }
  11229. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11230. Server svr;
  11231. const std::string body(4096, 'x');
  11232. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11233. res.set_content_provider(body.size(), "text/plain",
  11234. [&](size_t offset, size_t length, DataSink &sink) {
  11235. sink.write(body.data() + offset, length);
  11236. sink.done();
  11237. return true;
  11238. });
  11239. });
  11240. auto port = svr.bind_to_any_port(HOST);
  11241. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11242. auto se = detail::scope_exit([&] {
  11243. svr.stop();
  11244. listen_thread.join();
  11245. ASSERT_FALSE(svr.is_running());
  11246. });
  11247. svr.wait_until_ready();
  11248. Client cli(HOST, port);
  11249. auto res = cli.Get("/");
  11250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11251. EXPECT_EQ(StatusCode::OK_200, res->status);
  11252. EXPECT_EQ(body, res->body);
  11253. }
  11254. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11255. Server svr;
  11256. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11257. res.set_content_provider(
  11258. 1024, "text/plain",
  11259. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11260. sink.write("hello", 5);
  11261. sink.done(); // short of the 1024 bytes the response promised
  11262. return true;
  11263. });
  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. Client cli(HOST, port);
  11274. cli.set_read_timeout(5, 0);
  11275. // The response is short of its Content-Length, so the client cannot read a
  11276. // complete body. What matters is that this returns at all: a no-op done()
  11277. // would leave the writer looping over a provider that never makes progress.
  11278. auto res = cli.Get("/");
  11279. EXPECT_FALSE(res);
  11280. }
  11281. // Read as the next response by a peer that sees it after a framed body.
  11282. static const std::string smuggled_response =
  11283. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11284. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11285. Server svr;
  11286. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11287. res.set_content_provider(
  11288. 5, "text/plain",
  11289. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11290. auto data = "AAAAA" + smuggled_response;
  11291. sink.write(data.data(), data.size());
  11292. return true;
  11293. });
  11294. });
  11295. thread t = thread([&] { svr.listen(HOST, PORT); });
  11296. auto se = detail::scope_exit([&] {
  11297. svr.stop();
  11298. t.join();
  11299. ASSERT_FALSE(svr.is_running());
  11300. });
  11301. svr.wait_until_ready();
  11302. std::string resp;
  11303. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11304. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11305. resp.clear();
  11306. ASSERT_TRUE(send_request(
  11307. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11308. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11309. }
  11310. TEST(NoContentTest, BodyIsNotSent) {
  11311. Server svr;
  11312. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11313. res.status = StatusCode::NoContent_204;
  11314. res.set_content(smuggled_response, "text/plain");
  11315. });
  11316. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11317. res.status = StatusCode::NotModified_304;
  11318. res.set_chunked_content_provider(
  11319. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11320. sink.write(smuggled_response.data(), smuggled_response.size());
  11321. sink.done();
  11322. return true;
  11323. });
  11324. });
  11325. thread t = thread([&] { svr.listen(HOST, PORT); });
  11326. auto se = detail::scope_exit([&] {
  11327. svr.stop();
  11328. t.join();
  11329. ASSERT_FALSE(svr.is_running());
  11330. });
  11331. svr.wait_until_ready();
  11332. for (auto path : {"/204", "/304"}) {
  11333. std::string resp;
  11334. ASSERT_TRUE(send_request(
  11335. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11336. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11337. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11338. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11339. }
  11340. }
  11341. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11342. Server svr;
  11343. std::atomic<bool> smuggled(false);
  11344. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11345. res.set_content("ok", "text/plain");
  11346. });
  11347. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11348. smuggled = true;
  11349. });
  11350. auto port = svr.bind_to_any_port(HOST);
  11351. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11352. auto se = detail::scope_exit([&] {
  11353. svr.stop();
  11354. listen_thread.join();
  11355. ASSERT_FALSE(svr.is_running());
  11356. });
  11357. svr.wait_until_ready();
  11358. // What follows the body would be read as the next request.
  11359. Client cli(HOST, port);
  11360. auto res = cli.Post(
  11361. "/", 5,
  11362. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11363. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11364. sink.write(data.data(), data.size());
  11365. return true;
  11366. },
  11367. "text/plain");
  11368. ASSERT_FALSE(res);
  11369. EXPECT_EQ(Error::Write, res.error());
  11370. EXPECT_FALSE(smuggled);
  11371. }
  11372. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11373. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11374. // The compressed path builds the whole body before connecting, so this
  11375. // fails client-side and never reaches a server.
  11376. Client cli(HOST, PORT);
  11377. cli.set_compress(true);
  11378. auto res = cli.Post(
  11379. "/", 1024,
  11380. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11381. sink.write("hello", 5);
  11382. sink.done(); // short of the 1024 bytes the request announced
  11383. return true;
  11384. },
  11385. "text/plain");
  11386. ASSERT_FALSE(res);
  11387. EXPECT_EQ(Error::Write, res.error());
  11388. }
  11389. #endif
  11390. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11391. Server svr;
  11392. svr.set_error_handler([](Request const &, Response &res) -> void {
  11393. res.set_chunked_content_provider(
  11394. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11395. sink.os << "hello";
  11396. sink.os << "world";
  11397. sink.done();
  11398. return true;
  11399. });
  11400. });
  11401. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11402. auto se = detail::scope_exit([&] {
  11403. svr.stop();
  11404. listen_thread.join();
  11405. ASSERT_FALSE(svr.is_running());
  11406. });
  11407. svr.wait_until_ready();
  11408. Client cli("localhost", PORT);
  11409. auto res = cli.Get("/");
  11410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11411. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11412. EXPECT_EQ("helloworld", res->body);
  11413. }
  11414. // A body set after a content provider must replace it, not be sent through it.
  11415. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11416. Server svr;
  11417. svr.set_mount_point("/", "./www");
  11418. svr.set_file_request_handler([](const Request &req, Response &res) {
  11419. if (req.path == "/dir/test.html") {
  11420. res.status = StatusCode::Forbidden_403;
  11421. res.set_content(std::string(5000, 'D'), "text/plain");
  11422. } else if (req.path == "/file") {
  11423. res.status = StatusCode::Forbidden_403;
  11424. res.body = "Denied";
  11425. }
  11426. });
  11427. auto port = svr.bind_to_any_port(HOST);
  11428. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11429. auto se = detail::scope_exit([&] {
  11430. svr.stop();
  11431. t.join();
  11432. ASSERT_FALSE(svr.is_running());
  11433. });
  11434. svr.wait_until_ready();
  11435. Client cli(HOST, port);
  11436. {
  11437. auto res = cli.Get("/dir/test.html");
  11438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11439. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11440. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11441. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11442. }
  11443. {
  11444. auto res = cli.Get("/file");
  11445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11446. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11447. EXPECT_EQ("Denied", res->body);
  11448. }
  11449. {
  11450. auto res = cli.Get("/dir/index.html");
  11451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11452. EXPECT_EQ(StatusCode::OK_200, res->status);
  11453. EXPECT_EQ(0U, res->body.find("<html>"));
  11454. }
  11455. }
  11456. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11457. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11458. Server svr;
  11459. std::vector<bool> released;
  11460. std::mutex released_mutex;
  11461. auto releaser = [&](bool success) {
  11462. std::lock_guard<std::mutex> guard(released_mutex);
  11463. released.push_back(success);
  11464. };
  11465. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11466. return sink.write(&"hello"[offset], length);
  11467. };
  11468. svr.Get("/sized", [&](const Request &, Response &res) {
  11469. res.status = StatusCode::NotFound_404;
  11470. res.set_content_provider(5, "text/plain", provider, releaser);
  11471. });
  11472. svr.Get("/chunked", [&](const Request &, Response &res) {
  11473. res.status = StatusCode::ServiceUnavailable_503;
  11474. res.set_chunked_content_provider(
  11475. "text/plain",
  11476. [](size_t, DataSink &sink) {
  11477. sink.os << "chunk";
  11478. sink.done();
  11479. return true;
  11480. },
  11481. releaser);
  11482. });
  11483. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11484. res.set_content_provider(5, "text/plain", provider, releaser);
  11485. throw std::runtime_error("after the provider");
  11486. });
  11487. svr.set_error_handler([](const Request &req, Response &res) {
  11488. // Leave the exception handler's content to it.
  11489. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11490. res.set_content(std::string(1000, 'E'), "text/html");
  11491. return Server::HandlerResponse::Handled;
  11492. });
  11493. svr.set_exception_handler(
  11494. [](const Request &, Response &res, std::exception_ptr) {
  11495. res.status = StatusCode::InternalServerError_500;
  11496. res.set_content(std::string(1000, 'X'), "text/html");
  11497. });
  11498. auto port = svr.bind_to_any_port(HOST);
  11499. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11500. auto se = detail::scope_exit([&] {
  11501. svr.stop();
  11502. t.join();
  11503. ASSERT_FALSE(svr.is_running());
  11504. });
  11505. svr.wait_until_ready();
  11506. Client cli(HOST, port);
  11507. {
  11508. auto res = cli.Get("/sized");
  11509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11510. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11511. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11512. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11513. }
  11514. {
  11515. auto res = cli.Get("/chunked");
  11516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11517. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11518. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11519. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11520. }
  11521. {
  11522. auto res = cli.Get("/throw");
  11523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11524. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11525. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11526. }
  11527. std::lock_guard<std::mutex> guard(released_mutex);
  11528. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11529. }
  11530. #endif
  11531. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11532. Server svr;
  11533. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11534. return sink.write(&"abc"[offset], length);
  11535. };
  11536. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11537. res.set_file_content("./www/dir/test.html");
  11538. res.set_content("body", "text/plain");
  11539. });
  11540. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11541. res.set_content(std::string(100, 'B'), "text/plain");
  11542. res.set_file_content("./www/dir/test.html");
  11543. });
  11544. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11545. res.set_content(std::string(100, 'B'), "text/plain");
  11546. res.set_content_provider(3, "text/x-provider", abc);
  11547. });
  11548. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11549. res.set_content_provider(3, "text/x-provider", abc);
  11550. res.set_content(std::string(100, 'B'), "text/plain");
  11551. });
  11552. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11553. res.set_content_provider(3, "text/x-provider", abc);
  11554. res.set_file_content("./www/dir/test.html", "text/x-file");
  11555. });
  11556. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11557. res.set_file_content("./www/dir/test.html");
  11558. res.set_header("Content-Type", "text/x-handler");
  11559. });
  11560. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11561. res.set_content_provider(3, "text/plain", abc);
  11562. res.body = "direct";
  11563. });
  11564. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11565. res.set_file_content("./www/dir/test.html");
  11566. res.body = "direct";
  11567. });
  11568. auto port = svr.bind_to_any_port(HOST);
  11569. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11570. auto se = detail::scope_exit([&] {
  11571. svr.stop();
  11572. t.join();
  11573. ASSERT_FALSE(svr.is_running());
  11574. });
  11575. svr.wait_until_ready();
  11576. Client cli(HOST, port);
  11577. auto expect_body = [&](const char *path, const std::string &body,
  11578. const std::string &type) {
  11579. // Uncompressed, so Content-Length can be compared with the body.
  11580. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11581. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11582. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11583. EXPECT_EQ(body, res->body) << path;
  11584. EXPECT_EQ(std::to_string(body.size()),
  11585. res->get_header_value("Content-Length"))
  11586. << path;
  11587. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11588. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11589. };
  11590. expect_body("/file-then-body", "body", "text/plain");
  11591. expect_body("/body-then-file", "test.html", "text/html");
  11592. expect_body("/body-then-provider", "abc", "text/x-provider");
  11593. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11594. expect_body("/provider-then-file", "test.html", "text/x-file");
  11595. expect_body("/file-then-header", "test.html", "text/x-handler");
  11596. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11597. expect_body("/file-then-direct-body", "direct", "text/plain");
  11598. // Ranges are checked against the body, not the dropped provider.
  11599. {
  11600. auto res = cli.Get("/provider-then-direct-body",
  11601. Headers{{make_range_header({{1, 2}})}});
  11602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11604. EXPECT_EQ("ir", res->body);
  11605. }
  11606. {
  11607. auto res = cli.Get("/file-then-direct-body",
  11608. Headers{{make_range_header({{7, 8}})}});
  11609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11610. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11611. }
  11612. }
  11613. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11614. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11615. const char *path = "./truncated_while_served.txt";
  11616. const size_t size = 32 * 1024 * 1024;
  11617. {
  11618. std::ofstream f(path, std::ios::binary);
  11619. f << std::string(size, 'x');
  11620. }
  11621. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11622. // Over TLS, where the bytes are encrypted in this process rather than
  11623. // copied by send().
  11624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11625. svr.Get("/file", [&](const Request &, Response &res) {
  11626. res.set_file_content(path, "text/plain");
  11627. });
  11628. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11629. auto se = detail::scope_exit([&] {
  11630. svr.stop();
  11631. thread.join();
  11632. ASSERT_FALSE(svr.is_running());
  11633. });
  11634. svr.wait_until_ready();
  11635. // The file shrinks once the first bytes are in, as a rewrite in place
  11636. // would, and reading the mapping past its new end used to raise SIGBUS.
  11637. SSLClient cli(HOST, PORT);
  11638. cli.enable_server_certificate_verification(false);
  11639. size_t received = 0;
  11640. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11641. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11642. received += len;
  11643. return true;
  11644. });
  11645. EXPECT_FALSE(res);
  11646. EXPECT_LT(received, size);
  11647. }
  11648. #endif
  11649. // Forward declaration (see the base64_encode note).
  11650. namespace httplib {
  11651. namespace detail {
  11652. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11653. const std::string &content_type,
  11654. EncodingType encoding);
  11655. } // namespace detail
  11656. } // namespace httplib
  11657. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11658. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11659. ASSERT_TRUE(mm->is_open());
  11660. Response res;
  11661. detail::set_file_content_provider(res, mm, "text/html",
  11662. detail::EncodingType::None);
  11663. std::string out;
  11664. DataSink sink;
  11665. sink.write = [&](const char *d, size_t l) {
  11666. out.append(d, l);
  11667. return true;
  11668. };
  11669. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11670. EXPECT_EQ("test.html", out);
  11671. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11672. EXPECT_EQ("test.html", out);
  11673. }
  11674. TEST(LongPollingTest, ClientCloseDetection) {
  11675. Server svr;
  11676. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11677. res.set_chunked_content_provider(
  11678. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11679. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11680. sink.os << "hello";
  11681. auto count = 10;
  11682. while (count > 0 && sink.is_writable()) {
  11683. this_thread::sleep_for(chrono::milliseconds(10));
  11684. count--;
  11685. }
  11686. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11687. return true;
  11688. });
  11689. });
  11690. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11691. auto se = detail::scope_exit([&] {
  11692. svr.stop();
  11693. listen_thread.join();
  11694. ASSERT_FALSE(svr.is_running());
  11695. });
  11696. svr.wait_until_ready();
  11697. Client cli("localhost", PORT);
  11698. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11699. EXPECT_EQ("hello", string(data, data_length));
  11700. return false; // close the socket immediately.
  11701. });
  11702. ASSERT_FALSE(res);
  11703. }
  11704. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11705. Server svr;
  11706. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11707. res.set_chunked_content_provider(
  11708. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11709. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11710. sink.os << "hello";
  11711. EXPECT_TRUE(sink.os.good());
  11712. // Wait for the client to close the connection
  11713. auto count = 10;
  11714. while (count > 0 && sink.is_writable()) {
  11715. this_thread::sleep_for(chrono::milliseconds(10));
  11716. count--;
  11717. }
  11718. // After client disconnect, write repeatedly until the socket
  11719. // write actually fails (small writes may be absorbed by the
  11720. // kernel buffer)
  11721. std::string chunk(1024, 'x');
  11722. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11723. sink.os << chunk;
  11724. }
  11725. EXPECT_TRUE(sink.os.fail());
  11726. return true;
  11727. });
  11728. });
  11729. auto port = svr.bind_to_any_port("localhost");
  11730. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11731. auto se = detail::scope_exit([&] {
  11732. svr.stop();
  11733. listen_thread.join();
  11734. ASSERT_FALSE(svr.is_running());
  11735. });
  11736. svr.wait_until_ready();
  11737. Client cli("localhost", port);
  11738. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11739. EXPECT_EQ("hello", string(data, data_length));
  11740. return false; // close the socket immediately.
  11741. });
  11742. ASSERT_FALSE(res);
  11743. }
  11744. TEST(GetWithParametersTest, GetWithParameters) {
  11745. Server svr;
  11746. svr.Get("/", [&](const Request &req, Response &) {
  11747. EXPECT_EQ("world", req.get_param_value("hello"));
  11748. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11749. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11750. });
  11751. svr.Get("/params", [&](const Request &req, Response &) {
  11752. EXPECT_EQ("world", req.get_param_value("hello"));
  11753. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11754. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11755. });
  11756. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11757. EXPECT_EQ("resource-id", req.matches[1]);
  11758. EXPECT_EQ("foo", req.get_param_value("param1"));
  11759. EXPECT_EQ("bar", req.get_param_value("param2"));
  11760. });
  11761. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11762. EXPECT_EQ("user-id", req.path_params.at("id"));
  11763. EXPECT_EQ("foo", req.get_param_value("param1"));
  11764. EXPECT_EQ("bar", req.get_param_value("param2"));
  11765. });
  11766. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11767. auto se = detail::scope_exit([&] {
  11768. svr.stop();
  11769. listen_thread.join();
  11770. ASSERT_FALSE(svr.is_running());
  11771. });
  11772. svr.wait_until_ready();
  11773. {
  11774. Client cli(HOST, PORT);
  11775. Params params;
  11776. params.emplace("hello", "world");
  11777. params.emplace("hello2", "world2");
  11778. params.emplace("hello3", "world3");
  11779. auto res = cli.Get("/", params, Headers{});
  11780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11781. EXPECT_EQ(StatusCode::OK_200, res->status);
  11782. }
  11783. {
  11784. Client cli(HOST, PORT);
  11785. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11787. EXPECT_EQ(StatusCode::OK_200, res->status);
  11788. }
  11789. {
  11790. Client cli(HOST, PORT);
  11791. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11793. EXPECT_EQ(StatusCode::OK_200, res->status);
  11794. }
  11795. {
  11796. Client cli(HOST, PORT);
  11797. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11799. EXPECT_EQ(StatusCode::OK_200, res->status);
  11800. }
  11801. }
  11802. TEST(GetWithParametersTest, GetWithParameters2) {
  11803. Server svr;
  11804. svr.Get("/", [&](const Request &req, Response &res) {
  11805. auto text = req.get_param_value("hello");
  11806. res.set_content(text, "text/plain");
  11807. });
  11808. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11809. auto se = detail::scope_exit([&] {
  11810. svr.stop();
  11811. listen_thread.join();
  11812. ASSERT_FALSE(svr.is_running());
  11813. });
  11814. svr.wait_until_ready();
  11815. Client cli("localhost", PORT);
  11816. Params params;
  11817. params.emplace("hello", "world");
  11818. std::string body;
  11819. auto res = cli.Get("/", params, Headers{},
  11820. [&](const char *data, size_t data_length) {
  11821. body.append(data, data_length);
  11822. return true;
  11823. });
  11824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11825. EXPECT_EQ(StatusCode::OK_200, res->status);
  11826. EXPECT_EQ("world", body);
  11827. }
  11828. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11829. Server svr;
  11830. svr.Get("/search", [&](const Request &req, Response &res) {
  11831. auto q = req.get_param_value("q");
  11832. res.set_content(q, "text/plain");
  11833. });
  11834. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11835. auto se = detail::scope_exit([&] {
  11836. svr.stop();
  11837. listen_thread.join();
  11838. ASSERT_FALSE(svr.is_running());
  11839. });
  11840. svr.wait_until_ready();
  11841. Client cli("localhost", PORT);
  11842. // Verify that Get(path, params) works without requiring Headers argument
  11843. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11845. EXPECT_EQ(StatusCode::OK_200, res->status);
  11846. EXPECT_EQ("cpp-httplib", res->body);
  11847. }
  11848. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11849. auto host = "httpbingo.org";
  11850. auto path = std::string{"/range/32"};
  11851. #ifdef CPPHTTPLIB_SSL_ENABLED
  11852. SSLClient cli(host);
  11853. #else
  11854. Client cli(host);
  11855. #endif
  11856. cli.set_default_headers({make_range_header({{1, 10}})});
  11857. cli.set_connection_timeout(5);
  11858. {
  11859. auto res = cli.Get(path);
  11860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11861. EXPECT_EQ("bcdefghijk", res->body);
  11862. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11863. }
  11864. {
  11865. auto res = cli.Get(path);
  11866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11867. EXPECT_EQ("bcdefghijk", res->body);
  11868. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11869. }
  11870. }
  11871. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11872. Server svr;
  11873. svr.set_default_headers({{"Hello", "World"}});
  11874. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11875. res.set_content("ok", "text/plain");
  11876. });
  11877. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11878. auto se = detail::scope_exit([&] {
  11879. svr.stop();
  11880. listen_thread.join();
  11881. ASSERT_FALSE(svr.is_running());
  11882. });
  11883. svr.wait_until_ready();
  11884. Client cli("localhost", PORT);
  11885. auto res = cli.Get("/");
  11886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11887. EXPECT_EQ(StatusCode::OK_200, res->status);
  11888. EXPECT_EQ("ok", res->body);
  11889. EXPECT_EQ("World", res->get_header_value("Hello"));
  11890. }
  11891. #ifdef CPPHTTPLIB_SSL_ENABLED
  11892. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11894. ASSERT_TRUE(svr.is_valid());
  11895. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11896. std::this_thread::sleep_for(std::chrono::seconds(2));
  11897. res.set_content("a", "text/plain");
  11898. });
  11899. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11900. res.set_content("b", "text/plain");
  11901. });
  11902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11903. auto se = detail::scope_exit([&] {
  11904. svr.stop();
  11905. listen_thread.join();
  11906. ASSERT_FALSE(svr.is_running());
  11907. });
  11908. svr.wait_until_ready();
  11909. SSLClient cli("localhost", PORT);
  11910. cli.enable_server_certificate_verification(false);
  11911. cli.set_keep_alive(true);
  11912. cli.set_read_timeout(std::chrono::seconds(1));
  11913. auto resa = cli.Get("/a");
  11914. ASSERT_TRUE(!resa);
  11915. EXPECT_EQ(Error::Read, resa.error());
  11916. auto resb = cli.Get("/b");
  11917. ASSERT_TRUE(resb);
  11918. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11919. EXPECT_EQ("b", resb->body);
  11920. }
  11921. // Closing an idle keep-alive connection sends close_notify and returns. The
  11922. // server must not wait for the client's close_notify: an idle client never
  11923. // sends one, so the worker would be held until the read timeout expires, and
  11924. // stop() would wait for it.
  11925. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11927. ASSERT_TRUE(svr.is_valid());
  11928. svr.set_keep_alive_timeout(1);
  11929. svr.set_read_timeout(10, 0);
  11930. svr.Get("/", [](const Request &, Response &res) {
  11931. res.set_content("ok", "text/plain");
  11932. });
  11933. auto port = svr.bind_to_any_port(HOST);
  11934. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11935. auto se = detail::scope_exit([&] {
  11936. if (listen_thread.joinable()) {
  11937. svr.stop();
  11938. listen_thread.join();
  11939. }
  11940. });
  11941. svr.wait_until_ready();
  11942. SSLClient cli(HOST, port);
  11943. cli.enable_server_certificate_verification(false);
  11944. cli.set_keep_alive(true);
  11945. auto res = cli.Get("/");
  11946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11947. EXPECT_EQ(StatusCode::OK_200, res->status);
  11948. // Stay idle past the keep-alive timeout so the server closes the connection.
  11949. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11950. auto start = std::chrono::steady_clock::now();
  11951. svr.stop();
  11952. listen_thread.join();
  11953. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11954. std::chrono::steady_clock::now() - start)
  11955. .count();
  11956. EXPECT_LT(elapsed, 3000);
  11957. }
  11958. #endif
  11959. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11960. protected:
  11961. ServerTestWithAI_PASSIVE()
  11962. : cli_(HOST, PORT)
  11963. #ifdef CPPHTTPLIB_SSL_ENABLED
  11964. ,
  11965. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11966. #endif
  11967. {
  11968. #ifdef CPPHTTPLIB_SSL_ENABLED
  11969. cli_.enable_server_certificate_verification(false);
  11970. #endif
  11971. }
  11972. virtual void SetUp() {
  11973. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11974. res.set_content("Hello World!", "text/plain");
  11975. });
  11976. t_ = thread(
  11977. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11978. svr_.wait_until_ready();
  11979. }
  11980. virtual void TearDown() {
  11981. svr_.stop();
  11982. t_.join();
  11983. }
  11984. #ifdef CPPHTTPLIB_SSL_ENABLED
  11985. SSLClient cli_;
  11986. SSLServer svr_;
  11987. #else
  11988. Client cli_;
  11989. Server svr_;
  11990. #endif
  11991. thread t_;
  11992. };
  11993. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11994. auto res = cli_.Get("/hi");
  11995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11996. EXPECT_EQ(StatusCode::OK_200, res->status);
  11997. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11998. EXPECT_EQ("Hello World!", res->body);
  11999. }
  12000. class ServerUpDownTest : public ::testing::Test {
  12001. protected:
  12002. ServerUpDownTest() : cli_(HOST, PORT) {}
  12003. virtual void SetUp() {
  12004. t_ = thread([&]() {
  12005. svr_.bind_to_any_port(HOST);
  12006. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12007. ASSERT_TRUE(svr_.listen_after_bind());
  12008. });
  12009. svr_.wait_until_ready();
  12010. }
  12011. virtual void TearDown() {
  12012. svr_.stop();
  12013. t_.join();
  12014. }
  12015. Client cli_;
  12016. Server svr_;
  12017. thread t_;
  12018. };
  12019. TEST_F(ServerUpDownTest, QuickStartStop) {
  12020. // Should not crash, especially when run with
  12021. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12022. }
  12023. class PayloadMaxLengthTest : public ::testing::Test {
  12024. protected:
  12025. PayloadMaxLengthTest()
  12026. : cli_(HOST, PORT)
  12027. #ifdef CPPHTTPLIB_SSL_ENABLED
  12028. ,
  12029. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12030. #endif
  12031. {
  12032. #ifdef CPPHTTPLIB_SSL_ENABLED
  12033. cli_.enable_server_certificate_verification(false);
  12034. #endif
  12035. }
  12036. virtual void SetUp() {
  12037. svr_.set_payload_max_length(8);
  12038. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12039. res.set_content("test", "text/plain");
  12040. });
  12041. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12042. svr_.wait_until_ready();
  12043. }
  12044. virtual void TearDown() {
  12045. svr_.stop();
  12046. t_.join();
  12047. }
  12048. #ifdef CPPHTTPLIB_SSL_ENABLED
  12049. SSLClient cli_;
  12050. SSLServer svr_;
  12051. #else
  12052. Client cli_;
  12053. Server svr_;
  12054. #endif
  12055. thread t_;
  12056. };
  12057. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12058. auto res = cli_.Post("/test", "123456789", "text/plain");
  12059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12060. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12061. res = cli_.Post("/test", "12345678", "text/plain");
  12062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12063. EXPECT_EQ(StatusCode::OK_200, res->status);
  12064. }
  12065. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12066. // Test chunked encoding with payload exceeding the 8-byte limit
  12067. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12068. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12070. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12071. }
  12072. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12073. // Test chunked encoding with payload within the 8-byte limit
  12074. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12075. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12077. EXPECT_EQ(StatusCode::OK_200, res->status);
  12078. }
  12079. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12080. // Test using send_request to send chunked data exceeding payload limit
  12081. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12082. "Host: " +
  12083. std::string(HOST) + ":" + std::to_string(PORT) +
  12084. "\r\n"
  12085. "Transfer-Encoding: chunked\r\n"
  12086. "Connection: close\r\n"
  12087. "\r\n"
  12088. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12089. "0123456789\r\n"
  12090. "0\r\n" // End chunk
  12091. "\r\n";
  12092. std::string response;
  12093. bool result = send_request(1, chunked_request, &response);
  12094. if (!result) {
  12095. // If send_request fails, it might be because the server closed the
  12096. // connection due to payload limit enforcement, which is acceptable
  12097. SUCCEED()
  12098. << "Server rejected oversized chunked request (connection closed)";
  12099. } else {
  12100. // If we got a response, check if it's an error response or connection was
  12101. // closed early Short response length indicates connection was closed due to
  12102. // payload limit
  12103. if (response.length() <= 10) {
  12104. SUCCEED() << "Server closed connection for oversized chunked request";
  12105. } else {
  12106. // Check for error status codes
  12107. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12108. response.find("Payload Too Large") != std::string::npos ||
  12109. response.find("400") != std::string::npos);
  12110. }
  12111. }
  12112. }
  12113. class LargePayloadMaxLengthTest : public ::testing::Test {
  12114. protected:
  12115. LargePayloadMaxLengthTest()
  12116. : cli_(HOST, PORT)
  12117. #ifdef CPPHTTPLIB_SSL_ENABLED
  12118. ,
  12119. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12120. #endif
  12121. {
  12122. #ifdef CPPHTTPLIB_SSL_ENABLED
  12123. cli_.enable_server_certificate_verification(false);
  12124. #endif
  12125. }
  12126. virtual void SetUp() {
  12127. // Set 10MB payload limit
  12128. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12129. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12130. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12131. res.set_content("Large payload test", "text/plain");
  12132. });
  12133. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12134. svr_.wait_until_ready();
  12135. }
  12136. virtual void TearDown() {
  12137. svr_.stop();
  12138. t_.join();
  12139. }
  12140. #ifdef CPPHTTPLIB_SSL_ENABLED
  12141. SSLClient cli_;
  12142. SSLServer svr_;
  12143. #else
  12144. Client cli_;
  12145. Server svr_;
  12146. #endif
  12147. thread t_;
  12148. };
  12149. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12150. // Test chunked encoding with payload within 10MB limit
  12151. std::string medium_payload(5 * 1024 * 1024,
  12152. 'A'); // 5MB payload, within 10MB limit
  12153. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12155. EXPECT_EQ(StatusCode::OK_200, res->status);
  12156. }
  12157. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12158. // Test chunked encoding with payload exceeding 10MB limit
  12159. std::string large_payload(12 * 1024 * 1024,
  12160. 'B'); // 12MB payload, exceeds 10MB limit
  12161. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12162. // Server may either return 413 or close the connection
  12163. if (res) {
  12164. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12165. } else {
  12166. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12167. }
  12168. }
  12169. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12170. Server svr;
  12171. svr.Get("/", [](const Request &, Response &res) {
  12172. // Claims the most the client accepts, far more than it sends, then drops
  12173. // the connection.
  12174. res.set_content_provider(std::string().max_size(), "text/plain",
  12175. [](size_t, size_t, DataSink &sink) {
  12176. sink.write("abc", 3);
  12177. return false;
  12178. });
  12179. });
  12180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12181. auto se = detail::scope_exit([&] {
  12182. svr.stop();
  12183. thread.join();
  12184. ASSERT_FALSE(svr.is_running());
  12185. });
  12186. svr.wait_until_ready();
  12187. Client cli(HOST, PORT);
  12188. cli.set_payload_max_length(0);
  12189. EXPECT_FALSE(cli.Get("/"));
  12190. }
  12191. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12192. // Stream API does, not as a plain read failure
  12193. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12194. Server svr;
  12195. svr.Get("/big", [](const Request &, Response &res) {
  12196. res.set_content(std::string(100000, 'b'), "text/plain");
  12197. });
  12198. auto port = svr.bind_to_any_port(HOST);
  12199. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12200. auto se = detail::scope_exit([&] {
  12201. svr.stop();
  12202. thread.join();
  12203. });
  12204. svr.wait_until_ready();
  12205. Client cli(HOST, port);
  12206. cli.set_payload_max_length(1000);
  12207. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12208. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12209. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12210. [](const char *, size_t) { return true; });
  12211. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12212. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12213. // Small on the wire, over the limit once decompressed
  12214. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12215. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12216. #endif
  12217. }
  12218. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12219. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12220. // path.
  12221. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12222. Server svr;
  12223. const size_t LIMIT = 64 * 1024; // 64KB
  12224. svr.set_payload_max_length(LIMIT);
  12225. size_t total = 0;
  12226. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12227. const ContentReader &content_reader) {
  12228. content_reader([&](const char * /*data*/, size_t len) {
  12229. total += len;
  12230. return true;
  12231. });
  12232. res.status = 200;
  12233. res.set_content("stream_ok", "text/plain");
  12234. });
  12235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12236. auto se = detail::scope_exit([&] {
  12237. svr.stop();
  12238. thread.join();
  12239. ASSERT_FALSE(svr.is_running());
  12240. });
  12241. svr.wait_until_ready();
  12242. // Prepare 256KB raw data and gzip-compress it
  12243. std::string raw(256 * 1024, 'A');
  12244. std::string gz;
  12245. {
  12246. z_stream zs{};
  12247. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12248. Z_DEFAULT_STRATEGY);
  12249. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12250. zs.avail_in = static_cast<uInt>(raw.size());
  12251. char outbuf[4096];
  12252. int ret;
  12253. do {
  12254. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12255. zs.avail_out = sizeof(outbuf);
  12256. ret = deflate(&zs, Z_FINISH);
  12257. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12258. } while (ret != Z_STREAM_END);
  12259. deflateEnd(&zs);
  12260. }
  12261. Client cli(HOST, PORT);
  12262. cli.set_connection_timeout(std::chrono::seconds(5));
  12263. Headers headers = {{"Content-Encoding", "gzip"}};
  12264. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12265. "application/octet-stream");
  12266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12267. // Server must reject oversized decompressed payloads with 413.
  12268. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12269. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12270. EXPECT_LE(total, LIMIT);
  12271. }
  12272. #endif
  12273. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12274. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12275. // the payload must be passed through untouched instead of being rejected.
  12276. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12277. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12278. Server svr;
  12279. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12280. res.set_content(body, "image/jpeg");
  12281. res.set_header("Content-Encoding", "UTF-8");
  12282. });
  12283. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12284. res.set_content(body, "image/jpeg");
  12285. res.set_header("Content-Encoding", "identity");
  12286. });
  12287. svr.Post("/echo", [](const Request &req, Response &res) {
  12288. res.set_content(req.body, "image/jpeg");
  12289. });
  12290. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12291. auto se = detail::scope_exit([&] {
  12292. svr.stop();
  12293. t.join();
  12294. ASSERT_FALSE(svr.is_running());
  12295. });
  12296. svr.wait_until_ready();
  12297. Client cli(HOST, PORT);
  12298. {
  12299. auto res = cli.Get("/image");
  12300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12301. EXPECT_EQ(StatusCode::OK_200, res->status);
  12302. EXPECT_EQ(body, res->body);
  12303. }
  12304. {
  12305. auto res = cli.Get("/identity");
  12306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12307. EXPECT_EQ(StatusCode::OK_200, res->status);
  12308. EXPECT_EQ(body, res->body);
  12309. }
  12310. {
  12311. // The same applies to a request body reaching the server.
  12312. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12313. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12315. EXPECT_EQ(StatusCode::OK_200, res->status);
  12316. EXPECT_EQ(body, res->body);
  12317. }
  12318. }
  12319. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12320. // gzip-encoded response even when the build has no zlib support.
  12321. static const char GZIPPED_HELLO_WORLD[] = {
  12322. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12323. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12324. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12325. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12326. // A content coding is a whole token, not something the field value merely
  12327. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12328. // as "fibre" look like Brotli, and turned a multi-coding value like
  12329. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12330. // it was never meant to see.
  12331. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12332. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12333. Server svr;
  12334. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12335. res.set_content(body, "image/jpeg");
  12336. res.set_header("Content-Encoding", "fibre");
  12337. });
  12338. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12339. res.set_content(body, "image/jpeg");
  12340. res.set_header("Content-Encoding", "gzip, br");
  12341. });
  12342. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12343. res.set_content(body, "image/jpeg");
  12344. res.set_header("Content-Encoding", "x-zstd-ish");
  12345. });
  12346. auto port = svr.bind_to_any_port(HOST);
  12347. thread t = thread([&]() { svr.listen_after_bind(); });
  12348. auto se = detail::scope_exit([&] {
  12349. svr.stop();
  12350. t.join();
  12351. ASSERT_FALSE(svr.is_running());
  12352. });
  12353. svr.wait_until_ready();
  12354. Client cli(HOST, port);
  12355. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12356. auto res = cli.Get(path);
  12357. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12358. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12359. // Not a coding we recognize, so the payload comes back untouched
  12360. EXPECT_EQ(body, res->body) << path;
  12361. }
  12362. }
  12363. // A content coding cpp-httplib recognizes but was not built with must be
  12364. // reported as such. Handing the still-compressed payload back to the caller
  12365. // would silently corrupt it.
  12366. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12367. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12368. Server svr;
  12369. // "image/jpeg" keeps the server from applying a content coding of its own,
  12370. // so the hand-crafted Content-Encoding below survives.
  12371. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12372. res.set_content(gzipped, "image/jpeg");
  12373. res.set_header("Content-Encoding", "gzip");
  12374. });
  12375. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12376. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12377. res.set_content(gzipped, "image/jpeg");
  12378. res.set_header("Content-Encoding", "GZIP");
  12379. });
  12380. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12381. auto se = detail::scope_exit([&] {
  12382. svr.stop();
  12383. t.join();
  12384. ASSERT_FALSE(svr.is_running());
  12385. });
  12386. svr.wait_until_ready();
  12387. Client cli(HOST, PORT);
  12388. {
  12389. auto res = cli.Get("/gzipped");
  12390. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12392. EXPECT_EQ("Hello World!", res->body);
  12393. #else
  12394. ASSERT_FALSE(res);
  12395. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12396. #endif
  12397. }
  12398. {
  12399. // open_stream() must behave the same way.
  12400. auto handle = cli.open_stream("GET", "/gzipped");
  12401. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12402. ASSERT_TRUE(handle.is_valid());
  12403. std::string received;
  12404. char buf[256];
  12405. ssize_t n;
  12406. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12407. received.append(buf, static_cast<size_t>(n));
  12408. }
  12409. EXPECT_EQ("Hello World!", received);
  12410. #else
  12411. EXPECT_FALSE(handle.is_valid());
  12412. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12413. #endif
  12414. }
  12415. {
  12416. // A differently-cased coding must not be mistaken for an unknown one, or
  12417. // the body would be handed back still compressed.
  12418. auto res = cli.Get("/gzipped-uppercase");
  12419. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12421. EXPECT_EQ("Hello World!", res->body);
  12422. #else
  12423. ASSERT_FALSE(res);
  12424. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12425. #endif
  12426. }
  12427. }
  12428. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12429. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12430. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12431. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12432. // body a second time and appending a second Content-Encoding field line, so
  12433. // clients that decode one coding per listed value handed back raw gzip bytes.
  12434. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12435. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12436. Server svr;
  12437. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12438. // keeps the server from applying a coding of its own.
  12439. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12440. res.set_content(gzipped, "text/plain");
  12441. res.set_header("Content-Encoding", "gzip");
  12442. });
  12443. auto port = svr.bind_to_any_port(HOST);
  12444. thread t = thread([&]() { svr.listen_after_bind(); });
  12445. auto se = detail::scope_exit([&] {
  12446. svr.stop();
  12447. t.join();
  12448. ASSERT_FALSE(svr.is_running());
  12449. });
  12450. svr.wait_until_ready();
  12451. Client cli(HOST, port);
  12452. Headers headers = {{"Accept-Encoding", "gzip"}};
  12453. auto res = cli.Get("/pre-gzipped", headers);
  12454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12455. EXPECT_EQ(StatusCode::OK_200, res->status);
  12456. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12457. EXPECT_EQ("Hello World!", res->body);
  12458. }
  12459. // set_compress(false) sends every handler response as it is, buffered or
  12460. // streamed
  12461. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12462. const std::string text(1000, 'a');
  12463. Server svr;
  12464. svr.set_compress(false);
  12465. svr.Get("/buffered", [&](const Request &, Response &res) {
  12466. res.set_content(text, "text/plain");
  12467. });
  12468. svr.Get("/streamed", [&](const Request &, Response &res) {
  12469. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12470. sink.write(text.data(), text.size());
  12471. sink.done();
  12472. return true;
  12473. });
  12474. });
  12475. auto port = svr.bind_to_any_port(HOST);
  12476. ASSERT_LT(0, port);
  12477. thread t = thread([&] { svr.listen_after_bind(); });
  12478. auto se = detail::scope_exit([&] {
  12479. svr.stop();
  12480. t.join();
  12481. ASSERT_FALSE(svr.is_running());
  12482. });
  12483. svr.wait_until_ready();
  12484. Client cli(HOST, port);
  12485. cli.set_decompress(false);
  12486. for (auto path : {"/buffered", "/streamed"}) {
  12487. SCOPED_TRACE(path);
  12488. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12490. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12491. EXPECT_EQ(text, res->body);
  12492. }
  12493. }
  12494. // A chunked provider settles its coding where the headers are written and
  12495. // reuses it at write time. Both ends of that have to hold: a handler's own
  12496. // Content-Encoding suppresses the coding, and a response without one is still
  12497. // compressed as it always was.
  12498. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12499. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12500. const std::string plain = "Hello World! Hello World! Hello World!";
  12501. Server svr;
  12502. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12503. res.set_header("Content-Encoding", "gzip");
  12504. res.set_chunked_content_provider(
  12505. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12506. sink.write(gzipped.data(), gzipped.size());
  12507. sink.done();
  12508. return true;
  12509. });
  12510. });
  12511. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12512. res.set_chunked_content_provider(
  12513. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12514. sink.write(plain.data(), plain.size());
  12515. sink.done();
  12516. return true;
  12517. });
  12518. });
  12519. auto port = svr.bind_to_any_port(HOST);
  12520. thread t = thread([&]() { svr.listen_after_bind(); });
  12521. auto se = detail::scope_exit([&] {
  12522. svr.stop();
  12523. t.join();
  12524. ASSERT_FALSE(svr.is_running());
  12525. });
  12526. svr.wait_until_ready();
  12527. Client cli(HOST, port);
  12528. Headers headers = {{"Accept-Encoding", "gzip"}};
  12529. {
  12530. auto res = cli.Get("/pre-gzipped", headers);
  12531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12532. EXPECT_EQ(StatusCode::OK_200, res->status);
  12533. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12534. EXPECT_EQ("Hello World!", res->body);
  12535. }
  12536. {
  12537. auto res = cli.Get("/negotiated", headers);
  12538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12539. EXPECT_EQ(StatusCode::OK_200, res->status);
  12540. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12541. EXPECT_EQ(plain, res->body);
  12542. }
  12543. }
  12544. #endif
  12545. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12546. // the same message as the comma-joined one, so both have to be read the same
  12547. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12548. // single gzip coding, and a body the sender says was encoded twice was handed
  12549. // back after one pass, still compressed but presented as decoded.
  12550. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12551. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12552. Server svr;
  12553. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12554. res.set_content(body, "image/jpeg");
  12555. res.headers.emplace("Content-Encoding", "gzip");
  12556. res.headers.emplace("Content-Encoding", "gzip");
  12557. });
  12558. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12559. res.set_content(body, "image/jpeg");
  12560. res.set_header("Content-Encoding", "gzip, gzip");
  12561. });
  12562. auto port = svr.bind_to_any_port(HOST);
  12563. thread t = thread([&]() { svr.listen_after_bind(); });
  12564. auto se = detail::scope_exit([&] {
  12565. svr.stop();
  12566. t.join();
  12567. ASSERT_FALSE(svr.is_running());
  12568. });
  12569. svr.wait_until_ready();
  12570. Client cli(HOST, port);
  12571. // Two codings is not something cpp-httplib decodes, so both representations
  12572. // take the pass-through path rather than one of them being gunzipped once.
  12573. for (const char *path : {"/split", "/joined"}) {
  12574. auto res = cli.Get(path);
  12575. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12576. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12577. EXPECT_EQ(body, res->body) << path;
  12578. }
  12579. }
  12580. // Regression test for DoS vulnerability: a malicious server sending a response
  12581. // without Content-Length header must not cause unbounded memory consumption on
  12582. // the client side. The client should stop reading after a reasonable limit,
  12583. // similar to the server-side set_payload_max_length protection.
  12584. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12585. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12586. #ifndef _WIN32
  12587. signal(SIGPIPE, SIG_IGN);
  12588. #endif
  12589. auto server_thread = std::thread([] {
  12590. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12591. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12592. default_socket_options(srv);
  12593. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12594. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12595. sockaddr_in addr{};
  12596. addr.sin_family = AF_INET;
  12597. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12598. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12599. int opt = 1;
  12600. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12601. #ifdef _WIN32
  12602. reinterpret_cast<const char *>(&opt),
  12603. #else
  12604. &opt,
  12605. #endif
  12606. sizeof(opt));
  12607. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12608. ::listen(srv, 1);
  12609. sockaddr_in cli_addr{};
  12610. socklen_t cli_len = sizeof(cli_addr);
  12611. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12612. if (cli != INVALID_SOCKET) {
  12613. char buf[4096];
  12614. ::recv(cli, buf, sizeof(buf), 0);
  12615. // Malicious response: no Content-Length, no chunked encoding
  12616. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12617. "Connection: close\r\n"
  12618. "\r\n";
  12619. ::send(cli,
  12620. #ifdef _WIN32
  12621. static_cast<const char *>(response_header.c_str()),
  12622. static_cast<int>(response_header.size()),
  12623. #else
  12624. response_header.c_str(), response_header.size(),
  12625. #endif
  12626. 0);
  12627. // Send 10MB of data
  12628. std::string chunk(64 * 1024, 'A');
  12629. size_t total_sent = 0;
  12630. while (total_sent < MALICIOUS_DATA_SIZE) {
  12631. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12632. auto sent = ::send(cli,
  12633. #ifdef _WIN32
  12634. static_cast<const char *>(chunk.c_str()),
  12635. static_cast<int>(to_send),
  12636. #else
  12637. chunk.c_str(), to_send,
  12638. #endif
  12639. 0);
  12640. if (sent <= 0) break;
  12641. total_sent += static_cast<size_t>(sent);
  12642. }
  12643. detail::close_socket(cli);
  12644. }
  12645. detail::close_socket(srv);
  12646. });
  12647. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12648. size_t total_read = 0;
  12649. {
  12650. Client cli("127.0.0.1", PORT + 2);
  12651. cli.set_read_timeout(5, 0);
  12652. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12653. auto stream = cli.open_stream("GET", "/malicious");
  12654. ASSERT_TRUE(stream.is_valid());
  12655. char buffer[64 * 1024];
  12656. ssize_t n;
  12657. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12658. total_read += static_cast<size_t>(n);
  12659. }
  12660. } // StreamHandle and Client destroyed here, closing the socket
  12661. server_thread.join();
  12662. // With set_payload_max_length, the client must stop reading before consuming
  12663. // all 10MB. The read loop should be cut off at or near the configured limit.
  12664. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12665. << "Client read " << total_read << " bytes, exceeding the configured "
  12666. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12667. }
  12668. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12669. // the entire response body without truncation.
  12670. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12671. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12672. #ifndef _WIN32
  12673. signal(SIGPIPE, SIG_IGN);
  12674. #endif
  12675. auto server_thread = std::thread([] {
  12676. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12677. default_socket_options(srv);
  12678. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12679. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12680. sockaddr_in addr{};
  12681. addr.sin_family = AF_INET;
  12682. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12683. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12684. int opt = 1;
  12685. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12686. #ifdef _WIN32
  12687. reinterpret_cast<const char *>(&opt),
  12688. #else
  12689. &opt,
  12690. #endif
  12691. sizeof(opt));
  12692. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12693. ::listen(srv, 1);
  12694. sockaddr_in cli_addr{};
  12695. socklen_t cli_len = sizeof(cli_addr);
  12696. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12697. if (cli != INVALID_SOCKET) {
  12698. char buf[4096];
  12699. ::recv(cli, buf, sizeof(buf), 0);
  12700. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12701. "Connection: close\r\n"
  12702. "\r\n";
  12703. ::send(cli,
  12704. #ifdef _WIN32
  12705. static_cast<const char *>(response_header.c_str()),
  12706. static_cast<int>(response_header.size()),
  12707. #else
  12708. response_header.c_str(), response_header.size(),
  12709. #endif
  12710. 0);
  12711. std::string chunk(64 * 1024, 'A');
  12712. size_t total_sent = 0;
  12713. while (total_sent < DATA_SIZE) {
  12714. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12715. auto sent = ::send(cli,
  12716. #ifdef _WIN32
  12717. static_cast<const char *>(chunk.c_str()),
  12718. static_cast<int>(to_send),
  12719. #else
  12720. chunk.c_str(), to_send,
  12721. #endif
  12722. 0);
  12723. if (sent <= 0) break;
  12724. total_sent += static_cast<size_t>(sent);
  12725. }
  12726. #ifdef _WIN32
  12727. ::shutdown(cli, SD_SEND);
  12728. #else
  12729. ::shutdown(cli, SHUT_WR);
  12730. #endif
  12731. // Drain until the client closes its end, ensuring all data is delivered
  12732. char drain[1024];
  12733. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12734. detail::close_socket(cli);
  12735. }
  12736. detail::close_socket(srv);
  12737. });
  12738. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12739. size_t total_read = 0;
  12740. {
  12741. Client cli("127.0.0.1", PORT + 2);
  12742. cli.set_read_timeout(5, 0);
  12743. cli.set_payload_max_length(0); // 0 means no limit
  12744. auto stream = cli.open_stream("GET", "/data");
  12745. ASSERT_TRUE(stream.is_valid());
  12746. char buffer[64 * 1024];
  12747. ssize_t n;
  12748. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12749. total_read += static_cast<size_t>(n);
  12750. }
  12751. }
  12752. server_thread.join();
  12753. EXPECT_EQ(total_read, DATA_SIZE)
  12754. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12755. << " bytes without truncation, but only read " << total_read << " bytes.";
  12756. }
  12757. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12758. // enormous Content-Length must not cause the client to pre-allocate a huge
  12759. // response body buffer. The reservation is capped at payload_max_length_, and
  12760. // the read itself fails when the body exceeds the limit.
  12761. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12762. #ifndef _WIN32
  12763. signal(SIGPIPE, SIG_IGN);
  12764. #endif
  12765. auto server_thread = std::thread([] {
  12766. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12767. default_socket_options(srv);
  12768. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12769. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12770. sockaddr_in addr{};
  12771. addr.sin_family = AF_INET;
  12772. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12773. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12774. int opt = 1;
  12775. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12776. #ifdef _WIN32
  12777. reinterpret_cast<const char *>(&opt),
  12778. #else
  12779. &opt,
  12780. #endif
  12781. sizeof(opt));
  12782. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12783. ::listen(srv, 1);
  12784. sockaddr_in cli_addr{};
  12785. socklen_t cli_len = sizeof(cli_addr);
  12786. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12787. if (cli != INVALID_SOCKET) {
  12788. char buf[4096];
  12789. ::recv(cli, buf, sizeof(buf), 0);
  12790. // Malicious response: claim a 20GB body but send only a tiny payload.
  12791. std::string response = "HTTP/1.1 200 OK\r\n"
  12792. "Content-Length: 20000000000\r\n"
  12793. "\r\n"
  12794. "abc";
  12795. ::send(cli,
  12796. #ifdef _WIN32
  12797. static_cast<const char *>(response.c_str()),
  12798. static_cast<int>(response.size()),
  12799. #else
  12800. response.c_str(), response.size(),
  12801. #endif
  12802. 0);
  12803. detail::close_socket(cli);
  12804. }
  12805. detail::close_socket(srv);
  12806. });
  12807. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12808. {
  12809. Client cli("127.0.0.1", PORT + 2);
  12810. cli.set_read_timeout(5, 0);
  12811. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12812. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12813. // (server claims more bytes than payload_max_length permits), but it must
  12814. // not exhaust memory before getting there.
  12815. auto res = cli.Get("/malicious");
  12816. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12817. }
  12818. server_thread.join();
  12819. }
  12820. // Verify that content_receiver bypasses the default payload_max_length,
  12821. // allowing streaming downloads larger than 100MB without requiring an explicit
  12822. // set_payload_max_length call.
  12823. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12824. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12825. #ifndef _WIN32
  12826. signal(SIGPIPE, SIG_IGN);
  12827. #endif
  12828. auto server_thread = std::thread([] {
  12829. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12830. default_socket_options(srv);
  12831. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12832. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12833. sockaddr_in addr{};
  12834. addr.sin_family = AF_INET;
  12835. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12836. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12837. int opt = 1;
  12838. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12839. #ifdef _WIN32
  12840. reinterpret_cast<const char *>(&opt),
  12841. #else
  12842. &opt,
  12843. #endif
  12844. sizeof(opt));
  12845. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12846. ::listen(srv, 1);
  12847. sockaddr_in cli_addr{};
  12848. socklen_t cli_len = sizeof(cli_addr);
  12849. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12850. if (cli != INVALID_SOCKET) {
  12851. char buf[4096];
  12852. ::recv(cli, buf, sizeof(buf), 0);
  12853. // Response with Content-Length larger than default 100MB limit
  12854. auto content_length = std::to_string(DATA_SIZE);
  12855. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12856. "Content-Length: " +
  12857. content_length +
  12858. "\r\n"
  12859. "Connection: close\r\n"
  12860. "\r\n";
  12861. ::send(cli,
  12862. #ifdef _WIN32
  12863. static_cast<const char *>(response_header.c_str()),
  12864. static_cast<int>(response_header.size()),
  12865. #else
  12866. response_header.c_str(), response_header.size(),
  12867. #endif
  12868. 0);
  12869. std::string chunk(64 * 1024, 'A');
  12870. size_t total_sent = 0;
  12871. while (total_sent < DATA_SIZE) {
  12872. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12873. auto sent = ::send(cli,
  12874. #ifdef _WIN32
  12875. static_cast<const char *>(chunk.c_str()),
  12876. static_cast<int>(to_send),
  12877. #else
  12878. chunk.c_str(), to_send,
  12879. #endif
  12880. 0);
  12881. if (sent <= 0) break;
  12882. total_sent += static_cast<size_t>(sent);
  12883. }
  12884. detail::close_socket(cli);
  12885. }
  12886. detail::close_socket(srv);
  12887. });
  12888. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12889. size_t total_received = 0;
  12890. {
  12891. Client cli("127.0.0.1", PORT + 2);
  12892. cli.set_read_timeout(10, 0);
  12893. // Do NOT call set_payload_max_length — use the default 100MB limit
  12894. auto res =
  12895. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12896. total_received += data_length;
  12897. return true;
  12898. });
  12899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12900. EXPECT_EQ(StatusCode::OK_200, res->status);
  12901. }
  12902. server_thread.join();
  12903. EXPECT_EQ(total_received, DATA_SIZE)
  12904. << "With content_receiver, the client should read all " << DATA_SIZE
  12905. << " bytes despite the default 100MB payload_max_length, but only read "
  12906. << total_received << " bytes.";
  12907. }
  12908. // Verify that an explicit set_payload_max_length smaller than the response is
  12909. // enforced even when a content_receiver is used.
  12910. TEST(ClientVulnerabilityTest,
  12911. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12912. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12913. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12914. #ifndef _WIN32
  12915. signal(SIGPIPE, SIG_IGN);
  12916. #endif
  12917. auto server_thread = std::thread([] {
  12918. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12919. default_socket_options(srv);
  12920. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12921. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12922. sockaddr_in addr{};
  12923. addr.sin_family = AF_INET;
  12924. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12925. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12926. int opt = 1;
  12927. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12928. #ifdef _WIN32
  12929. reinterpret_cast<const char *>(&opt),
  12930. #else
  12931. &opt,
  12932. #endif
  12933. sizeof(opt));
  12934. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12935. ::listen(srv, 1);
  12936. sockaddr_in cli_addr{};
  12937. socklen_t cli_len = sizeof(cli_addr);
  12938. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12939. if (cli != INVALID_SOCKET) {
  12940. char buf[4096];
  12941. ::recv(cli, buf, sizeof(buf), 0);
  12942. auto content_length = std::to_string(DATA_SIZE);
  12943. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12944. "Content-Length: " +
  12945. content_length +
  12946. "\r\n"
  12947. "Connection: close\r\n"
  12948. "\r\n";
  12949. ::send(cli,
  12950. #ifdef _WIN32
  12951. static_cast<const char *>(response_header.c_str()),
  12952. static_cast<int>(response_header.size()),
  12953. #else
  12954. response_header.c_str(), response_header.size(),
  12955. #endif
  12956. 0);
  12957. std::string chunk(64 * 1024, 'A');
  12958. size_t total_sent = 0;
  12959. while (total_sent < DATA_SIZE) {
  12960. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12961. auto sent = ::send(cli,
  12962. #ifdef _WIN32
  12963. static_cast<const char *>(chunk.c_str()),
  12964. static_cast<int>(to_send),
  12965. #else
  12966. chunk.c_str(), to_send,
  12967. #endif
  12968. 0);
  12969. if (sent <= 0) break;
  12970. total_sent += static_cast<size_t>(sent);
  12971. }
  12972. detail::close_socket(cli);
  12973. }
  12974. detail::close_socket(srv);
  12975. });
  12976. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12977. size_t total_received = 0;
  12978. {
  12979. Client cli("127.0.0.1", PORT + 2);
  12980. cli.set_read_timeout(10, 0);
  12981. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12982. auto res =
  12983. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12984. total_received += data_length;
  12985. return true;
  12986. });
  12987. // Should fail because 200MB exceeds the explicit 150MB limit
  12988. EXPECT_FALSE(res);
  12989. }
  12990. server_thread.join();
  12991. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12992. << "Client with content_receiver should respect the explicit "
  12993. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12994. << total_received << " bytes.";
  12995. }
  12996. // Verify that an explicit set_payload_max_length larger than the response
  12997. // allows the content_receiver to read all data successfully.
  12998. TEST(ClientVulnerabilityTest,
  12999. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13000. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13001. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13002. #ifndef _WIN32
  13003. signal(SIGPIPE, SIG_IGN);
  13004. #endif
  13005. auto server_thread = std::thread([] {
  13006. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13007. default_socket_options(srv);
  13008. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13009. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13010. sockaddr_in addr{};
  13011. addr.sin_family = AF_INET;
  13012. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13013. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13014. int opt = 1;
  13015. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13016. #ifdef _WIN32
  13017. reinterpret_cast<const char *>(&opt),
  13018. #else
  13019. &opt,
  13020. #endif
  13021. sizeof(opt));
  13022. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13023. ::listen(srv, 1);
  13024. sockaddr_in cli_addr{};
  13025. socklen_t cli_len = sizeof(cli_addr);
  13026. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13027. if (cli != INVALID_SOCKET) {
  13028. char buf[4096];
  13029. ::recv(cli, buf, sizeof(buf), 0);
  13030. auto content_length = std::to_string(DATA_SIZE);
  13031. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13032. "Content-Length: " +
  13033. content_length +
  13034. "\r\n"
  13035. "Connection: close\r\n"
  13036. "\r\n";
  13037. ::send(cli,
  13038. #ifdef _WIN32
  13039. static_cast<const char *>(response_header.c_str()),
  13040. static_cast<int>(response_header.size()),
  13041. #else
  13042. response_header.c_str(), response_header.size(),
  13043. #endif
  13044. 0);
  13045. std::string chunk(64 * 1024, 'A');
  13046. size_t total_sent = 0;
  13047. while (total_sent < DATA_SIZE) {
  13048. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13049. auto sent = ::send(cli,
  13050. #ifdef _WIN32
  13051. static_cast<const char *>(chunk.c_str()),
  13052. static_cast<int>(to_send),
  13053. #else
  13054. chunk.c_str(), to_send,
  13055. #endif
  13056. 0);
  13057. if (sent <= 0) break;
  13058. total_sent += static_cast<size_t>(sent);
  13059. }
  13060. #ifdef _WIN32
  13061. ::shutdown(cli, SD_SEND);
  13062. #else
  13063. ::shutdown(cli, SHUT_WR);
  13064. #endif
  13065. char drain[1024];
  13066. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13067. detail::close_socket(cli);
  13068. }
  13069. detail::close_socket(srv);
  13070. });
  13071. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13072. size_t total_received = 0;
  13073. {
  13074. Client cli("127.0.0.1", PORT + 2);
  13075. cli.set_read_timeout(10, 0);
  13076. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13077. auto res =
  13078. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13079. total_received += data_length;
  13080. return true;
  13081. });
  13082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13083. EXPECT_EQ(StatusCode::OK_200, res->status);
  13084. }
  13085. server_thread.join();
  13086. EXPECT_EQ(total_received, DATA_SIZE)
  13087. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13088. << " bytes (larger than " << DATA_SIZE
  13089. << " bytes response), content_receiver should read all data, but only "
  13090. "read "
  13091. << total_received << " bytes.";
  13092. }
  13093. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13094. // Regression test for "zip bomb" attack on the client side: a malicious server
  13095. // sends a small gzip-compressed response that decompresses to a huge payload.
  13096. // The client must enforce payload_max_length on the decompressed size.
  13097. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13098. constexpr size_t DECOMPRESSED_SIZE =
  13099. 10 * 1024 * 1024; // 10MB after decompression
  13100. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13101. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13102. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13103. std::string compressed;
  13104. {
  13105. httplib::detail::gzip_compressor compressor;
  13106. bool ok =
  13107. compressor.compress(uncompressed.data(), uncompressed.size(),
  13108. /*last=*/true, [&](const char *buf, size_t len) {
  13109. compressed.append(buf, len);
  13110. return true;
  13111. });
  13112. ASSERT_TRUE(ok);
  13113. }
  13114. // Sanity: compressed data should be much smaller than the decompressed size
  13115. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13116. #ifndef _WIN32
  13117. signal(SIGPIPE, SIG_IGN);
  13118. #endif
  13119. // Set up the listening socket in the main thread so the server is guaranteed
  13120. // to be ready before the client connects (eliminates race condition).
  13121. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13122. default_socket_options(srv);
  13123. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13124. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13125. sockaddr_in addr{};
  13126. addr.sin_family = AF_INET;
  13127. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13128. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13129. int opt = 1;
  13130. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13131. #ifdef _WIN32
  13132. reinterpret_cast<const char *>(&opt),
  13133. #else
  13134. &opt,
  13135. #endif
  13136. sizeof(opt));
  13137. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13138. ASSERT_EQ(0, ::listen(srv, 1));
  13139. auto server_thread = std::thread([&compressed, srv] {
  13140. sockaddr_in cli_addr{};
  13141. socklen_t cli_len = sizeof(cli_addr);
  13142. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13143. if (cli != INVALID_SOCKET) {
  13144. // Read the full HTTP request (until \r\n\r\n)
  13145. char buf[4096];
  13146. size_t total = 0;
  13147. while (total < sizeof(buf)) {
  13148. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13149. if (n <= 0) break;
  13150. total += static_cast<size_t>(n);
  13151. // Check for end of headers
  13152. if (total >= 4) {
  13153. std::string req(buf, total);
  13154. if (req.find("\r\n\r\n") != std::string::npos) break;
  13155. }
  13156. }
  13157. // Malicious response: gzip-compressed body, no Content-Length
  13158. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13159. "Content-Encoding: gzip\r\n"
  13160. "Connection: close\r\n"
  13161. "\r\n";
  13162. ::send(cli,
  13163. #ifdef _WIN32
  13164. static_cast<const char *>(response_header.c_str()),
  13165. static_cast<int>(response_header.size()),
  13166. #else
  13167. response_header.c_str(), response_header.size(),
  13168. #endif
  13169. 0);
  13170. // Send the compressed payload (small on the wire, huge when decompressed)
  13171. size_t total_sent = 0;
  13172. while (total_sent < compressed.size()) {
  13173. auto to_send = std::min(compressed.size() - total_sent,
  13174. static_cast<size_t>(64 * 1024));
  13175. auto sent =
  13176. ::send(cli,
  13177. #ifdef _WIN32
  13178. static_cast<const char *>(compressed.c_str() + total_sent),
  13179. static_cast<int>(to_send),
  13180. #else
  13181. compressed.c_str() + total_sent, to_send,
  13182. #endif
  13183. 0);
  13184. if (sent <= 0) break;
  13185. total_sent += static_cast<size_t>(sent);
  13186. }
  13187. detail::close_socket(cli);
  13188. }
  13189. });
  13190. auto se = detail::scope_exit([&] {
  13191. detail::close_socket(srv);
  13192. server_thread.join();
  13193. });
  13194. size_t total_decompressed = 0;
  13195. {
  13196. Client cli("127.0.0.1", PORT + 3);
  13197. cli.set_read_timeout(5, 0);
  13198. cli.set_decompress(true);
  13199. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13200. auto stream = cli.open_stream("GET", "/zipbomb");
  13201. ASSERT_TRUE(stream.is_valid());
  13202. char buffer[64 * 1024];
  13203. ssize_t n;
  13204. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13205. total_decompressed += static_cast<size_t>(n);
  13206. }
  13207. }
  13208. // The decompressed size must be capped by payload_max_length. Without
  13209. // protection, the client would decompress the full 10MB from a tiny
  13210. // compressed payload, enabling a zip bomb DoS attack.
  13211. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13212. << "Client decompressed " << total_decompressed
  13213. << " bytes from a gzip response. The decompressed size should be "
  13214. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13215. }
  13216. #endif
  13217. TEST(HostAndPortPropertiesTest, NoSSL) {
  13218. httplib::Client cli("www.google.com", 1234);
  13219. ASSERT_EQ("www.google.com", cli.host());
  13220. ASSERT_EQ(1234, cli.port());
  13221. }
  13222. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13223. httplib::Client cli("www.google.com:1234");
  13224. ASSERT_EQ("www.google.com", cli.host());
  13225. ASSERT_EQ(1234, cli.port());
  13226. }
  13227. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13228. // Port number that overflows int — should not crash, client becomes invalid
  13229. httplib::Client cli("http://www.google.com:99999999999999999999");
  13230. ASSERT_FALSE(cli.is_valid());
  13231. }
  13232. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13233. // Port 99999 exceeds valid range (1-65535) — should not crash
  13234. httplib::Client cli("http://www.google.com:99999");
  13235. ASSERT_FALSE(cli.is_valid());
  13236. auto res = cli.Get("/");
  13237. EXPECT_FALSE(res);
  13238. EXPECT_EQ(Error::Connection, res.error());
  13239. }
  13240. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13241. httplib::Client cli("http://user:pass@localhost:1234");
  13242. ASSERT_FALSE(cli.is_valid());
  13243. EXPECT_FALSE(cli.Get("/"));
  13244. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13245. }
  13246. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13247. httplib::Client cli("http://www.google.com:80abc");
  13248. ASSERT_FALSE(cli.is_valid());
  13249. }
  13250. #ifdef CPPHTTPLIB_SSL_ENABLED
  13251. TEST(HostAndPortPropertiesTest, SSL) {
  13252. httplib::SSLClient cli("www.google.com");
  13253. ASSERT_EQ("www.google.com", cli.host());
  13254. ASSERT_EQ(443, cli.port());
  13255. }
  13256. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13257. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13258. std::string cert;
  13259. read_file(CA_CERT_FILE, cert);
  13260. httplib::SSLClient httplib_client("www.google.com");
  13261. // Load CA store first time
  13262. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13263. // Load CA store second time (update)
  13264. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13265. // Verify client is still valid and can make connections
  13266. httplib_client.enable_server_certificate_verification(true);
  13267. auto res = httplib_client.Get("/");
  13268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13269. // Google may return 200 or 301 depending on various factors
  13270. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13271. res->status == StatusCode::MovedPermanently_301);
  13272. }
  13273. TEST(SSLClientTest, ServerNameIndication_Online) {
  13274. auto host = "httpbingo.org";
  13275. auto path = std::string{"/get"};
  13276. SSLClient cli(host, 443);
  13277. auto res = cli.Get(path);
  13278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13279. ASSERT_EQ(StatusCode::OK_200, res->status);
  13280. }
  13281. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13282. // Use a site that will cause SSL verification failure due to self-signed cert
  13283. SSLClient cli("self-signed.badssl.com", 443);
  13284. cli.enable_server_certificate_verification(true);
  13285. auto res = cli.Get("/");
  13286. ASSERT_TRUE(!res);
  13287. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13288. // Verify backend error is captured for SSLServerVerification
  13289. // This occurs when certificate verification fails
  13290. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13291. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13292. EXPECT_NE(0UL, res.ssl_backend_error());
  13293. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13294. res.ssl_error());
  13295. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13296. #if !defined(_WIN32) || \
  13297. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13298. // On non-Windows or when Windows Schannel is disabled, the error comes
  13299. // from OpenSSL's verification
  13300. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13301. res.ssl_backend_error());
  13302. #endif
  13303. #endif
  13304. }
  13305. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13306. // Use a site where hostname doesn't match the certificate
  13307. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13308. SSLClient cli("wrong.host.badssl.com", 443);
  13309. cli.enable_server_certificate_verification(true);
  13310. cli.enable_server_hostname_verification(true);
  13311. auto res = cli.Get("/");
  13312. ASSERT_TRUE(!res);
  13313. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13314. // Verify backend error is captured for hostname verification failure
  13315. EXPECT_NE(0UL, res.ssl_backend_error());
  13316. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13317. res.ssl_error());
  13318. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13319. #if !defined(_WIN32) || \
  13320. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13321. // On non-Windows or when Windows Schannel is disabled, the error comes
  13322. // from OpenSSL's hostname verification
  13323. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13324. res.ssl_backend_error());
  13325. #endif
  13326. #endif
  13327. }
  13328. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13329. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13330. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13331. SSLClient cli("www.google.com", 443);
  13332. cli.enable_server_certificate_verification(true);
  13333. auto res = cli.Get("/");
  13334. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13335. }
  13336. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13337. SSLClient cli("www.google.com", 443);
  13338. cli.enable_server_certificate_verification(true);
  13339. cli.enable_windows_certificate_verification(false);
  13340. auto res = cli.Get("/");
  13341. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13342. }
  13343. // The server sends an intermediate cross-signed by a root Windows trusts,
  13344. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13345. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13346. SSLClient cli("accounts.spotify.com", 443);
  13347. auto res = cli.Get("/");
  13348. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13349. << " ssl_backend_error=" << res.ssl_backend_error();
  13350. }
  13351. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13352. // policy status, which no backend reports for a self-signed certificate.
  13353. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13354. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13355. ASSERT_TRUE(svr.is_valid());
  13356. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13357. auto se = detail::scope_exit([&] {
  13358. svr.stop();
  13359. t.join();
  13360. ASSERT_FALSE(svr.is_running());
  13361. });
  13362. svr.wait_until_ready();
  13363. SSLClient cli("127.0.0.1", PORT);
  13364. cli.set_connection_timeout(30);
  13365. auto res = cli.Get("/");
  13366. ASSERT_FALSE(res);
  13367. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13368. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13369. }
  13370. #endif
  13371. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13372. Client cli("https://google.com");
  13373. auto res = cli.Get("/");
  13374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13375. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13376. }
  13377. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13378. SSLClient cli("google.com");
  13379. cli.set_ca_cert_path(CA_CERT_FILE);
  13380. auto res = cli.Get("/");
  13381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13382. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13383. }
  13384. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13385. SSLClient cli("google.com");
  13386. cli.enable_server_certificate_verification(true);
  13387. cli.set_ca_cert_path("hello");
  13388. auto res = cli.Get("/");
  13389. ASSERT_TRUE(!res);
  13390. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13391. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13392. // should be set
  13393. EXPECT_EQ(0, res.ssl_error());
  13394. // Verify backend error is captured for SSLLoadingCerts
  13395. // This error occurs when loading CA certificates fails
  13396. EXPECT_NE(0UL, res.ssl_backend_error());
  13397. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13398. // OpenSSL specific error codes:
  13399. // > openssl errstr 0x80000002
  13400. // error:80000002:system library::No such file or directory
  13401. // > openssl errstr 0xA000126
  13402. // error:0A000126:SSL routines::unexpected eof while reading
  13403. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13404. res.ssl_backend_error() == 0xA000126);
  13405. #endif
  13406. }
  13407. TEST(SSLClientTest, ServerCertificateVerification4) {
  13408. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13409. ASSERT_TRUE(svr.is_valid());
  13410. svr.Get("/test", [&](const Request &, Response &res) {
  13411. res.set_content("test", "text/plain");
  13412. svr.stop();
  13413. ASSERT_TRUE(true);
  13414. });
  13415. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13416. auto se = detail::scope_exit([&] {
  13417. t.join();
  13418. ASSERT_FALSE(svr.is_running());
  13419. });
  13420. svr.wait_until_ready();
  13421. SSLClient cli("127.0.0.1", PORT);
  13422. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13423. cli.enable_server_certificate_verification(true);
  13424. cli.set_connection_timeout(30);
  13425. auto res = cli.Get("/test");
  13426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13427. ASSERT_EQ(StatusCode::OK_200, res->status);
  13428. }
  13429. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13430. std::string cert;
  13431. read_file(CA_CERT_FILE, cert);
  13432. SSLClient cli("google.com");
  13433. cli.load_ca_cert_store(cert.data(), cert.size());
  13434. const auto res = cli.Get("/");
  13435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13436. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13437. }
  13438. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13439. // clang-format off
  13440. static constexpr char cert[] =
  13441. "GlobalSign Root CA\n"
  13442. "==================\n"
  13443. "-----BEGIN CERTIFICATE-----\n"
  13444. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13445. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13446. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13447. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13448. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13449. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13450. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13451. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13452. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13453. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13454. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13455. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13456. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13457. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13458. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13459. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13460. "-----END CERTIFICATE-----\n";
  13461. // clang-format on
  13462. SSLClient cli("google.com");
  13463. cli.load_ca_cert_store(cert, sizeof(cert));
  13464. const auto res = cli.Get("/");
  13465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13466. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13467. }
  13468. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13469. SSLClient cli("www.youtube.com");
  13470. cli.set_ca_cert_path(CA_CERT_FILE);
  13471. cli.enable_server_certificate_verification(true);
  13472. cli.set_follow_location(true);
  13473. auto res = cli.Get("/");
  13474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13475. ASSERT_EQ(StatusCode::OK_200, res->status);
  13476. }
  13477. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13478. SSLClient cli("wWw.YouTube.Com");
  13479. cli.set_ca_cert_path(CA_CERT_FILE);
  13480. cli.enable_server_certificate_verification(true);
  13481. cli.enable_server_hostname_verification(true);
  13482. cli.set_follow_location(true);
  13483. auto res = cli.Get("/");
  13484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13485. ASSERT_EQ(StatusCode::OK_200, res->status);
  13486. }
  13487. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13488. SSLClient cli("gOoGlE.COm");
  13489. cli.enable_server_certificate_verification(true);
  13490. cli.enable_server_hostname_verification(true);
  13491. cli.set_follow_location(true);
  13492. auto res = cli.Get("/");
  13493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13494. ASSERT_EQ(StatusCode::OK_200, res->status);
  13495. }
  13496. TEST(SSLClientTest, Issue2004_Online) {
  13497. Client client("https://google.com");
  13498. client.set_follow_location(true);
  13499. auto res = client.Get("/");
  13500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13501. ASSERT_EQ(StatusCode::OK_200, res->status);
  13502. auto body = res->body;
  13503. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13504. }
  13505. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13506. // Create SSLClient with invalid cert/key to make is_valid() return false
  13507. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13508. "nonexistent_key.pem");
  13509. // is_valid() should be false due to cert loading failure
  13510. ASSERT_FALSE(cli.is_valid());
  13511. auto res = cli.Get("/");
  13512. ASSERT_FALSE(res);
  13513. EXPECT_EQ(Error::SSLConnection, res.error());
  13514. }
  13515. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13516. // Test for Issue #2251: SSL error not properly reported when client cert
  13517. // and key paths are swapped or mismatched
  13518. // This simulates the scenario where user accidentally swaps the cert and key
  13519. // files
  13520. // Using client cert file as private key and vice versa (completely wrong)
  13521. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13522. // Should fail validation due to cert/key mismatch
  13523. ASSERT_FALSE(cli.is_valid());
  13524. // Attempt to make a request should fail with proper error
  13525. auto res = cli.Get("/");
  13526. ASSERT_FALSE(res);
  13527. EXPECT_EQ(Error::SSLConnection, res.error());
  13528. // SSL error should be recorded in the Result object (this is the key fix for
  13529. // Issue #2251)
  13530. auto backend_error = res.ssl_backend_error();
  13531. EXPECT_NE(0u, backend_error);
  13532. }
  13533. // Tests cert/key mismatch detection at the TLS context level
  13534. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13535. // Test that using mismatched cert/key causes connection failure.
  13536. // We verify this at the SSLClient level rather than through internal
  13537. // TLS API functions.
  13538. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13539. cli.enable_server_certificate_verification(false);
  13540. cli.set_connection_timeout(2);
  13541. // The mismatch should cause a connection or handshake error
  13542. auto res = cli.Get("/test");
  13543. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13544. // Either way, the request should fail
  13545. EXPECT_FALSE(res);
  13546. }
  13547. #endif
  13548. #if 0
  13549. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13550. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13551. ASSERT_TRUE(cli != nullptr);
  13552. cli->set_address_family(AF_INET6);
  13553. cli->set_interface("en0");
  13554. auto res = cli->Get("/get");
  13555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13556. ASSERT_EQ(StatusCode::OK_200, res->status);
  13557. }
  13558. #endif
  13559. // Client certificate tests - work with all TLS backends
  13560. #ifdef CPPHTTPLIB_SSL_ENABLED
  13561. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13562. void ClientCertPresent(
  13563. const std::string &client_cert_file,
  13564. const std::string &client_private_key_file,
  13565. const std::string &client_encrypted_private_key_pass = std::string(),
  13566. const ClientCertServerSetup &setup = nullptr) {
  13567. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13568. ASSERT_TRUE(svr.is_valid());
  13569. if (setup) { setup(svr); }
  13570. svr.Get("/test", [&](const Request &req, Response &res) {
  13571. res.set_content("test", "text/plain");
  13572. auto cert = req.peer_cert();
  13573. ASSERT_TRUE(static_cast<bool>(cert));
  13574. std::string common_name = cert.subject_cn();
  13575. EXPECT_EQ("Common Name", common_name);
  13576. });
  13577. auto port = svr.bind_to_any_port(HOST);
  13578. ASSERT_LT(0, port);
  13579. thread t = thread([&]() { svr.listen_after_bind(); });
  13580. auto se = detail::scope_exit([&] {
  13581. svr.stop();
  13582. t.join();
  13583. ASSERT_FALSE(svr.is_running());
  13584. });
  13585. svr.wait_until_ready();
  13586. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13587. client_encrypted_private_key_pass);
  13588. cli.enable_server_certificate_verification(false);
  13589. cli.set_connection_timeout(30);
  13590. auto res = cli.Get("/test");
  13591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13592. ASSERT_EQ(StatusCode::OK_200, res->status);
  13593. }
  13594. TEST(SSLClientServerTest, ClientCertPresent) {
  13595. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13596. }
  13597. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13598. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13599. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13600. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13601. }
  13602. // Expects svr, which must require client certificates, to reject a client
  13603. // that has none
  13604. void RejectsClientWithoutCert(SSLServer &svr) {
  13605. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13606. auto port = svr.bind_to_any_port(HOST);
  13607. ASSERT_LT(0, port);
  13608. thread t = thread([&]() { svr.listen_after_bind(); });
  13609. auto se = detail::scope_exit([&] {
  13610. svr.stop();
  13611. t.join();
  13612. ASSERT_FALSE(svr.is_running());
  13613. });
  13614. svr.wait_until_ready();
  13615. SSLClient cli(HOST, port);
  13616. cli.set_connection_timeout(30);
  13617. // Skip the server certificate check, so that the request fails because the
  13618. // client certificate is missing rather than because cert.pem is not trusted
  13619. cli.enable_server_certificate_verification(false);
  13620. auto res = cli.Get("/test");
  13621. ASSERT_FALSE(res);
  13622. // The server rejects the client during the handshake, or on TLS 1.3 right
  13623. // after it, which the client notices on its first write or read
  13624. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13625. res.error() == Error::Write || res.error() == Error::Read)
  13626. << to_string(res.error());
  13627. if (res.error() == Error::SSLConnection) {
  13628. EXPECT_NE(0UL, res.ssl_backend_error());
  13629. }
  13630. // A rejection noticed on the write keeps the TLS error the write hit
  13631. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13632. }
  13633. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13635. ASSERT_TRUE(svr.is_valid());
  13636. if (setup) { setup(svr); }
  13637. RejectsClientWithoutCert(svr);
  13638. }
  13639. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13640. // A server that requires client certificates must keep requiring them after
  13641. // setup changes it, and keep accepting a client that has one
  13642. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13643. ClientCertMissing(setup);
  13644. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13645. setup);
  13646. }
  13647. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13648. ClientCertStillRequired([](SSLServer &svr) {
  13649. ASSERT_TRUE(tls::set_verify_callback(
  13650. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13651. });
  13652. }
  13653. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13654. ClientCertStillRequired([](SSLServer &svr) {
  13655. ASSERT_TRUE(tls::set_verify_callback(
  13656. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13657. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13658. });
  13659. }
  13660. // The client verifies the server certificate during the handshake, so a
  13661. // server that fails the check never gets the client certificate, even when a
  13662. // verifier of the client's own accepts it
  13663. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13664. struct Case {
  13665. const char *trusted_ca;
  13666. const char *host;
  13667. Error error;
  13668. };
  13669. // cert2.pem names localhost: the first client does not trust it, and the
  13670. // second trusts it but asks for another name
  13671. for (const auto &c :
  13672. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13673. Case{SERVER_CERT2_FILE, "example.com",
  13674. Error::SSLServerHostnameVerification}}) {
  13675. for (auto with_verifier : {false, true}) {
  13676. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13677. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13678. CLIENT_CA_CERT_FILE);
  13679. ASSERT_TRUE(svr.is_valid());
  13680. std::atomic<bool> got_client_cert{false};
  13681. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13682. [&](const tls::VerifyContext &) {
  13683. got_client_cert = true;
  13684. return true;
  13685. }));
  13686. auto port = svr.bind_to_any_port("127.0.0.1");
  13687. ASSERT_LT(0, port);
  13688. thread t = thread([&] { svr.listen_after_bind(); });
  13689. svr.wait_until_ready();
  13690. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13691. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13692. cli.set_ca_cert_path(c.trusted_ca);
  13693. if (with_verifier) {
  13694. cli.set_server_certificate_verifier(
  13695. [](const tls::VerifyContext &) { return true; });
  13696. }
  13697. auto res = cli.Get("/");
  13698. EXPECT_FALSE(res);
  13699. EXPECT_EQ(c.error, res.error());
  13700. svr.stop();
  13701. t.join();
  13702. EXPECT_FALSE(got_client_cert);
  13703. }
  13704. }
  13705. }
  13706. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13707. std::string cert_pem, key_pem, ca_pem;
  13708. read_file(SERVER_CERT_FILE, cert_pem);
  13709. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13710. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13711. ASSERT_TRUE(
  13712. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13713. }
  13714. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13716. ASSERT_TRUE(svr.is_valid());
  13717. UpdateCertsPemWithClientCA(svr);
  13718. RejectsClientWithoutCert(svr);
  13719. }
  13720. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13721. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13722. }
  13723. // A TLS error from one request must not show up in a later request's Result
  13724. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13726. ASSERT_TRUE(svr.is_valid());
  13727. svr.Get("/test", [](const Request &, Response &res) {
  13728. res.set_content("test", "text/plain");
  13729. });
  13730. auto port = svr.bind_to_any_port(HOST);
  13731. ASSERT_LT(0, port);
  13732. thread t = thread([&]() { svr.listen_after_bind(); });
  13733. auto se = detail::scope_exit([&] {
  13734. svr.stop();
  13735. t.join();
  13736. ASSERT_FALSE(svr.is_running());
  13737. });
  13738. svr.wait_until_ready();
  13739. SSLClient cli(HOST, port);
  13740. cli.set_connection_timeout(30);
  13741. cli.enable_server_hostname_verification(false);
  13742. // cert.pem is not trusted, so the handshake fails
  13743. ASSERT_FALSE(cli.Get("/test"));
  13744. cli.enable_server_certificate_verification(false);
  13745. auto res = cli.Get("/test");
  13746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13747. EXPECT_EQ(0, res.ssl_error());
  13748. EXPECT_EQ(0UL, res.ssl_backend_error());
  13749. }
  13750. // PEM memory-based constructor tests (works with all TLS backends).
  13751. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13752. // terminator after it.
  13753. void PemMemoryClientCertPresent(
  13754. const std::string &client_cert_file,
  13755. const std::string &client_private_key_file,
  13756. const std::string &client_encrypted_private_key_pass = std::string(),
  13757. bool exact_size = false) {
  13758. // Read PEM files into memory
  13759. std::string server_cert_pem, server_key_pem;
  13760. std::string client_ca_pem;
  13761. std::string client_cert_pem, client_key_pem;
  13762. read_file(SERVER_CERT_FILE, server_cert_pem);
  13763. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13764. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13765. read_file(client_cert_file, client_cert_pem);
  13766. read_file(client_private_key_file, client_key_pem);
  13767. std::list<std::vector<char>> exact_copies;
  13768. auto data = [&](const std::string &pem) -> const char * {
  13769. if (!exact_size) { return pem.c_str(); }
  13770. exact_copies.emplace_back(pem.begin(), pem.end());
  13771. return exact_copies.back().data();
  13772. };
  13773. // Create server with PEM memory
  13774. SSLServer::PemMemory server_pem = {
  13775. data(server_cert_pem),
  13776. server_cert_pem.size(),
  13777. data(server_key_pem),
  13778. server_key_pem.size(),
  13779. data(client_ca_pem),
  13780. client_ca_pem.size(),
  13781. nullptr // no password for server key
  13782. };
  13783. SSLServer svr(server_pem);
  13784. ASSERT_TRUE(svr.is_valid());
  13785. svr.Get("/test", [&](const Request &req, Response &res) {
  13786. res.set_content("test", "text/plain");
  13787. auto cert = req.peer_cert();
  13788. ASSERT_TRUE(static_cast<bool>(cert));
  13789. EXPECT_EQ("Common Name", cert.subject_cn());
  13790. });
  13791. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13792. auto se = detail::scope_exit([&] {
  13793. svr.stop();
  13794. t.join();
  13795. ASSERT_FALSE(svr.is_running());
  13796. });
  13797. svr.wait_until_ready();
  13798. // Create client with PEM memory
  13799. const char *password = client_encrypted_private_key_pass.empty()
  13800. ? nullptr
  13801. : client_encrypted_private_key_pass.c_str();
  13802. SSLClient::PemMemory client_pem = {
  13803. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13804. client_key_pem.size(), password};
  13805. SSLClient cli(HOST, PORT, client_pem);
  13806. cli.enable_server_certificate_verification(false);
  13807. cli.set_connection_timeout(30);
  13808. auto res = cli.Get("/test");
  13809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13810. ASSERT_EQ(StatusCode::OK_200, res->status);
  13811. }
  13812. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13813. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13814. }
  13815. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13816. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13817. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13818. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13819. }
  13820. // A server built from PEM memory with a client CA requires client certificates,
  13821. // also when the CA is a NUL-terminated string passed with a length of 0
  13822. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13823. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13824. read_file(SERVER_CERT_FILE, server_cert_pem);
  13825. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13826. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13827. SSLServer::PemMemory server_pem = {
  13828. server_cert_pem.c_str(),
  13829. server_cert_pem.size(),
  13830. server_key_pem.c_str(),
  13831. server_key_pem.size(),
  13832. client_ca_pem.c_str(),
  13833. client_ca_pem.size(),
  13834. nullptr // no password for server key
  13835. };
  13836. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13837. SCOPED_TRACE(client_ca_pem_len);
  13838. server_pem.client_ca_pem_len = client_ca_pem_len;
  13839. SSLServer svr(server_pem);
  13840. ASSERT_TRUE(svr.is_valid());
  13841. RejectsClientWithoutCert(svr);
  13842. }
  13843. // An empty CA fails to load instead of turning the check off
  13844. server_pem.client_ca_pem = "";
  13845. server_pem.client_ca_pem_len = 0;
  13846. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13847. }
  13848. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13849. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13850. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13851. true);
  13852. }
  13853. // A length shorter than the PEM cuts it short, so it no longer loads
  13854. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13855. std::string cert, key;
  13856. read_file(SERVER_CERT_FILE, cert);
  13857. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13858. for (auto cut_cert : {true, false}) {
  13859. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13860. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13861. SSLServer::PemMemory server_pem = {
  13862. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13863. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13864. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13865. key_len, nullptr};
  13866. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13867. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13868. key.c_str(), key_len, nullptr};
  13869. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13870. }
  13871. }
  13872. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13873. class NoListenSSLServer : public SSLServer {
  13874. public:
  13875. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13876. const char *client_ca_cert_file_path,
  13877. const char *client_ca_cert_dir_path = nullptr)
  13878. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13879. client_ca_cert_dir_path),
  13880. stop_(false) {}
  13881. std::atomic_bool stop_;
  13882. private:
  13883. bool process_and_close_socket(socket_t /*sock*/) override {
  13884. // Don't create SSL context
  13885. while (!stop_.load()) {
  13886. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13887. }
  13888. return true;
  13889. }
  13890. };
  13891. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13892. CLIENT_CA_CERT_FILE);
  13893. ASSERT_TRUE(svr.is_valid());
  13894. svr.Get("/test", [&](const Request &, Response &res) {
  13895. res.set_content("test", "text/plain");
  13896. });
  13897. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13898. auto se = detail::scope_exit([&] {
  13899. svr.stop_ = true;
  13900. svr.stop();
  13901. t.join();
  13902. ASSERT_FALSE(svr.is_running());
  13903. });
  13904. svr.wait_until_ready();
  13905. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13906. cli.enable_server_certificate_verification(false);
  13907. cli.set_connection_timeout(1);
  13908. auto res = cli.Get("/test");
  13909. ASSERT_TRUE(!res);
  13910. EXPECT_EQ(Error::SSLConnection, res.error());
  13911. // Timeout results in WantRead error code (maps to backend-specific value)
  13912. EXPECT_NE(0, res.ssl_error());
  13913. }
  13914. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13915. // Test SSLServer with client certificate verification using the standard
  13916. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13917. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13918. CLIENT_CA_CERT_DIR);
  13919. ASSERT_TRUE(svr.is_valid());
  13920. svr.Get("/test", [&](const Request &req, Response &res) {
  13921. res.set_content("test", "text/plain");
  13922. auto cert = req.peer_cert();
  13923. ASSERT_TRUE(static_cast<bool>(cert));
  13924. auto common_name = cert.subject_cn();
  13925. EXPECT_EQ("Common Name", common_name);
  13926. });
  13927. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13928. auto se = detail::scope_exit([&] {
  13929. svr.stop();
  13930. t.join();
  13931. ASSERT_FALSE(svr.is_running());
  13932. });
  13933. svr.wait_until_ready();
  13934. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13935. cli.enable_server_certificate_verification(false);
  13936. cli.set_connection_timeout(30);
  13937. auto res = cli.Get("/test");
  13938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13939. ASSERT_EQ(StatusCode::OK_200, res->status);
  13940. }
  13941. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13942. // Verifies that wildcard matching and exact matching work consistently
  13943. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13944. using namespace httplib::tls;
  13945. // We need a running server to test against
  13946. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13947. ASSERT_TRUE(svr.is_valid());
  13948. svr.Get("/test", [](const Request &, Response &res) {
  13949. res.set_content("ok", "text/plain");
  13950. });
  13951. thread t([&]() { svr.listen(HOST, PORT); });
  13952. auto se = detail::scope_exit([&] {
  13953. svr.stop();
  13954. t.join();
  13955. });
  13956. svr.wait_until_ready();
  13957. bool verify_callback_called = false;
  13958. bool verify_result_wrong = false;
  13959. SSLClient cli(HOST, PORT);
  13960. cli.enable_server_certificate_verification(true);
  13961. cli.set_ca_cert_path(CA_CERT_FILE);
  13962. cli.set_connection_timeout(5);
  13963. // Note: Test certificate has CN="Common Name", not "localhost"
  13964. bool verify_result_cn = false;
  13965. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13966. verify_callback_called = true;
  13967. if (!ctx.cert) return false;
  13968. // Test 1: "Common Name" should match (our test server cert CN)
  13969. verify_result_cn = ctx.check_hostname("Common Name");
  13970. // Test 2: wrong hostname should not match
  13971. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13972. return true; // Accept for the purpose of this test
  13973. });
  13974. auto res = cli.Get("/test");
  13975. // The request may succeed or fail depending on cert configuration
  13976. // but the callback should have been called
  13977. ASSERT_TRUE(verify_callback_called)
  13978. << "Verify callback should have been called";
  13979. // CN="Common Name" should match our test certificate
  13980. //
  13981. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13982. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13983. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13984. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13985. // <openssl/base.h>, which is included transitively when
  13986. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13987. #if defined(OPENSSL_IS_BORINGSSL)
  13988. EXPECT_FALSE(verify_result_cn)
  13989. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13990. #else
  13991. EXPECT_TRUE(verify_result_cn)
  13992. << "verify_hostname should match 'Common Name' (certificate CN)";
  13993. #endif
  13994. // Wrong hostname should not match
  13995. EXPECT_FALSE(verify_result_wrong)
  13996. << "verify_hostname should not match 'wronghost.example.com'";
  13997. }
  13998. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13999. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14000. // X509_check_ip behavior and must hold for every backend.
  14001. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14002. using namespace httplib::tls;
  14003. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14004. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14005. ASSERT_TRUE(svr.is_valid());
  14006. svr.Get("/test", [](const Request &, Response &res) {
  14007. res.set_content("ok", "text/plain");
  14008. });
  14009. thread t([&]() { svr.listen(HOST, PORT); });
  14010. auto se = detail::scope_exit([&] {
  14011. svr.stop();
  14012. t.join();
  14013. });
  14014. svr.wait_until_ready();
  14015. bool verify_callback_called = false;
  14016. bool ip_matched_via_cn = true;
  14017. SSLClient cli(HOST, PORT);
  14018. cli.enable_server_certificate_verification(true);
  14019. cli.set_ca_cert_path(CA_CERT_FILE);
  14020. cli.set_connection_timeout(5);
  14021. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14022. verify_callback_called = true;
  14023. if (!ctx.cert) return false;
  14024. // The IP appears only in the CN, so it must NOT be accepted.
  14025. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14026. return true; // Accept for the purpose of this test
  14027. });
  14028. cli.Get("/test");
  14029. ASSERT_TRUE(verify_callback_called)
  14030. << "Verify callback should have been called";
  14031. EXPECT_FALSE(ip_matched_via_cn)
  14032. << "An IP host must not be authenticated via the certificate CN";
  14033. }
  14034. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14035. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14036. using namespace httplib::tls;
  14037. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14038. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14039. ASSERT_TRUE(svr.is_valid());
  14040. svr.Get("/test", [](const Request &, Response &res) {
  14041. res.set_content("ok", "text/plain");
  14042. });
  14043. thread t([&]() { svr.listen(HOST, PORT); });
  14044. auto se = detail::scope_exit([&] {
  14045. svr.stop();
  14046. t.join();
  14047. });
  14048. svr.wait_until_ready();
  14049. bool verify_callback_called = false;
  14050. bool san_matched = false;
  14051. bool wrong_ipv6_matched = true;
  14052. bool cn_ipv6_matched = true;
  14053. SSLClient cli(HOST, PORT);
  14054. cli.enable_server_certificate_verification(true);
  14055. cli.set_ca_cert_path(CA_CERT_FILE);
  14056. cli.set_connection_timeout(5);
  14057. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14058. verify_callback_called = true;
  14059. if (!ctx.cert) return false;
  14060. // Matches the IPv6 iPAddress SAN.
  14061. san_matched = ctx.check_hostname("2001:db8::1");
  14062. // A different IPv6 address must not match.
  14063. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14064. // "::1" lives only in the CN, so it must not be accepted.
  14065. cn_ipv6_matched = ctx.check_hostname("::1");
  14066. return true; // Accept for the purpose of this test
  14067. });
  14068. cli.Get("/test");
  14069. ASSERT_TRUE(verify_callback_called)
  14070. << "Verify callback should have been called";
  14071. EXPECT_TRUE(san_matched)
  14072. << "verify_hostname should match an IPv6 iPAddress SAN";
  14073. EXPECT_FALSE(wrong_ipv6_matched)
  14074. << "verify_hostname should not match a non-matching IPv6 address";
  14075. EXPECT_FALSE(cn_ipv6_matched)
  14076. << "An IPv6 host must not be authenticated via the certificate CN";
  14077. }
  14078. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14079. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14080. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14081. using namespace httplib::tls;
  14082. // SANs: DNS:a.zz, IP:42.46.122.122
  14083. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14084. ASSERT_TRUE(svr.is_valid());
  14085. svr.Get("/test", [](const Request &, Response &res) {
  14086. res.set_content("ok", "text/plain");
  14087. });
  14088. auto port = svr.bind_to_any_port(HOST);
  14089. thread t([&]() { svr.listen_after_bind(); });
  14090. auto se = detail::scope_exit([&] {
  14091. svr.stop();
  14092. t.join();
  14093. });
  14094. svr.wait_until_ready();
  14095. bool verify_callback_called = false;
  14096. bool dns_san_matched = false;
  14097. bool ip_san_matched = false;
  14098. bool ip_matched_via_dns_san = true;
  14099. bool dns_matched_via_ip_san = true;
  14100. bool cn_matched_next_to_dns_san = true;
  14101. SSLClient cli(HOST, port);
  14102. cli.enable_server_certificate_verification(true);
  14103. cli.set_ca_cert_path(CA_CERT_FILE);
  14104. cli.set_connection_timeout(5);
  14105. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14106. verify_callback_called = true;
  14107. if (!ctx.cert) return false;
  14108. dns_san_matched = ctx.check_hostname("a.zz");
  14109. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14110. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14111. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14112. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14113. return true; // Accept for the purpose of this test
  14114. });
  14115. cli.Get("/test");
  14116. ASSERT_TRUE(verify_callback_called)
  14117. << "Verify callback should have been called";
  14118. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14119. EXPECT_TRUE(ip_san_matched)
  14120. << "verify_hostname should match an iPAddress SAN";
  14121. EXPECT_FALSE(ip_matched_via_dns_san)
  14122. << "An IP host must not be authenticated via a dNSName SAN";
  14123. EXPECT_FALSE(dns_matched_via_ip_san)
  14124. << "A DNS host must not be authenticated via an iPAddress SAN";
  14125. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14126. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14127. }
  14128. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14129. // "www.*.example.test" names one host and not every host under example.test.
  14130. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14131. using namespace httplib::tls;
  14132. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14133. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14134. ASSERT_TRUE(svr.is_valid());
  14135. svr.Get("/test", [](const Request &, Response &res) {
  14136. res.set_content("ok", "text/plain");
  14137. });
  14138. auto port = svr.bind_to_any_port(HOST);
  14139. thread t([&]() { svr.listen_after_bind(); });
  14140. auto se = detail::scope_exit([&] {
  14141. svr.stop();
  14142. t.join();
  14143. });
  14144. svr.wait_until_ready();
  14145. bool verify_callback_called = false;
  14146. bool leftmost_wildcard_matched = false;
  14147. bool wildcard_spanned_labels = true;
  14148. bool inner_wildcard_matched = true;
  14149. SSLClient cli(HOST, port);
  14150. cli.enable_server_certificate_verification(true);
  14151. cli.set_ca_cert_path(CA_CERT_FILE);
  14152. cli.set_connection_timeout(5);
  14153. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14154. verify_callback_called = true;
  14155. if (!ctx.cert) return false;
  14156. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14157. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14158. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14159. return true; // Accept for the purpose of this test
  14160. });
  14161. cli.Get("/test");
  14162. ASSERT_TRUE(verify_callback_called)
  14163. << "Verify callback should have been called";
  14164. EXPECT_TRUE(leftmost_wildcard_matched)
  14165. << "A leftmost wildcard should match a single label";
  14166. EXPECT_FALSE(wildcard_spanned_labels)
  14167. << "A wildcard label must not match more than one label";
  14168. EXPECT_FALSE(inner_wildcard_matched)
  14169. << "A wildcard outside the leftmost label must not be honoured";
  14170. }
  14171. // sans() must report each SAN entry under its own type.
  14172. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14173. using namespace httplib::tls;
  14174. // SANs: DNS:a.zz, IP:42.46.122.122
  14175. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14176. ASSERT_TRUE(svr.is_valid());
  14177. svr.Get("/test", [](const Request &, Response &res) {
  14178. res.set_content("ok", "text/plain");
  14179. });
  14180. auto port = svr.bind_to_any_port(HOST);
  14181. thread t([&]() { svr.listen_after_bind(); });
  14182. auto se = detail::scope_exit([&] {
  14183. svr.stop();
  14184. t.join();
  14185. });
  14186. svr.wait_until_ready();
  14187. bool verify_callback_called = false;
  14188. std::vector<SanEntry> sans;
  14189. SSLClient cli(HOST, port);
  14190. cli.enable_server_certificate_verification(true);
  14191. cli.set_ca_cert_path(CA_CERT_FILE);
  14192. cli.set_connection_timeout(5);
  14193. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14194. verify_callback_called = true;
  14195. if (!ctx.cert) return false;
  14196. sans = ctx.sans();
  14197. return true; // Accept for the purpose of this test
  14198. });
  14199. cli.Get("/test");
  14200. ASSERT_TRUE(verify_callback_called)
  14201. << "Verify callback should have been called";
  14202. auto has_san = [&](SanType type, const std::string &value) {
  14203. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14204. return san.type == type && san.value == value;
  14205. });
  14206. };
  14207. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14208. << "sans() should report the dNSName SAN";
  14209. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14210. << "sans() should report the iPAddress SAN";
  14211. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14212. << "sans() must not report the dNSName SAN as an address";
  14213. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14214. << "sans() must not report the iPAddress SAN as a DNS name";
  14215. }
  14216. #endif
  14217. // mbedTLS-specific callback constructor test
  14218. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14219. #ifdef CPPHTTPLIB_SSL_ENABLED
  14220. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14222. ASSERT_TRUE(svr.is_valid());
  14223. // Set up a handler to verify client certificate is present
  14224. bool client_cert_verified = false;
  14225. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14226. // Verify that client certificate was provided
  14227. client_cert_verified = true;
  14228. res.set_content("success", "text/plain");
  14229. });
  14230. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14231. auto se = detail::scope_exit([&] {
  14232. svr.stop();
  14233. t.join();
  14234. ASSERT_FALSE(svr.is_running());
  14235. });
  14236. svr.wait_until_ready();
  14237. // Client with certificate
  14238. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14239. cli.enable_server_certificate_verification(false);
  14240. cli.set_connection_timeout(30);
  14241. auto res = cli.Get("/test");
  14242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14243. ASSERT_EQ(StatusCode::OK_200, res->status);
  14244. ASSERT_TRUE(client_cert_verified);
  14245. EXPECT_EQ("success", res->body);
  14246. }
  14247. #endif
  14248. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14249. // backends
  14250. #ifdef CPPHTTPLIB_SSL_ENABLED
  14251. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14252. using namespace httplib::tls;
  14253. // Test that when client CA cert file is provided,
  14254. // the server properly requests and validates client certificates
  14255. // Create a server with client authentication
  14256. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14257. ASSERT_TRUE(svr.is_valid());
  14258. bool handler_called = false;
  14259. svr.Get("/test", [&](const Request &req, Response &res) {
  14260. handler_called = true;
  14261. // Verify that a client certificate was provided
  14262. auto cert = req.peer_cert();
  14263. ASSERT_TRUE(static_cast<bool>(cert));
  14264. // Get the issuer name
  14265. std::string issuer_str = cert.issuer_name();
  14266. ASSERT_FALSE(issuer_str.empty());
  14267. // The client certificate should be issued by our test CA
  14268. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14269. res.set_content("authenticated", "text/plain");
  14270. });
  14271. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14272. auto se = detail::scope_exit([&] {
  14273. svr.stop();
  14274. t.join();
  14275. ASSERT_FALSE(svr.is_running());
  14276. });
  14277. svr.wait_until_ready();
  14278. // Connect with a client certificate issued by the CA
  14279. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14280. cli.enable_server_certificate_verification(false);
  14281. cli.set_connection_timeout(30);
  14282. auto res = cli.Get("/test");
  14283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14284. ASSERT_EQ(StatusCode::OK_200, res->status);
  14285. ASSERT_TRUE(handler_called);
  14286. EXPECT_EQ("authenticated", res->body);
  14287. }
  14288. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14289. using namespace httplib::tls;
  14290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14291. ASSERT_TRUE(svr.is_valid());
  14292. svr.Get("/test", [](const Request &, Response &res) {
  14293. res.set_content("ok", "text/plain");
  14294. });
  14295. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14296. auto se = detail::scope_exit([&] {
  14297. svr.stop();
  14298. t.join();
  14299. });
  14300. svr.wait_until_ready();
  14301. SSLClient cli(HOST, PORT);
  14302. cli.enable_server_certificate_verification(false);
  14303. cli.set_connection_timeout(30);
  14304. bool cert_checked = false;
  14305. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14306. if (ctx.cert) {
  14307. auto sans = ctx.sans();
  14308. // Test certificate may or may not have SANs - just verify the API
  14309. // works If SANs exist, verify the types are valid
  14310. for (const auto &san : sans) {
  14311. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14312. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14313. san.type == SanType::OTHER);
  14314. EXPECT_FALSE(san.value.empty());
  14315. }
  14316. cert_checked = true;
  14317. }
  14318. return true;
  14319. });
  14320. auto res = cli.Get("/test");
  14321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14322. EXPECT_TRUE(cert_checked);
  14323. }
  14324. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14325. using namespace httplib::tls;
  14326. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14327. ASSERT_TRUE(svr.is_valid());
  14328. svr.Get("/test", [](const Request &, Response &res) {
  14329. res.set_content("ok", "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. });
  14336. svr.wait_until_ready();
  14337. SSLClient cli(HOST, PORT);
  14338. cli.enable_server_certificate_verification(false);
  14339. cli.set_connection_timeout(30);
  14340. bool validity_checked = false;
  14341. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14342. if (ctx.cert) {
  14343. time_t not_before = 0, not_after = 0;
  14344. bool result = ctx.validity(not_before, not_after);
  14345. EXPECT_TRUE(result);
  14346. // Verify that not_before < now < not_after for a valid cert
  14347. time_t now = time(nullptr);
  14348. EXPECT_LT(not_before, now);
  14349. EXPECT_GT(not_after, now);
  14350. validity_checked = true;
  14351. }
  14352. return true;
  14353. });
  14354. auto res = cli.Get("/test");
  14355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14356. EXPECT_TRUE(validity_checked);
  14357. }
  14358. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14359. using namespace httplib::tls;
  14360. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14361. ASSERT_TRUE(svr.is_valid());
  14362. svr.Get("/test", [](const Request &, Response &res) {
  14363. res.set_content("ok", "text/plain");
  14364. });
  14365. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14366. auto se = detail::scope_exit([&] {
  14367. svr.stop();
  14368. t.join();
  14369. });
  14370. svr.wait_until_ready();
  14371. SSLClient cli(HOST, PORT);
  14372. cli.enable_server_certificate_verification(false);
  14373. cli.set_connection_timeout(30);
  14374. bool serial_checked = false;
  14375. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14376. if (ctx.cert) {
  14377. std::string serial = ctx.serial();
  14378. EXPECT_FALSE(serial.empty());
  14379. // Serial should be a hex string
  14380. for (char c : serial) {
  14381. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14382. (c >= 'a' && c <= 'f'));
  14383. }
  14384. serial_checked = true;
  14385. }
  14386. return true;
  14387. });
  14388. auto res = cli.Get("/test");
  14389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14390. EXPECT_TRUE(serial_checked);
  14391. }
  14392. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14393. // Test 1: Valid CA file - no error should be recorded
  14394. {
  14395. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14396. CLIENT_CA_CERT_FILE);
  14397. ASSERT_TRUE(svr.is_valid());
  14398. // With valid setup, last_ssl_error should be 0
  14399. EXPECT_EQ(0, svr.ssl_last_error());
  14400. }
  14401. // Test 2: Invalid CA file content
  14402. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14403. {
  14404. // Create a temporary file with completely invalid content
  14405. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14406. {
  14407. std::ofstream ofs(temp_invalid_ca);
  14408. ofs << "This is not a certificate file at all\n";
  14409. ofs << "Just plain text content\n";
  14410. }
  14411. // Create server with invalid CA file
  14412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14413. // Clean up temporary file
  14414. std::remove(temp_invalid_ca);
  14415. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14416. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14417. // Note: SSL_CTX_load_verify_locations typically fails first,
  14418. // but our error handling code path is still exercised
  14419. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14420. }
  14421. }
  14422. TEST(VerifyCallbackTest, VerifyContextFields) {
  14423. using namespace httplib::tls;
  14424. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14425. ASSERT_TRUE(svr.is_valid());
  14426. svr.Get("/test", [](const Request &, Response &res) {
  14427. res.set_content("ok", "text/plain");
  14428. });
  14429. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14430. auto se = detail::scope_exit([&] {
  14431. svr.stop();
  14432. t.join();
  14433. });
  14434. svr.wait_until_ready();
  14435. SSLClient cli(HOST, PORT);
  14436. cli.enable_server_certificate_verification(false);
  14437. cli.set_connection_timeout(30);
  14438. int callback_count = 0;
  14439. bool saw_leaf_cert = false;
  14440. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14441. if (ctx.cert) {
  14442. callback_count++;
  14443. // We should see at least one certificate (the leaf)
  14444. std::string cn = ctx.subject_cn();
  14445. if (!cn.empty()) { saw_leaf_cert = true; }
  14446. // Verify context fields are populated
  14447. EXPECT_NE(ctx.session, nullptr);
  14448. EXPECT_GE(ctx.depth, 0);
  14449. }
  14450. return true;
  14451. });
  14452. auto res = cli.Get("/test");
  14453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14454. EXPECT_GT(callback_count, 0);
  14455. EXPECT_TRUE(saw_leaf_cert);
  14456. }
  14457. // A verifier that accepts runs alongside the built-in verification, and is the
  14458. // only check once that is turned off.
  14459. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14460. using namespace httplib::tls;
  14461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14462. ASSERT_TRUE(svr.is_valid());
  14463. svr.Get("/test", [](const Request &, Response &res) {
  14464. res.set_content("ok", "text/plain");
  14465. });
  14466. auto port = svr.bind_to_any_port(HOST);
  14467. thread t([&]() { svr.listen_after_bind(); });
  14468. auto se = detail::scope_exit([&] {
  14469. svr.stop();
  14470. t.join();
  14471. });
  14472. svr.wait_until_ready();
  14473. SSLClient cli(HOST, port);
  14474. cli.enable_server_hostname_verification(false);
  14475. auto calls = 0;
  14476. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14477. calls++;
  14478. return true;
  14479. });
  14480. // cert.pem is not trusted
  14481. auto res = cli.Get("/test");
  14482. ASSERT_FALSE(res);
  14483. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14484. EXPECT_GT(calls, 0);
  14485. cli.enable_server_certificate_verification(false);
  14486. res = cli.Get("/test");
  14487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14488. EXPECT_EQ("ok", res->body);
  14489. }
  14490. // A verifier belongs to the client that set it, not to the thread that set it.
  14491. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14492. using namespace httplib::tls;
  14493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14494. ASSERT_TRUE(svr.is_valid());
  14495. svr.Get("/test", [](const Request &, Response &res) {
  14496. res.set_content("ok", "text/plain");
  14497. });
  14498. auto port = svr.bind_to_any_port(HOST);
  14499. thread t([&]() { svr.listen_after_bind(); });
  14500. auto se = detail::scope_exit([&] {
  14501. svr.stop();
  14502. t.join();
  14503. });
  14504. svr.wait_until_ready();
  14505. auto rejecting_calls = 0;
  14506. SSLClient rejecting(HOST, port);
  14507. rejecting.enable_server_certificate_verification(false);
  14508. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14509. rejecting_calls++;
  14510. return false;
  14511. });
  14512. auto accepting_calls = 0;
  14513. SSLClient accepting(HOST, port);
  14514. accepting.enable_server_certificate_verification(false);
  14515. // Set on another thread than the requests below.
  14516. thread([&]() {
  14517. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14518. accepting_calls++;
  14519. return true;
  14520. });
  14521. }).join();
  14522. // Requested on another thread than the verifier was set on.
  14523. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14524. EXPECT_GT(rejecting_calls, 0);
  14525. auto res = accepting.Get("/test");
  14526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14527. EXPECT_GT(accepting_calls, 0);
  14528. }
  14529. // A verifier replaced while a handshake runs it lives until it returns.
  14530. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14531. using namespace httplib::tls;
  14532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14533. ASSERT_TRUE(svr.is_valid());
  14534. svr.Get("/test", [](const Request &, Response &res) {
  14535. res.set_content("ok", "text/plain");
  14536. });
  14537. auto port = svr.bind_to_any_port(HOST);
  14538. thread t([&]() { svr.listen_after_bind(); });
  14539. auto se = detail::scope_exit([&] {
  14540. svr.stop();
  14541. t.join();
  14542. });
  14543. svr.wait_until_ready();
  14544. SSLClient cli(HOST, port);
  14545. cli.enable_server_certificate_verification(false);
  14546. std::promise<void> entered;
  14547. std::promise<void> replaced;
  14548. auto replaced_future = replaced.get_future();
  14549. auto first_call = true;
  14550. // Long enough to live on the heap
  14551. std::string expected(64, 'v');
  14552. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14553. if (first_call) {
  14554. first_call = false;
  14555. entered.set_value();
  14556. replaced_future.wait();
  14557. }
  14558. return expected == std::string(64, 'v');
  14559. });
  14560. thread request([&]() {
  14561. auto res = cli.Get("/test");
  14562. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14563. });
  14564. entered.get_future().wait();
  14565. cli.set_server_certificate_verifier(
  14566. [](const VerifyContext &) { return true; });
  14567. replaced.set_value();
  14568. request.join();
  14569. }
  14570. // VerifyContext::session is the same handle the other tls:: functions take.
  14571. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14572. using namespace httplib::tls;
  14573. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14574. ASSERT_TRUE(svr.is_valid());
  14575. svr.Get("/test", [](const Request &, Response &res) {
  14576. res.set_content("ok", "text/plain");
  14577. });
  14578. auto port = svr.bind_to_any_port(HOST);
  14579. thread t([&]() { svr.listen_after_bind(); });
  14580. auto se = detail::scope_exit([&] {
  14581. svr.stop();
  14582. t.join();
  14583. });
  14584. svr.wait_until_ready();
  14585. SSLClient cli(HOST, port);
  14586. cli.enable_server_certificate_verification(false);
  14587. session_t verifier_session = nullptr;
  14588. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14589. verifier_session = ctx.session;
  14590. return true;
  14591. });
  14592. session_t session_verifier_session = nullptr;
  14593. cli.set_session_verifier([&](session_t session) {
  14594. session_verifier_session = session;
  14595. return SSLVerifierResponse::NoDecisionMade;
  14596. });
  14597. auto res = cli.Get("/test");
  14598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14599. EXPECT_NE(nullptr, verifier_session);
  14600. EXPECT_EQ(session_verifier_session, verifier_session);
  14601. }
  14602. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14603. using httplib::tls::TlsError;
  14604. // Test that verify_error_to_string returns empty for success
  14605. std::string success_str = TlsError::verify_error_to_string(0);
  14606. EXPECT_TRUE(success_str.empty());
  14607. // Test that verify_error_to_string returns non-empty for error codes
  14608. // Using a common error code (certificate expired)
  14609. std::string error_str =
  14610. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14611. EXPECT_FALSE(error_str.empty());
  14612. }
  14613. TEST(SessionVerifierTest, CertificateAccepted) {
  14614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14615. ASSERT_TRUE(svr.is_valid());
  14616. svr.Get("/test", [](const Request &, Response &res) {
  14617. res.set_content("ok", "text/plain");
  14618. });
  14619. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14620. auto se = detail::scope_exit([&] {
  14621. svr.stop();
  14622. t.join();
  14623. });
  14624. svr.wait_until_ready();
  14625. SSLClient cli(HOST, PORT);
  14626. cli.enable_server_certificate_verification(false);
  14627. cli.set_connection_timeout(30);
  14628. bool callback_called = false;
  14629. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14630. EXPECT_NE(session, nullptr);
  14631. callback_called = true;
  14632. return SSLVerifierResponse::CertificateAccepted;
  14633. });
  14634. auto res = cli.Get("/test");
  14635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14636. EXPECT_EQ(200, res->status);
  14637. EXPECT_TRUE(callback_called);
  14638. }
  14639. TEST(SessionVerifierTest, CertificateRejected) {
  14640. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14641. ASSERT_TRUE(svr.is_valid());
  14642. svr.Get("/test", [](const Request &, Response &res) {
  14643. res.set_content("ok", "text/plain");
  14644. });
  14645. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14646. auto se = detail::scope_exit([&] {
  14647. svr.stop();
  14648. t.join();
  14649. });
  14650. svr.wait_until_ready();
  14651. SSLClient cli(HOST, PORT);
  14652. cli.enable_server_certificate_verification(false);
  14653. cli.set_connection_timeout(30);
  14654. bool callback_called = false;
  14655. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14656. EXPECT_NE(session, nullptr);
  14657. callback_called = true;
  14658. return SSLVerifierResponse::CertificateRejected;
  14659. });
  14660. auto res = cli.Get("/test");
  14661. EXPECT_FALSE(res);
  14662. EXPECT_TRUE(callback_called);
  14663. }
  14664. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14666. ASSERT_TRUE(svr.is_valid());
  14667. svr.Get("/test", [](const Request &, Response &res) {
  14668. res.set_content("ok", "text/plain");
  14669. });
  14670. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14671. auto se = detail::scope_exit([&] {
  14672. svr.stop();
  14673. t.join();
  14674. });
  14675. svr.wait_until_ready();
  14676. // NoDecisionMade with verification disabled should succeed (no default check)
  14677. SSLClient cli(HOST, PORT);
  14678. cli.enable_server_certificate_verification(false);
  14679. cli.set_connection_timeout(30);
  14680. bool callback_called = false;
  14681. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14682. EXPECT_NE(session, nullptr);
  14683. callback_called = true;
  14684. return SSLVerifierResponse::NoDecisionMade;
  14685. });
  14686. auto res = cli.Get("/test");
  14687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14688. EXPECT_EQ(200, res->status);
  14689. EXPECT_TRUE(callback_called);
  14690. }
  14691. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14692. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14693. ASSERT_TRUE(svr.is_valid());
  14694. svr.Get("/test", [](const Request &, Response &res) {
  14695. res.set_content("ok", "text/plain");
  14696. });
  14697. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14698. auto se = detail::scope_exit([&] {
  14699. svr.stop();
  14700. t.join();
  14701. });
  14702. svr.wait_until_ready();
  14703. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14704. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14705. // so we only check that the request fails, not whether the callback was
  14706. // called.
  14707. SSLClient cli(HOST, PORT);
  14708. cli.enable_server_certificate_verification(true);
  14709. cli.set_connection_timeout(30);
  14710. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14711. EXPECT_NE(session, nullptr);
  14712. return SSLVerifierResponse::NoDecisionMade;
  14713. });
  14714. auto res = cli.Get("/test");
  14715. EXPECT_FALSE(res);
  14716. }
  14717. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14718. // Test SSL server using PemMemory constructor with client CA certificates
  14719. // Read PEM files
  14720. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14721. read_file(SERVER_CERT_FILE, server_cert_pem);
  14722. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14723. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14724. // Create SSLServer with PemMemory constructor including client CA
  14725. SSLServer::PemMemory server_pem = {
  14726. server_cert_pem.c_str(),
  14727. server_cert_pem.size(),
  14728. server_key_pem.c_str(),
  14729. server_key_pem.size(),
  14730. client_ca_pem.c_str(),
  14731. client_ca_pem.size(),
  14732. nullptr // no password for server key
  14733. };
  14734. SSLServer svr(server_pem);
  14735. ASSERT_TRUE(svr.is_valid());
  14736. // No SSL error should be recorded for valid setup
  14737. EXPECT_EQ(0, svr.ssl_last_error());
  14738. // Set up server endpoints
  14739. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14740. res.set_content("ok", "text/plain");
  14741. });
  14742. // Start server in a thread
  14743. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14744. svr.wait_until_ready();
  14745. // Connect with client certificate (using constructor with paths)
  14746. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14747. cli.enable_server_certificate_verification(false);
  14748. auto res = cli.Get("/test-pem-ca");
  14749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14750. EXPECT_EQ(200, res->status);
  14751. EXPECT_EQ("ok", res->body);
  14752. svr.stop();
  14753. server_thread.join();
  14754. }
  14755. #endif
  14756. #ifdef _WIN32
  14757. TEST(CleanupTest, WSACleanup) {
  14758. int ret = WSACleanup();
  14759. ASSERT_EQ(0, ret);
  14760. }
  14761. #endif
  14762. #ifndef CPPHTTPLIB_SSL_ENABLED
  14763. TEST(NoSSLSupport, SimpleInterface) {
  14764. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14765. }
  14766. #endif
  14767. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14768. TEST(InvalidScheme, SimpleInterface) {
  14769. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14770. }
  14771. #endif
  14772. TEST(NoScheme, SimpleInterface) {
  14773. Client cli("yahoo.com:80");
  14774. ASSERT_TRUE(cli.is_valid());
  14775. }
  14776. TEST(SendAPI, SimpleInterface_Online) {
  14777. Client cli("http://yahoo.com");
  14778. Request req;
  14779. req.method = "GET";
  14780. req.path = "/";
  14781. auto res = cli.send(req);
  14782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14783. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14784. }
  14785. TEST(SendAPI, WithParamsInRequest) {
  14786. Server svr;
  14787. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14788. EXPECT_TRUE(req.has_param("test"));
  14789. EXPECT_EQ("test_value", req.get_param_value("test"));
  14790. });
  14791. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14792. auto se = detail::scope_exit([&] {
  14793. svr.stop();
  14794. t.join();
  14795. ASSERT_FALSE(svr.is_running());
  14796. });
  14797. svr.wait_until_ready();
  14798. Client cli(HOST, PORT);
  14799. {
  14800. Request req;
  14801. req.method = "GET";
  14802. req.path = "/";
  14803. req.params.emplace("test", "test_value");
  14804. auto res = cli.send(req);
  14805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14806. }
  14807. {
  14808. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14810. }
  14811. }
  14812. TEST(ClientImplMethods, GetSocketTest) {
  14813. httplib::Server svr;
  14814. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14815. res.status = StatusCode::OK_200;
  14816. });
  14817. auto port = svr.bind_to_any_port("127.0.0.1");
  14818. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14819. auto se = detail::scope_exit([&] {
  14820. svr.stop();
  14821. thread.join();
  14822. ASSERT_FALSE(svr.is_running());
  14823. });
  14824. svr.wait_until_ready();
  14825. {
  14826. httplib::Client cli("127.0.0.1", port);
  14827. cli.set_keep_alive(true);
  14828. // Use the behavior of cpp-httplib of opening the connection
  14829. // only when the first request happens. If that changes,
  14830. // this test would be obsolete.
  14831. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14832. // This also implicitly tests the server. But other tests would fail much
  14833. // earlier than this one to be considered.
  14834. auto res = cli.Get("/");
  14835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14836. EXPECT_EQ(StatusCode::OK_200, res->status);
  14837. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14838. }
  14839. }
  14840. #ifdef CPPHTTPLIB_SSL_ENABLED
  14841. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14842. Client cli("http://yahoo.com");
  14843. auto res = cli.Get("/");
  14844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14845. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14846. cli.set_follow_location(true);
  14847. res = cli.Get("/");
  14848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14849. EXPECT_EQ(StatusCode::OK_200, res->status);
  14850. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14851. }
  14852. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14853. Client cli("https://yahoo.com");
  14854. auto res = cli.Get("/");
  14855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14856. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14857. cli.set_follow_location(true);
  14858. res = cli.Get("/");
  14859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14860. EXPECT_EQ(StatusCode::OK_200, res->status);
  14861. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14862. }
  14863. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14864. Client cli("https://yahoo.com");
  14865. auto res = cli.Get("/");
  14866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14867. ASSERT_FALSE(!res);
  14868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14869. ASSERT_FALSE(res == nullptr);
  14870. ASSERT_TRUE(res != nullptr);
  14871. EXPECT_EQ(Error::Success, res.error());
  14872. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14873. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14874. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14875. cli.set_follow_location(true);
  14876. res = cli.Get("/");
  14877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14878. EXPECT_EQ(Error::Success, res.error());
  14879. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14880. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14881. EXPECT_EQ(StatusCode::OK_200, res->status);
  14882. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14883. }
  14884. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14885. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14886. Client cli("https://cdnjs.cloudflare.com");
  14887. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14888. Headers{{"Accept-Encoding", "br"}});
  14889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14890. EXPECT_EQ(StatusCode::OK_200, res->status);
  14891. EXPECT_EQ(287630U, res->body.size());
  14892. EXPECT_EQ("application/javascript; charset=utf-8",
  14893. res->get_header_value("Content-Type"));
  14894. }
  14895. #endif
  14896. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14897. #undef REDIR_HOST // Silence compiler warning
  14898. #define REDIR_HOST "https://httpbingo.org"
  14899. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14900. Client cli(REDIR_HOST);
  14901. cli.set_follow_location(true);
  14902. auto res =
  14903. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14905. EXPECT_EQ(StatusCode::OK_200, res->status);
  14906. }
  14907. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14908. Client cli(REDIR_HOST);
  14909. cli.set_follow_location(true);
  14910. Params params;
  14911. params.emplace("url", "http://example.com");
  14912. params.emplace("status_code", "302");
  14913. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14915. EXPECT_EQ(StatusCode::OK_200, res->status);
  14916. }
  14917. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14918. Client cli(REDIR_HOST);
  14919. cli.set_follow_location(true);
  14920. Params params;
  14921. params.emplace("url", "http://example.com");
  14922. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14924. EXPECT_EQ(StatusCode::OK_200, res->status);
  14925. }
  14926. TEST(HttpToHttpsRedirectTest, CertFile) {
  14927. auto ssl_port = PORT + 1;
  14928. Server svr;
  14929. ASSERT_TRUE(svr.is_valid());
  14930. svr.Get("/index", [&](const Request &, Response &res) {
  14931. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14932. "/index");
  14933. svr.stop();
  14934. });
  14935. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14936. ASSERT_TRUE(ssl_svr.is_valid());
  14937. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14938. res.set_content("test", "text/plain");
  14939. ssl_svr.stop();
  14940. });
  14941. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14942. thread t2 =
  14943. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14944. auto se = detail::scope_exit([&] {
  14945. t2.join();
  14946. t.join();
  14947. ASSERT_FALSE(svr.is_running());
  14948. });
  14949. svr.wait_until_ready();
  14950. ssl_svr.wait_until_ready();
  14951. Client cli("127.0.0.1", PORT);
  14952. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14953. cli.enable_server_certificate_verification(true);
  14954. cli.set_follow_location(true);
  14955. cli.set_connection_timeout(30);
  14956. auto res = cli.Get("/index");
  14957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14958. ASSERT_EQ(StatusCode::OK_200, res->status);
  14959. }
  14960. TEST(SSLClientRedirectTest, CertFile) {
  14961. auto ssl_port = PORT + 1;
  14962. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14963. ASSERT_TRUE(ssl_svr1.is_valid());
  14964. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14965. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14966. "/index");
  14967. ssl_svr1.stop();
  14968. });
  14969. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14970. ASSERT_TRUE(ssl_svr2.is_valid());
  14971. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14972. res.set_content("test", "text/plain");
  14973. ssl_svr2.stop();
  14974. });
  14975. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14976. thread t2 =
  14977. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14978. auto se = detail::scope_exit([&] {
  14979. t2.join();
  14980. t.join();
  14981. ASSERT_FALSE(ssl_svr1.is_running());
  14982. });
  14983. ssl_svr1.wait_until_ready();
  14984. ssl_svr2.wait_until_ready();
  14985. SSLClient cli("127.0.0.1", PORT);
  14986. std::string cert;
  14987. read_file(SERVER_CERT2_FILE, cert);
  14988. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14989. cli.enable_server_certificate_verification(true);
  14990. cli.set_follow_location(true);
  14991. cli.set_connection_timeout(30);
  14992. auto res = cli.Get("/index");
  14993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14994. ASSERT_EQ(StatusCode::OK_200, res->status);
  14995. }
  14996. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14997. // another port, so the client follows it with a new client.
  14998. static Result GetThroughTlsRedirectToDifferentPort(
  14999. const std::function<void(SSLClient &)> &setup,
  15000. const char *target_cert = SERVER_CERT2_FILE,
  15001. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15002. auto ssl_port = PORT + 1;
  15003. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15004. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15005. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15006. "/index");
  15007. });
  15008. SSLServer ssl_svr2(target_cert, target_key);
  15009. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15010. res.set_content("test", "text/plain");
  15011. });
  15012. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15013. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15014. auto se = detail::scope_exit([&] {
  15015. ssl_svr2.stop();
  15016. ssl_svr1.stop();
  15017. t2.join();
  15018. t.join();
  15019. });
  15020. ssl_svr1.wait_until_ready();
  15021. ssl_svr2.wait_until_ready();
  15022. SSLClient cli("127.0.0.1", PORT);
  15023. cli.set_follow_location(true);
  15024. cli.set_connection_timeout(30);
  15025. setup(cli);
  15026. return cli.Get("/index");
  15027. }
  15028. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15029. auto calls = 0;
  15030. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15031. cli.enable_server_certificate_verification(false);
  15032. // Accept the first server only.
  15033. cli.set_session_verifier([&](tls::session_t) {
  15034. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15035. : SSLVerifierResponse::CertificateRejected;
  15036. });
  15037. });
  15038. ASSERT_FALSE(res);
  15039. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15040. EXPECT_EQ(2, calls);
  15041. }
  15042. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15043. std::string pinned;
  15044. auto res = GetThroughTlsRedirectToDifferentPort(
  15045. [&](SSLClient &cli) {
  15046. cli.enable_server_certificate_verification(false);
  15047. // Pin the first certificate seen.
  15048. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15049. if (pinned.empty()) { pinned = ctx.serial(); }
  15050. return ctx.serial() == pinned;
  15051. });
  15052. },
  15053. // A certificate other than the first server's.
  15054. SERVER_CERT_FILE);
  15055. EXPECT_FALSE(res);
  15056. EXPECT_FALSE(pinned.empty());
  15057. }
  15058. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15059. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15060. std::string cert;
  15061. read_file(SERVER_CERT2_FILE, cert);
  15062. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15063. });
  15064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15065. EXPECT_EQ(StatusCode::OK_200, res->status);
  15066. }
  15067. // The target's certificate is signed by the root CA, which the first server's
  15068. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15069. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15070. auto res = GetThroughTlsRedirectToDifferentPort(
  15071. [](SSLClient &cli) {
  15072. std::string root_ca, cert;
  15073. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15074. read_file(SERVER_CERT2_FILE, cert);
  15075. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15076. cli.load_ca_cert_store(cert.data(), cert.size());
  15077. cli.enable_server_hostname_verification(false);
  15078. },
  15079. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15081. EXPECT_EQ(StatusCode::OK_200, res->status);
  15082. }
  15083. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15084. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15085. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15086. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15087. auto res = GetThroughTlsRedirectToDifferentPort(
  15088. [](SSLClient &cli) {
  15089. std::string root_ca, cert;
  15090. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15091. read_file(SERVER_CERT2_FILE, cert);
  15092. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15093. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15094. cli.enable_server_hostname_verification(false);
  15095. },
  15096. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15097. ASSERT_FALSE(res);
  15098. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15099. }
  15100. #endif
  15101. #endif
  15102. #ifdef CPPHTTPLIB_SSL_ENABLED
  15103. // Test that set_ca_cert_store() skips system certs (consistent with
  15104. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15105. // should be trusted - system certs should NOT be loaded.
  15106. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15107. // Load a specific cert that is NOT a system CA cert
  15108. std::string cert;
  15109. read_file(SERVER_CERT2_FILE, cert);
  15110. SSLClient cli("google.com");
  15111. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15112. cli.enable_server_certificate_verification(true);
  15113. // This should FAIL because:
  15114. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15115. // 2. System certs should NOT be loaded when custom store is set
  15116. // If system certs WERE loaded, this would succeed
  15117. auto res = cli.Get("/");
  15118. ASSERT_FALSE(res);
  15119. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15120. }
  15121. // Same as above, but through the native store handle path. Regression test:
  15122. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15123. // merged system certs into the user-provided store.
  15124. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15125. std::string cert;
  15126. read_file(SERVER_CERT2_FILE, cert);
  15127. SSLClient cli("google.com");
  15128. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15129. cli.enable_server_certificate_verification(true);
  15130. auto res = cli.Get("/");
  15131. ASSERT_FALSE(res);
  15132. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15133. }
  15134. // A custom store set via the native handle must still verify a server whose
  15135. // cert it does contain.
  15136. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15137. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15138. ASSERT_TRUE(svr.is_valid());
  15139. svr.Get("/test", [&](const Request &, Response &res) {
  15140. res.set_content("test", "text/plain");
  15141. });
  15142. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15143. auto se = detail::scope_exit([&] {
  15144. svr.stop();
  15145. t.join();
  15146. ASSERT_FALSE(svr.is_running());
  15147. });
  15148. svr.wait_until_ready();
  15149. SSLClient cli("127.0.0.1", PORT);
  15150. std::string cert;
  15151. read_file(SERVER_CERT2_FILE, cert);
  15152. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15153. cli.enable_server_certificate_verification(true);
  15154. cli.set_connection_timeout(30);
  15155. auto res = cli.Get("/test");
  15156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15157. ASSERT_EQ(StatusCode::OK_200, res->status);
  15158. }
  15159. // CA certs loaded through the universal Client must be transferred to the
  15160. // client created internally for following an HTTPS redirect. Regression test:
  15161. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15162. // the CA data for redirect transfer.
  15163. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15164. auto ssl_port = PORT + 1;
  15165. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15166. ASSERT_TRUE(ssl_svr1.is_valid());
  15167. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15168. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15169. "/index");
  15170. });
  15171. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15172. ASSERT_TRUE(ssl_svr2.is_valid());
  15173. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15174. res.set_content("test", "text/plain");
  15175. });
  15176. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15177. thread t2 =
  15178. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15179. auto se = detail::scope_exit([&] {
  15180. ssl_svr2.stop();
  15181. ssl_svr1.stop();
  15182. t2.join();
  15183. t.join();
  15184. ASSERT_FALSE(ssl_svr1.is_running());
  15185. });
  15186. ssl_svr1.wait_until_ready();
  15187. ssl_svr2.wait_until_ready();
  15188. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15189. std::string cert;
  15190. read_file(SERVER_CERT2_FILE, cert);
  15191. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15192. cli.enable_server_certificate_verification(true);
  15193. cli.set_follow_location(true);
  15194. cli.set_connection_timeout(30);
  15195. auto res = cli.Get("/index");
  15196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15197. ASSERT_EQ(StatusCode::OK_200, res->status);
  15198. }
  15199. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15200. // so a host signed by a system CA verifies even though a custom CA is set
  15201. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15202. std::string cert;
  15203. read_file(SERVER_CERT2_FILE, cert);
  15204. SSLClient cli("google.com");
  15205. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15206. cli.enable_system_ca(true);
  15207. cli.enable_server_certificate_verification(true);
  15208. auto res = cli.Get("/");
  15209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15210. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15211. }
  15212. // The custom CA remains effective when combined with the system CA
  15213. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15214. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15215. ASSERT_TRUE(svr.is_valid());
  15216. svr.Get("/test", [&](const Request &, Response &res) {
  15217. res.set_content("test", "text/plain");
  15218. });
  15219. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15220. auto se = detail::scope_exit([&] {
  15221. svr.stop();
  15222. t.join();
  15223. ASSERT_FALSE(svr.is_running());
  15224. });
  15225. svr.wait_until_ready();
  15226. SSLClient cli("127.0.0.1", PORT);
  15227. std::string cert;
  15228. read_file(SERVER_CERT2_FILE, cert);
  15229. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15230. cli.enable_system_ca(true);
  15231. cli.enable_server_certificate_verification(true);
  15232. cli.set_connection_timeout(30);
  15233. auto res = cli.Get("/test");
  15234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15235. ASSERT_EQ(StatusCode::OK_200, res->status);
  15236. }
  15237. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15238. // skip chain verification entirely (only the certificate identity was
  15239. // checked), so a server presenting an untrusted certificate with a matching
  15240. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15241. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15242. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15243. ASSERT_TRUE(svr.is_valid());
  15244. svr.Get("/test", [&](const Request &, Response &res) {
  15245. res.set_content("test", "text/plain");
  15246. });
  15247. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15248. auto se = detail::scope_exit([&] {
  15249. svr.stop();
  15250. t.join();
  15251. ASSERT_FALSE(svr.is_running());
  15252. });
  15253. svr.wait_until_ready();
  15254. SSLClient cli("127.0.0.1", PORT);
  15255. std::string cert;
  15256. // A trusted CA that did not sign the server certificate. The server cert
  15257. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15258. // this connection.
  15259. read_file(CLIENT_CA_CERT_FILE, cert);
  15260. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15261. cli.enable_server_certificate_verification(true);
  15262. cli.set_connection_timeout(30);
  15263. auto res = cli.Get("/test");
  15264. ASSERT_FALSE(res);
  15265. }
  15266. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15267. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15268. // CA that failed to come through fails verification instead of trusting them.
  15269. // (wolfSSL does not list the system CAs it loaded.)
  15270. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15271. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15272. ASSERT_TRUE(svr.is_valid());
  15273. auto port = svr.bind_to_any_port("127.0.0.1");
  15274. ASSERT_LT(0, port);
  15275. thread t = thread([&] { svr.listen_after_bind(); });
  15276. auto se = detail::scope_exit([&] {
  15277. svr.stop();
  15278. t.join();
  15279. ASSERT_FALSE(svr.is_running());
  15280. });
  15281. svr.wait_until_ready();
  15282. // The CAs a client trusts once its first request has loaded them
  15283. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15284. Client cli("https://127.0.0.1:" + std::to_string(port));
  15285. setup(cli);
  15286. cli.Get("/");
  15287. return tls::get_ca_names(cli.tls_context()).size();
  15288. };
  15289. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15290. EXPECT_EQ(0u,
  15291. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15292. }
  15293. #endif
  15294. // A TLS setting changed between requests applies to the next one, not just to
  15295. // the next connection
  15296. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15297. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15298. ASSERT_TRUE(svr.is_valid());
  15299. svr.Get("/", [](const Request &req, Response &res) {
  15300. res.set_content(std::to_string(req.remote_port), "text/plain");
  15301. });
  15302. auto port = svr.bind_to_any_port("127.0.0.1");
  15303. ASSERT_LT(0, port);
  15304. thread t = thread([&] { svr.listen_after_bind(); });
  15305. auto se = detail::scope_exit([&] {
  15306. svr.stop();
  15307. t.join();
  15308. ASSERT_FALSE(svr.is_running());
  15309. });
  15310. svr.wait_until_ready();
  15311. SSLClient cli("127.0.0.1", port);
  15312. cli.set_keep_alive(true);
  15313. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15314. cli.enable_server_certificate_verification(false);
  15315. // The port the request went out from, so a new one means a new connection
  15316. auto client_port = [&] {
  15317. auto res = cli.Get("/");
  15318. return res ? res->body : std::string();
  15319. };
  15320. auto last = client_port();
  15321. ASSERT_FALSE(last.empty());
  15322. // Setting a value it already has keeps the connection
  15323. cli.enable_server_certificate_verification(false);
  15324. cli.enable_server_hostname_verification(true);
  15325. EXPECT_EQ(last, client_port());
  15326. cli.enable_server_certificate_verification(true);
  15327. auto res = cli.Get("/");
  15328. EXPECT_FALSE(res);
  15329. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15330. std::string ca;
  15331. read_file(SERVER_CERT2_FILE, ca);
  15332. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15333. last = client_port();
  15334. ASSERT_FALSE(last.empty());
  15335. std::vector<std::function<void()>> setters = {
  15336. [&] { cli.enable_server_hostname_verification(false); },
  15337. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15338. [&] {
  15339. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15340. },
  15341. [&] {
  15342. cli.set_server_certificate_verifier(
  15343. [](const tls::VerifyContext &) { return true; });
  15344. },
  15345. [&] {
  15346. cli.set_session_verifier(
  15347. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15348. },
  15349. };
  15350. for (const auto &setter : setters) {
  15351. setter();
  15352. auto next = client_port();
  15353. ASSERT_FALSE(next.empty());
  15354. EXPECT_NE(last, next);
  15355. last = next;
  15356. }
  15357. cli.set_session_verifier(
  15358. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15359. auto handle = cli.open_stream("GET", "/");
  15360. EXPECT_FALSE(handle.is_valid());
  15361. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15362. }
  15363. // A PEM given to create_ca_store() needs no NUL after it
  15364. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15365. std::string pem;
  15366. read_file(SERVER_CERT2_FILE, pem);
  15367. auto buf = pem + "X";
  15368. auto store = tls::create_ca_store(buf.data(), pem.size());
  15369. EXPECT_TRUE(store != nullptr);
  15370. SSLClient cli("localhost");
  15371. cli.set_ca_cert_store(store);
  15372. }
  15373. // enable_system_ca(false) prevents system CA loading entirely
  15374. TEST(SSLClientTest, DisableSystemCa_Online) {
  15375. SSLClient cli("google.com");
  15376. cli.enable_system_ca(false);
  15377. cli.enable_server_certificate_verification(true);
  15378. auto res = cli.Get("/");
  15379. ASSERT_FALSE(res);
  15380. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15381. // itself when the CA chain is empty
  15382. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15383. res.error() == Error::SSLConnection);
  15384. }
  15385. // The universal Client forwards enable_system_ca()
  15386. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15387. std::string cert;
  15388. read_file(SERVER_CERT2_FILE, cert);
  15389. Client cli("https://google.com");
  15390. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15391. cli.enable_system_ca(true);
  15392. cli.enable_server_certificate_verification(true);
  15393. auto res = cli.Get("/");
  15394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15395. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15396. }
  15397. // The system CA policy must carry over to the client created internally for
  15398. // following a cross-host HTTPS redirect
  15399. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15400. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15401. ASSERT_TRUE(svr.is_valid());
  15402. svr.Get("/index", [&](const Request &, Response &res) {
  15403. res.set_redirect("https://www.google.com/");
  15404. });
  15405. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15406. auto se = detail::scope_exit([&] {
  15407. svr.stop();
  15408. t.join();
  15409. ASSERT_FALSE(svr.is_running());
  15410. });
  15411. svr.wait_until_ready();
  15412. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15413. std::string cert;
  15414. read_file(SERVER_CERT2_FILE, cert);
  15415. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15416. cli.enable_system_ca(true);
  15417. cli.enable_server_certificate_verification(true);
  15418. cli.set_follow_location(true);
  15419. cli.set_connection_timeout(30);
  15420. // Receiving any response proves the redirect client completed the TLS
  15421. // handshake with a system-CA-signed host
  15422. auto res = cli.Get("/index");
  15423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15424. }
  15425. TEST(MultipartFormDataTest, LargeData) {
  15426. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15427. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15428. const ContentReader &content_reader) {
  15429. if (req.is_multipart_form_data()) {
  15430. std::vector<FormData> items;
  15431. content_reader(
  15432. [&](const FormData &file) {
  15433. items.push_back(file);
  15434. return true;
  15435. },
  15436. [&](const char *data, size_t data_length) {
  15437. items.back().content.append(data, data_length);
  15438. return true;
  15439. });
  15440. EXPECT_TRUE(std::string(items[0].name) == "document");
  15441. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15442. EXPECT_TRUE(items[0].filename == "2MB_data");
  15443. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15444. EXPECT_TRUE(items[1].name == "hello");
  15445. EXPECT_TRUE(items[1].content == "world");
  15446. EXPECT_TRUE(items[1].filename == "");
  15447. EXPECT_TRUE(items[1].content_type == "");
  15448. } else {
  15449. std::string body;
  15450. content_reader([&](const char *data, size_t data_length) {
  15451. body.append(data, data_length);
  15452. return true;
  15453. });
  15454. }
  15455. });
  15456. auto port = svr.bind_to_any_port(HOST);
  15457. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15458. auto se = detail::scope_exit([&] {
  15459. svr.stop();
  15460. t.join();
  15461. ASSERT_FALSE(svr.is_running());
  15462. });
  15463. svr.wait_until_ready();
  15464. {
  15465. std::string data(1024 * 1024 * 2, '.');
  15466. std::stringstream buffer;
  15467. buffer << data;
  15468. SSLClient cli(HOST, port);
  15469. cli.enable_server_certificate_verification(false);
  15470. UploadFormDataItems items{
  15471. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15472. {"hello", "world", "", ""},
  15473. };
  15474. auto res = cli.Post("/post", items);
  15475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15476. ASSERT_EQ(StatusCode::OK_200, res->status);
  15477. }
  15478. }
  15479. TEST(MultipartFormDataTest, DataProviderItems) {
  15480. std::random_device seed_gen;
  15481. std::mt19937 random(seed_gen());
  15482. std::string rand1;
  15483. rand1.resize(1000);
  15484. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15485. std::string rand2;
  15486. rand2.resize(3000);
  15487. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15489. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15490. const ContentReader &content_reader) {
  15491. ASSERT_FALSE(req.is_multipart_form_data());
  15492. std::string body;
  15493. content_reader([&](const char *data, size_t data_length) {
  15494. body.append(data, data_length);
  15495. return true;
  15496. });
  15497. EXPECT_EQ(body, "");
  15498. });
  15499. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15500. const ContentReader &content_reader) {
  15501. ASSERT_TRUE(req.is_multipart_form_data());
  15502. std::vector<FormData> items;
  15503. content_reader(
  15504. [&](const FormData &file) {
  15505. items.push_back(file);
  15506. return true;
  15507. },
  15508. [&](const char *data, size_t data_length) {
  15509. items.back().content.append(data, data_length);
  15510. return true;
  15511. });
  15512. ASSERT_TRUE(items.size() == 2);
  15513. EXPECT_EQ(std::string(items[0].name), "name1");
  15514. EXPECT_EQ(items[0].content, "Testing123");
  15515. EXPECT_EQ(items[0].filename, "filename1");
  15516. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15517. EXPECT_EQ(items[1].name, "name2");
  15518. EXPECT_EQ(items[1].content, "Testing456");
  15519. EXPECT_EQ(items[1].filename, "");
  15520. EXPECT_EQ(items[1].content_type, "");
  15521. });
  15522. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15523. const ContentReader &content_reader) {
  15524. ASSERT_TRUE(req.is_multipart_form_data());
  15525. std::vector<FormData> items;
  15526. content_reader(
  15527. [&](const FormData &file) {
  15528. items.push_back(file);
  15529. return true;
  15530. },
  15531. [&](const char *data, size_t data_length) {
  15532. items.back().content.append(data, data_length);
  15533. return true;
  15534. });
  15535. ASSERT_TRUE(items.size() == 2);
  15536. EXPECT_EQ(items[0].name, "name3");
  15537. EXPECT_EQ(items[0].content, rand1);
  15538. EXPECT_EQ(items[0].filename, "filename3");
  15539. EXPECT_EQ(items[0].content_type, "");
  15540. EXPECT_EQ(items[1].name, "name4");
  15541. EXPECT_EQ(items[1].content, rand2);
  15542. EXPECT_EQ(items[1].filename, "filename4");
  15543. EXPECT_EQ(items[1].content_type, "");
  15544. });
  15545. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15546. const ContentReader &content_reader) {
  15547. ASSERT_TRUE(req.is_multipart_form_data());
  15548. std::vector<FormData> items;
  15549. content_reader(
  15550. [&](const FormData &file) {
  15551. items.push_back(file);
  15552. return true;
  15553. },
  15554. [&](const char *data, size_t data_length) {
  15555. items.back().content.append(data, data_length);
  15556. return true;
  15557. });
  15558. ASSERT_TRUE(items.size() == 4);
  15559. EXPECT_EQ(std::string(items[0].name), "name1");
  15560. EXPECT_EQ(items[0].content, "Testing123");
  15561. EXPECT_EQ(items[0].filename, "filename1");
  15562. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15563. EXPECT_EQ(items[1].name, "name2");
  15564. EXPECT_EQ(items[1].content, "Testing456");
  15565. EXPECT_EQ(items[1].filename, "");
  15566. EXPECT_EQ(items[1].content_type, "");
  15567. EXPECT_EQ(items[2].name, "name3");
  15568. EXPECT_EQ(items[2].content, rand1);
  15569. EXPECT_EQ(items[2].filename, "filename3");
  15570. EXPECT_EQ(items[2].content_type, "");
  15571. EXPECT_EQ(items[3].name, "name4");
  15572. EXPECT_EQ(items[3].content, rand2);
  15573. EXPECT_EQ(items[3].filename, "filename4");
  15574. EXPECT_EQ(items[3].content_type, "");
  15575. });
  15576. auto port = svr.bind_to_any_port("localhost");
  15577. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15578. auto se = detail::scope_exit([&] {
  15579. svr.stop();
  15580. t.join();
  15581. ASSERT_FALSE(svr.is_running());
  15582. });
  15583. svr.wait_until_ready();
  15584. {
  15585. SSLClient cli("localhost", port);
  15586. cli.enable_server_certificate_verification(false);
  15587. UploadFormDataItems items{
  15588. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15589. {"name2", "Testing456", "", ""}, // not a file
  15590. };
  15591. {
  15592. auto res = cli.Post("/post-none", {}, {}, {});
  15593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15594. ASSERT_EQ(StatusCode::OK_200, res->status);
  15595. }
  15596. FormDataProviderItems providers;
  15597. {
  15598. auto res =
  15599. cli.Post("/post-items", {}, items, providers); // empty providers
  15600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15601. ASSERT_EQ(StatusCode::OK_200, res->status);
  15602. }
  15603. providers.push_back({"name3",
  15604. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15605. // test the offset is given correctly at each step
  15606. if (!offset)
  15607. sink.os.write(rand1.data(), 30);
  15608. else if (offset == 30)
  15609. sink.os.write(rand1.data() + 30, 300);
  15610. else if (offset == 330)
  15611. sink.os.write(rand1.data() + 330, 670);
  15612. else if (offset == rand1.size())
  15613. sink.done();
  15614. return true;
  15615. },
  15616. "filename3",
  15617. {}});
  15618. providers.push_back({"name4",
  15619. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15620. // test the offset is given correctly at each step
  15621. if (!offset)
  15622. sink.os.write(rand2.data(), 2000);
  15623. else if (offset == 2000)
  15624. sink.os.write(rand2.data() + 2000, 1);
  15625. else if (offset == 2001)
  15626. sink.os.write(rand2.data() + 2001, 999);
  15627. else if (offset == rand2.size())
  15628. sink.done();
  15629. return true;
  15630. },
  15631. "filename4",
  15632. {}});
  15633. {
  15634. auto res = cli.Post("/post-providers", {}, {}, providers);
  15635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15636. ASSERT_EQ(StatusCode::OK_200, res->status);
  15637. }
  15638. {
  15639. auto res = cli.Post("/post-both", {}, items, providers);
  15640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15641. ASSERT_EQ(StatusCode::OK_200, res->status);
  15642. }
  15643. }
  15644. }
  15645. TEST(MultipartFormDataTest, BadHeader) {
  15646. Server svr;
  15647. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15648. res.set_content("ok", "text/plain");
  15649. });
  15650. thread t = thread([&] { svr.listen(HOST, PORT); });
  15651. auto se = detail::scope_exit([&] {
  15652. svr.stop();
  15653. t.join();
  15654. ASSERT_FALSE(svr.is_running());
  15655. });
  15656. svr.wait_until_ready();
  15657. const std::string body =
  15658. "This is the preamble. It is to be ignored, though it\r\n"
  15659. "is a handy place for composition agents to include an\r\n"
  15660. "explanatory note to non-MIME conformant readers.\r\n"
  15661. "\r\n"
  15662. "\r\n"
  15663. "--simple boundary\r\n"
  15664. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15665. ": BAD...\r\n"
  15666. "\r\n"
  15667. "value1\r\n"
  15668. "--simple boundary\r\n"
  15669. "Content-Disposition: form-data; name=\"field2\"; "
  15670. "filename=\"example.txt\"\r\n"
  15671. "\r\n"
  15672. "value2\r\n"
  15673. "--simple boundary--\r\n"
  15674. "This is the epilogue. It is also to be ignored.\r\n";
  15675. std::string content_type =
  15676. R"(multipart/form-data; boundary="simple boundary")";
  15677. Client cli(HOST, PORT);
  15678. auto res = cli.Post("/post", body, content_type.c_str());
  15679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15680. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15681. }
  15682. TEST(MultipartFormDataTest, WithPreamble) {
  15683. Server svr;
  15684. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15685. res.set_content("ok", "text/plain");
  15686. });
  15687. thread t = thread([&] { svr.listen(HOST, PORT); });
  15688. auto se = detail::scope_exit([&] {
  15689. svr.stop();
  15690. t.join();
  15691. ASSERT_FALSE(svr.is_running());
  15692. });
  15693. svr.wait_until_ready();
  15694. const std::string body =
  15695. "This is the preamble. It is to be ignored, though it\r\n"
  15696. "is a handy place for composition agents to include an\r\n"
  15697. "explanatory note to non-MIME conformant readers.\r\n"
  15698. "\r\n"
  15699. "\r\n"
  15700. "--simple boundary\r\n"
  15701. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15702. "\r\n"
  15703. "value1\r\n"
  15704. "--simple boundary\r\n"
  15705. "Content-Disposition: form-data; name=\"field2\"; "
  15706. "filename=\"example.txt\"\r\n"
  15707. "\r\n"
  15708. "value2\r\n"
  15709. "--simple boundary--\r\n"
  15710. "This is the epilogue. It is also to be ignored.\r\n";
  15711. std::string content_type =
  15712. R"(multipart/form-data; boundary="simple boundary")";
  15713. Client cli(HOST, PORT);
  15714. auto res = cli.Post("/post", body, content_type.c_str());
  15715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15716. EXPECT_EQ(StatusCode::OK_200, res->status);
  15717. }
  15718. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15720. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15721. const ContentReader &content_reader) {
  15722. if (req.is_multipart_form_data()) {
  15723. std::vector<FormData> items;
  15724. content_reader(
  15725. [&](const FormData &file) {
  15726. items.push_back(file);
  15727. return true;
  15728. },
  15729. [&](const char *data, size_t data_length) {
  15730. items.back().content.append(data, data_length);
  15731. return true;
  15732. });
  15733. EXPECT_TRUE(std::string(items[0].name) == "document");
  15734. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15735. EXPECT_TRUE(items[0].filename == "2MB_data");
  15736. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15737. EXPECT_TRUE(items[1].name == "hello");
  15738. EXPECT_TRUE(items[1].content == "world");
  15739. EXPECT_TRUE(items[1].filename == "");
  15740. EXPECT_TRUE(items[1].content_type == "");
  15741. } else {
  15742. std::string body;
  15743. content_reader([&](const char *data, size_t data_length) {
  15744. body.append(data, data_length);
  15745. return true;
  15746. });
  15747. }
  15748. });
  15749. auto port = svr.bind_to_any_port("localhost");
  15750. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15751. auto se = detail::scope_exit([&] {
  15752. svr.stop();
  15753. t.join();
  15754. ASSERT_FALSE(svr.is_running());
  15755. });
  15756. svr.wait_until_ready();
  15757. {
  15758. std::string data(1024 * 1024 * 2, '.');
  15759. std::stringstream buffer;
  15760. buffer << data;
  15761. SSLClient cli("localhost", port);
  15762. cli.enable_server_certificate_verification(false);
  15763. UploadFormDataItems items{
  15764. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15765. {"hello", "world", "", ""},
  15766. };
  15767. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15769. ASSERT_EQ(StatusCode::OK_200, res->status);
  15770. }
  15771. }
  15772. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15773. std::string data(1024 * 1024 * 2, '&');
  15774. std::stringstream buffer;
  15775. buffer << data;
  15776. Client cli("https://localhost:8080");
  15777. UploadFormDataItems items{
  15778. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15779. {"hello", "world", "", ""},
  15780. };
  15781. for (const char &c : " \t\r\n") {
  15782. auto res =
  15783. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15784. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15785. ASSERT_FALSE(res);
  15786. }
  15787. }
  15788. TEST(MultipartFormDataTest, PutFormData) {
  15789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15790. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15791. const ContentReader &content_reader) {
  15792. if (req.is_multipart_form_data()) {
  15793. std::vector<FormData> items;
  15794. content_reader(
  15795. [&](const FormData &file) {
  15796. items.push_back(file);
  15797. return true;
  15798. },
  15799. [&](const char *data, size_t data_length) {
  15800. items.back().content.append(data, data_length);
  15801. return true;
  15802. });
  15803. EXPECT_TRUE(std::string(items[0].name) == "document");
  15804. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15805. EXPECT_TRUE(items[0].filename == "2MB_data");
  15806. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15807. EXPECT_TRUE(items[1].name == "hello");
  15808. EXPECT_TRUE(items[1].content == "world");
  15809. EXPECT_TRUE(items[1].filename == "");
  15810. EXPECT_TRUE(items[1].content_type == "");
  15811. } else {
  15812. std::string body;
  15813. content_reader([&](const char *data, size_t data_length) {
  15814. body.append(data, data_length);
  15815. return true;
  15816. });
  15817. }
  15818. });
  15819. auto port = svr.bind_to_any_port("localhost");
  15820. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15821. auto se = detail::scope_exit([&] {
  15822. svr.stop();
  15823. t.join();
  15824. ASSERT_FALSE(svr.is_running());
  15825. });
  15826. svr.wait_until_ready();
  15827. {
  15828. std::string data(1024 * 1024 * 2, '&');
  15829. std::stringstream buffer;
  15830. buffer << data;
  15831. SSLClient cli("localhost", port);
  15832. cli.enable_server_certificate_verification(false);
  15833. UploadFormDataItems items{
  15834. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15835. {"hello", "world", "", ""},
  15836. };
  15837. auto res = cli.Put("/put", items);
  15838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15839. ASSERT_EQ(StatusCode::OK_200, res->status);
  15840. }
  15841. }
  15842. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15844. svr.Put("/put_customboundary",
  15845. [&](const Request &req, const Response & /*res*/,
  15846. const ContentReader &content_reader) {
  15847. if (req.is_multipart_form_data()) {
  15848. std::vector<FormData> items;
  15849. content_reader(
  15850. [&](const FormData &file) {
  15851. items.push_back(file);
  15852. return true;
  15853. },
  15854. [&](const char *data, size_t data_length) {
  15855. items.back().content.append(data, data_length);
  15856. return true;
  15857. });
  15858. EXPECT_TRUE(std::string(items[0].name) == "document");
  15859. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15860. EXPECT_TRUE(items[0].filename == "2MB_data");
  15861. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15862. EXPECT_TRUE(items[1].name == "hello");
  15863. EXPECT_TRUE(items[1].content == "world");
  15864. EXPECT_TRUE(items[1].filename == "");
  15865. EXPECT_TRUE(items[1].content_type == "");
  15866. } else {
  15867. std::string body;
  15868. content_reader([&](const char *data, size_t data_length) {
  15869. body.append(data, data_length);
  15870. return true;
  15871. });
  15872. }
  15873. });
  15874. auto port = svr.bind_to_any_port("localhost");
  15875. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15876. auto se = detail::scope_exit([&] {
  15877. svr.stop();
  15878. t.join();
  15879. ASSERT_FALSE(svr.is_running());
  15880. });
  15881. svr.wait_until_ready();
  15882. {
  15883. std::string data(1024 * 1024 * 2, '&');
  15884. std::stringstream buffer;
  15885. buffer << data;
  15886. SSLClient cli("localhost", port);
  15887. cli.enable_server_certificate_verification(false);
  15888. UploadFormDataItems items{
  15889. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15890. {"hello", "world", "", ""},
  15891. };
  15892. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15894. ASSERT_EQ(StatusCode::OK_200, res->status);
  15895. }
  15896. }
  15897. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15898. std::string data(1024 * 1024 * 2, '&');
  15899. std::stringstream buffer;
  15900. buffer << data;
  15901. Client cli("https://localhost:8080");
  15902. cli.enable_server_certificate_verification(false);
  15903. UploadFormDataItems items{
  15904. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15905. {"hello", "world", "", ""},
  15906. };
  15907. for (const char &c : " \t\r\n") {
  15908. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15909. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15910. ASSERT_FALSE(res);
  15911. }
  15912. }
  15913. TEST(MultipartFormDataTest, AlternateFilename) {
  15914. auto handled = false;
  15915. Server svr;
  15916. svr.Post("/test", [&](const Request &req, Response &res) {
  15917. ASSERT_EQ(2u, req.form.files.size());
  15918. ASSERT_EQ(1u, req.form.fields.size());
  15919. // Test files
  15920. const auto &file1 = req.form.get_file("file1");
  15921. ASSERT_EQ("file1", file1.name);
  15922. ASSERT_EQ("A.txt", file1.filename);
  15923. ASSERT_EQ("text/plain", file1.content_type);
  15924. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15925. const auto &file2 = req.form.get_file("file2");
  15926. ASSERT_EQ("file2", file2.name);
  15927. ASSERT_EQ("a.html", file2.filename);
  15928. ASSERT_EQ("text/html", file2.content_type);
  15929. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15930. file2.content);
  15931. // Test text field
  15932. const auto &text = req.form.get_field("text");
  15933. ASSERT_EQ("text default", text);
  15934. res.set_content("ok", "text/plain");
  15935. handled = true;
  15936. });
  15937. thread t = thread([&] { svr.listen(HOST, PORT); });
  15938. auto se = detail::scope_exit([&] {
  15939. svr.stop();
  15940. t.join();
  15941. ASSERT_FALSE(svr.is_running());
  15942. ASSERT_TRUE(handled);
  15943. });
  15944. svr.wait_until_ready();
  15945. auto req = "POST /test HTTP/1.1\r\n"
  15946. "Host: localhost\r\n"
  15947. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15948. "Content-Length: 399\r\n"
  15949. "\r\n"
  15950. "----------\r\n"
  15951. "Content-Disposition: form-data; name=\"text\"\r\n"
  15952. "\r\n"
  15953. "text default\r\n"
  15954. "----------\r\n"
  15955. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15956. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15957. "Content-Type: text/plain\r\n"
  15958. "\r\n"
  15959. "Content of a.txt.\r\n"
  15960. "\r\n"
  15961. "----------\r\n"
  15962. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15963. "\"a.html\"\r\n"
  15964. "Content-Type: text/html\r\n"
  15965. "\r\n"
  15966. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15967. "\r\n"
  15968. "------------\r\n";
  15969. ASSERT_TRUE(send_request(1, req));
  15970. }
  15971. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15972. auto handled = false;
  15973. Server svr;
  15974. svr.Post("/test", [&](const Request &req, Response &res) {
  15975. // Case-insensitive "utf-8''" prefix with a long value
  15976. const auto &file = req.form.get_file("file1");
  15977. ASSERT_EQ("file1", file.name);
  15978. // 8000 chars exercises both the Content-Disposition parser and the
  15979. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15980. // Prior to the fix, std::regex_match on this header would cause O(N)
  15981. // stack recursion in libstdc++, leading to SIGSEGV.
  15982. std::string expected_filename(8000, 'A');
  15983. ASSERT_EQ(expected_filename, file.filename);
  15984. res.set_content("ok", "text/plain");
  15985. handled = true;
  15986. });
  15987. thread t = thread([&] { svr.listen(HOST, PORT); });
  15988. auto se = detail::scope_exit([&] {
  15989. svr.stop();
  15990. t.join();
  15991. ASSERT_FALSE(svr.is_running());
  15992. ASSERT_TRUE(handled);
  15993. });
  15994. svr.wait_until_ready();
  15995. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15996. // Regression test for GHSA-qq6v-r583-3h69
  15997. std::string long_filename(8000, 'A');
  15998. std::string body = "----------\r\n"
  15999. "Content-Disposition: form-data; name=\"file1\"; "
  16000. "filename*=\"Utf-8''" +
  16001. long_filename +
  16002. "\"\r\n"
  16003. "\r\n"
  16004. "hello\r\n"
  16005. "------------\r\n";
  16006. auto req = "POST /test HTTP/1.1\r\n"
  16007. "Host: localhost\r\n"
  16008. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16009. "Content-Length: " +
  16010. std::to_string(body.size()) + "\r\n\r\n" + body;
  16011. ASSERT_TRUE(send_request(1, req));
  16012. }
  16013. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16014. auto handled = false;
  16015. Server svr;
  16016. svr.Post("/test", [&](const Request &req, Response &) {
  16017. ASSERT_EQ(2u, req.form.fields.size());
  16018. const auto &text1 = req.form.get_field("text1");
  16019. ASSERT_EQ("text1", text1);
  16020. const auto &text2 = req.form.get_field("text2");
  16021. ASSERT_EQ("text2", text2);
  16022. handled = true;
  16023. });
  16024. thread t = thread([&] { svr.listen(HOST, PORT); });
  16025. auto se = detail::scope_exit([&] {
  16026. svr.stop();
  16027. t.join();
  16028. ASSERT_FALSE(svr.is_running());
  16029. ASSERT_TRUE(handled);
  16030. });
  16031. svr.wait_until_ready();
  16032. auto req = "POST /test HTTP/1.1\r\n"
  16033. "Host: localhost\r\n"
  16034. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16035. "Content-Length: 146\r\n"
  16036. "\r\n----------\r\n"
  16037. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16038. "\r\n"
  16039. "text1"
  16040. "\r\n----------\r\n"
  16041. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16042. "\r\n"
  16043. "text2"
  16044. "\r\n------------";
  16045. std::string response;
  16046. ASSERT_TRUE(send_request(1, req, &response));
  16047. ASSERT_EQ("200", response.substr(9, 3));
  16048. }
  16049. TEST(MultipartFormDataTest, ContentLength) {
  16050. auto handled = false;
  16051. Server svr;
  16052. svr.Post("/test", [&](const Request &req, Response &) {
  16053. ASSERT_EQ(2u, req.form.fields.size());
  16054. const auto &text1 = req.form.get_field("text1");
  16055. ASSERT_EQ("text1", text1);
  16056. const auto &text2 = req.form.get_field("text2");
  16057. ASSERT_EQ("text2", text2);
  16058. handled = true;
  16059. });
  16060. thread t = thread([&] { svr.listen(HOST, PORT); });
  16061. auto se = detail::scope_exit([&] {
  16062. svr.stop();
  16063. t.join();
  16064. ASSERT_FALSE(svr.is_running());
  16065. ASSERT_TRUE(handled);
  16066. });
  16067. svr.wait_until_ready();
  16068. auto req = "POST /test HTTP/1.1\r\n"
  16069. "Host: localhost\r\n"
  16070. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16071. "Content-Length: 167\r\n"
  16072. "\r\n----------\r\n"
  16073. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16074. "Content-Length: 5\r\n"
  16075. "\r\n"
  16076. "text1"
  16077. "\r\n----------\r\n"
  16078. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16079. "\r\n"
  16080. "text2"
  16081. "\r\n------------\r\n";
  16082. std::string response;
  16083. ASSERT_TRUE(send_request(1, req, &response));
  16084. ASSERT_EQ("200", response.substr(9, 3));
  16085. }
  16086. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16087. auto handled = false;
  16088. Server svr;
  16089. svr.Post("/test", [&](const Request &req, Response &) {
  16090. ASSERT_EQ(2u, req.form.fields.size());
  16091. const auto &text1 = req.form.get_field("text1");
  16092. ASSERT_EQ("text1", text1);
  16093. // TODO: Add header access for text fields if needed
  16094. const auto &text2 = req.form.get_field("text2");
  16095. ASSERT_EQ("text2", text2);
  16096. // TODO: Header access for text fields needs to be implemented
  16097. // auto &headers = it->second.headers;
  16098. // ASSERT_EQ(3U, headers.size());
  16099. // auto custom_header = headers.find("x-whatever");
  16100. // ASSERT_TRUE(custom_header != headers.end());
  16101. // ASSERT_NE("customvalue", custom_header->second);
  16102. // ASSERT_EQ("CustomValue", custom_header->second);
  16103. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16104. handled = true;
  16105. });
  16106. thread t = thread([&] { svr.listen(HOST, PORT); });
  16107. auto se = detail::scope_exit([&] {
  16108. svr.stop();
  16109. t.join();
  16110. ASSERT_FALSE(svr.is_running());
  16111. ASSERT_TRUE(handled);
  16112. });
  16113. svr.wait_until_ready();
  16114. auto req = "POST /test HTTP/1.1\r\n"
  16115. "Host: localhost\r\n"
  16116. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16117. "Content-Length: 232\r\n"
  16118. "\r\n----------\r\n"
  16119. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16120. "Content-Length: 5\r\n"
  16121. "X-Test: 1\r\n"
  16122. "\r\n"
  16123. "text1"
  16124. "\r\n----------\r\n"
  16125. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16126. "Content-Type: text/plain\r\n"
  16127. "X-Whatever: CustomValue\r\n"
  16128. "\r\n"
  16129. "text2"
  16130. "\r\n------------\r\n"
  16131. "That should be disregarded. Not even read";
  16132. std::string response;
  16133. ASSERT_TRUE(send_request(1, req, &response));
  16134. ASSERT_EQ("200", response.substr(9, 3));
  16135. }
  16136. TEST(MultipartFormDataTest, LargeHeader) {
  16137. auto handled = false;
  16138. Server svr;
  16139. svr.Post("/test", [&](const Request &req, Response &) {
  16140. ASSERT_EQ(1u, req.form.fields.size());
  16141. const auto &text = req.form.get_field("name1");
  16142. ASSERT_EQ("text1", text);
  16143. handled = true;
  16144. });
  16145. thread t = thread([&] { svr.listen(HOST, PORT); });
  16146. auto se = detail::scope_exit([&] {
  16147. svr.stop();
  16148. t.join();
  16149. ASSERT_FALSE(svr.is_running());
  16150. ASSERT_TRUE(handled);
  16151. });
  16152. svr.wait_until_ready();
  16153. auto boundary = std::string("cpp-httplib-multipart-data");
  16154. std::string content = "--" + boundary +
  16155. "\r\n"
  16156. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16157. "\r\n"
  16158. "text1\r\n"
  16159. "--" +
  16160. boundary + "--\r\n";
  16161. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16162. "Host: localhost\r\n"
  16163. "Content-Type: multipart/form-data;boundary=" +
  16164. boundary +
  16165. "\r\n"
  16166. "Content-Length: " +
  16167. std::to_string(content.size()) +
  16168. "\r\n"
  16169. "Dummy-Header: ";
  16170. std::string header_suffix = "\r\n"
  16171. "\r\n";
  16172. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16173. size_t header_dummy_size =
  16174. read_buff_size -
  16175. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16176. auto header_dummy = std::string(header_dummy_size, '@');
  16177. auto req = header_prefix + header_dummy + header_suffix + content;
  16178. std::string response;
  16179. ASSERT_TRUE(send_request(1, req, &response));
  16180. ASSERT_EQ("200", response.substr(9, 3));
  16181. }
  16182. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16183. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16184. // (not chunked Transfer-Encoding) after the streaming refactor.
  16185. auto handled = false;
  16186. Server svr;
  16187. svr.Post("/upload", [&](const Request &req, Response &res) {
  16188. auto cl_it = req.headers.find("Content-Length");
  16189. EXPECT_TRUE(cl_it != req.headers.end());
  16190. auto te_it = req.headers.find("Transfer-Encoding");
  16191. EXPECT_TRUE(te_it == req.headers.end());
  16192. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16193. res.set_content("ok", "text/plain");
  16194. handled = true;
  16195. });
  16196. auto port = svr.bind_to_any_port(HOST);
  16197. auto t = thread([&] { svr.listen_after_bind(); });
  16198. auto se = detail::scope_exit([&] {
  16199. svr.stop();
  16200. t.join();
  16201. ASSERT_FALSE(svr.is_running());
  16202. ASSERT_TRUE(handled);
  16203. });
  16204. svr.wait_until_ready();
  16205. UploadFormDataItems items = {
  16206. {"field1", "hello", "", "text/plain"},
  16207. {"file1", "world", "test.txt", "application/octet-stream"},
  16208. };
  16209. Client cli(HOST, port);
  16210. auto res = cli.Post("/upload", {}, items);
  16211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16212. EXPECT_EQ(StatusCode::OK_200, res->status);
  16213. }
  16214. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16215. // Verify that make_multipart_content_provider coalesces many small segments
  16216. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16217. constexpr size_t kItemCount = 1000;
  16218. UploadFormDataItems items;
  16219. items.reserve(kItemCount);
  16220. for (size_t i = 0; i < kItemCount; i++) {
  16221. items.push_back(
  16222. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16223. }
  16224. const std::string boundary = "----test-boundary";
  16225. auto content_length = detail::get_multipart_content_length(items, boundary);
  16226. auto provider = detail::make_multipart_content_provider(items, boundary);
  16227. // Drive the provider the same way write_content_with_progress does
  16228. size_t write_count = 0;
  16229. size_t total_bytes = 0;
  16230. DataSink sink;
  16231. size_t offset = 0;
  16232. sink.write = [&](const char *d, size_t l) -> bool {
  16233. (void)d;
  16234. write_count++;
  16235. total_bytes += l;
  16236. offset += l;
  16237. return true;
  16238. };
  16239. sink.is_writable = []() -> bool { return true; };
  16240. while (offset < content_length) {
  16241. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16242. }
  16243. EXPECT_EQ(content_length, total_bytes);
  16244. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16245. // With buffering into 64KB blocks, write_count should be much smaller.
  16246. auto segment_count = 3 * kItemCount + 1;
  16247. EXPECT_LT(write_count, segment_count / 10);
  16248. }
  16249. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16250. // Integration test: send many UploadFormDataItems and verify the server
  16251. // receives all of them correctly (#2410).
  16252. constexpr size_t kItemCount = 500;
  16253. auto handled = false;
  16254. Server svr;
  16255. svr.Post("/upload", [&](const Request &req, Response &res) {
  16256. EXPECT_EQ(kItemCount, req.form.fields.size());
  16257. for (size_t i = 0; i < kItemCount; i++) {
  16258. auto key = "field" + std::to_string(i);
  16259. auto val = "value" + std::to_string(i);
  16260. auto it = req.form.fields.find(key);
  16261. if (it != req.form.fields.end()) {
  16262. EXPECT_EQ(val, it->second.content);
  16263. } else {
  16264. ADD_FAILURE() << "Missing field: " << key;
  16265. }
  16266. }
  16267. res.set_content("ok", "text/plain");
  16268. handled = true;
  16269. });
  16270. auto port = svr.bind_to_any_port(HOST);
  16271. auto t = thread([&] { svr.listen_after_bind(); });
  16272. auto se = detail::scope_exit([&] {
  16273. svr.stop();
  16274. t.join();
  16275. ASSERT_FALSE(svr.is_running());
  16276. ASSERT_TRUE(handled);
  16277. });
  16278. svr.wait_until_ready();
  16279. UploadFormDataItems items;
  16280. items.reserve(kItemCount);
  16281. for (size_t i = 0; i < kItemCount; i++) {
  16282. items.push_back(
  16283. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16284. }
  16285. Client cli(HOST, port);
  16286. auto res = cli.Post("/upload", items);
  16287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16288. EXPECT_EQ(StatusCode::OK_200, res->status);
  16289. }
  16290. TEST(MultipartFormDataTest, MakeFileProvider) {
  16291. // Verify make_file_provider sends a file's contents correctly.
  16292. const std::string file_content(4096, 'Z');
  16293. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16294. {
  16295. std::ofstream ofs(tmp_path, std::ios::binary);
  16296. ofs.write(file_content.data(),
  16297. static_cast<std::streamsize>(file_content.size()));
  16298. }
  16299. auto handled = false;
  16300. Server svr;
  16301. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16302. const ContentReader &content_reader) {
  16303. ASSERT_TRUE(req.is_multipart_form_data());
  16304. std::vector<FormData> items;
  16305. content_reader(
  16306. [&](const FormData &file) {
  16307. items.push_back(file);
  16308. return true;
  16309. },
  16310. [&](const char *data, size_t data_length) {
  16311. items.back().content.append(data, data_length);
  16312. return true;
  16313. });
  16314. ASSERT_EQ(1u, items.size());
  16315. EXPECT_EQ("myfile", items[0].name);
  16316. EXPECT_EQ("data.bin", items[0].filename);
  16317. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16318. EXPECT_EQ(file_content, items[0].content);
  16319. handled = true;
  16320. });
  16321. auto port = svr.bind_to_any_port(HOST);
  16322. auto t = thread([&] { svr.listen_after_bind(); });
  16323. auto se = detail::scope_exit([&] {
  16324. svr.stop();
  16325. t.join();
  16326. ASSERT_FALSE(svr.is_running());
  16327. ASSERT_TRUE(handled);
  16328. std::remove(tmp_path.c_str());
  16329. });
  16330. svr.wait_until_ready();
  16331. FormDataProviderItems providers;
  16332. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16333. "application/octet-stream"));
  16334. Client cli(HOST, port);
  16335. auto res = cli.Post("/upload", {}, {}, providers);
  16336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16337. EXPECT_EQ(StatusCode::OK_200, res->status);
  16338. }
  16339. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16340. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16341. // (100) headers is rejected with a 400 Bad Request response.
  16342. Server svr;
  16343. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16344. res.set_content("ok", "text/plain");
  16345. });
  16346. thread t = thread([&] { svr.listen(HOST, PORT); });
  16347. auto se = detail::scope_exit([&] {
  16348. svr.stop();
  16349. t.join();
  16350. ASSERT_FALSE(svr.is_running());
  16351. });
  16352. svr.wait_until_ready();
  16353. // Build a multipart part with 101 custom headers (exceeding
  16354. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16355. std::stringstream body;
  16356. body << "--simpleboundary\r\n"
  16357. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16358. for (int i = 0; i < 101; i++) {
  16359. body << "X-Custom-Header-" << i << ": value\r\n";
  16360. }
  16361. body << "\r\n"
  16362. << "value1\r\n"
  16363. << "--simpleboundary--\r\n";
  16364. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16365. Client cli(HOST, PORT);
  16366. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16368. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16369. }
  16370. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16371. // A body that never contains the declared boundary must not be accumulated
  16372. // while the parser waits for it. Buffering it would also make every read
  16373. // rescan everything seen so far, which is quadratic in the body size.
  16374. Server svr;
  16375. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16376. res.set_content("ok", "text/plain");
  16377. });
  16378. auto port = svr.bind_to_any_port(HOST);
  16379. thread t = thread([&] { svr.listen_after_bind(); });
  16380. auto se = detail::scope_exit([&] {
  16381. svr.stop();
  16382. t.join();
  16383. ASSERT_FALSE(svr.is_running());
  16384. });
  16385. svr.wait_until_ready();
  16386. Client cli(HOST, port);
  16387. cli.set_read_timeout(60, 0);
  16388. cli.set_write_timeout(60, 0);
  16389. // '-' is the worst case: it matches the first character of the boundary, so
  16390. // every position has to be checked against it.
  16391. auto post_dashes = [&](size_t size) {
  16392. const std::string body(size, '-');
  16393. auto start = std::chrono::steady_clock::now();
  16394. auto res =
  16395. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16396. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16397. std::chrono::steady_clock::now() - start)
  16398. .count();
  16399. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16400. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16401. return ms;
  16402. };
  16403. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16404. // Windows.
  16405. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16406. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16407. // Comparing the two sizes rather than checking an absolute duration keeps
  16408. // this meaningful across build types and CI load, both of which move the
  16409. // absolute numbers by more than an order of magnitude. Four times the bytes
  16410. // costs about four times the time when parsing is linear, and about sixteen
  16411. // times when the body is buffered and rescanned.
  16412. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16413. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16414. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16415. << "ms, which suggests the body is being buffered and rescanned";
  16416. }
  16417. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16418. // A boundary can only be followed by CRLF or by "--", so anything else is
  16419. // malformed no matter what comes next. The parser must say so right away
  16420. // instead of buffering the rest of the declared body.
  16421. Server svr;
  16422. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16423. res.set_content("ok", "text/plain");
  16424. });
  16425. auto port = svr.bind_to_any_port(HOST);
  16426. thread t = thread([&] { svr.listen_after_bind(); });
  16427. auto se = detail::scope_exit([&] {
  16428. svr.stop();
  16429. t.join();
  16430. ASSERT_FALSE(svr.is_running());
  16431. });
  16432. svr.wait_until_ready();
  16433. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16434. // buffers instead of failing would still be waiting for the remaining bytes.
  16435. const std::string body = "--zzzz\r\n"
  16436. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16437. "\r\n"
  16438. "text1"
  16439. "\r\n--zzzzXX";
  16440. const std::string req = "POST /post HTTP/1.1\r\n"
  16441. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16442. "Content-Length: 1048576\r\n"
  16443. "\r\n" +
  16444. body;
  16445. std::string response;
  16446. ASSERT_TRUE(send_request(3, req, &response, port));
  16447. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16448. EXPECT_EQ("400", response.substr(9, 3));
  16449. }
  16450. // Posts a multipart body split into two writes, so that the server sees the
  16451. // split at whatever offset the caller chose, and expects the single "text1"
  16452. // field to come through.
  16453. static void expect_split_multipart_ok(const std::string &body1,
  16454. const std::string &body2) {
  16455. auto handled = false;
  16456. Server svr;
  16457. svr.Post("/post", [&](const Request &req, Response &) {
  16458. EXPECT_EQ(1u, req.form.fields.size());
  16459. EXPECT_EQ("text1", req.form.get_field("text1"));
  16460. handled = true;
  16461. });
  16462. auto port = svr.bind_to_any_port(HOST);
  16463. thread t = thread([&] { svr.listen_after_bind(); });
  16464. auto se = detail::scope_exit([&] {
  16465. svr.stop();
  16466. t.join();
  16467. ASSERT_FALSE(svr.is_running());
  16468. ASSERT_TRUE(handled);
  16469. });
  16470. svr.wait_until_ready();
  16471. // "Connection: close" makes the server close once it has answered, so the
  16472. // response drain ends immediately instead of idling until the read timeout.
  16473. const std::string head =
  16474. "POST /post HTTP/1.1\r\n"
  16475. "Host: localhost\r\n"
  16476. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16477. "Connection: close\r\n"
  16478. "Content-Length: " +
  16479. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16480. std::string response;
  16481. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16482. ASSERT_GE(response.size(), 12u) << "no response";
  16483. EXPECT_EQ("200", response.substr(9, 3));
  16484. }
  16485. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16486. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16487. // ignored, including when it does not arrive in the same read as the
  16488. // close-delimiter itself.
  16489. expect_split_multipart_ok("--zzzz\r\n"
  16490. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16491. "\r\n"
  16492. "text1"
  16493. "\r\n--zzzz--",
  16494. "\r\nthis epilogue must be ignored\r\n");
  16495. }
  16496. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16497. // The initial boundary may be preceded by a preamble of any length and may
  16498. // straddle a read boundary. Discarding data while waiting for it must not
  16499. // throw away a partial boundary sitting at the end of the buffer.
  16500. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16501. "zz\r\n"
  16502. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16503. "\r\n"
  16504. "text1"
  16505. "\r\n--zzzz--\r\n");
  16506. }
  16507. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16508. // The received boundary was only checked for being non-empty, so it could be
  16509. // as long as a header is allowed to be. The parser scans the body for
  16510. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16511. // costs a nearly full comparison at nearly every position, making the
  16512. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16513. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16514. Server svr;
  16515. svr.Post("/post", [](const Request &req, Response &res) {
  16516. EXPECT_EQ(1u, req.form.fields.size());
  16517. EXPECT_EQ("text1", req.form.get_field("text1"));
  16518. res.set_content("ok", "text/plain");
  16519. });
  16520. auto port = svr.bind_to_any_port(HOST);
  16521. thread t = thread([&] { svr.listen_after_bind(); });
  16522. auto se = detail::scope_exit([&] {
  16523. svr.stop();
  16524. t.join();
  16525. ASSERT_FALSE(svr.is_running());
  16526. });
  16527. svr.wait_until_ready();
  16528. Client cli(HOST, port);
  16529. auto post_with_boundary_of_length = [&](size_t len) {
  16530. const std::string boundary(len, 'a');
  16531. const std::string body =
  16532. "--" + boundary +
  16533. "\r\n"
  16534. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16535. "\r\n"
  16536. "text1"
  16537. "\r\n--" +
  16538. boundary + "--\r\n";
  16539. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16540. };
  16541. auto res = post_with_boundary_of_length(70);
  16542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16543. EXPECT_EQ(StatusCode::OK_200, res->status);
  16544. res = post_with_boundary_of_length(71);
  16545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16546. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16547. }
  16548. TEST(MakeFileBodyTest, Basic) {
  16549. const std::string file_content(4096, 'Z');
  16550. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16551. {
  16552. std::ofstream ofs(tmp_path, std::ios::binary);
  16553. ofs.write(file_content.data(),
  16554. static_cast<std::streamsize>(file_content.size()));
  16555. }
  16556. auto handled = false;
  16557. Server svr;
  16558. svr.Post("/upload", [&](const Request &req, Response &res) {
  16559. EXPECT_EQ(file_content, req.body);
  16560. handled = true;
  16561. res.status = StatusCode::OK_200;
  16562. });
  16563. auto port = svr.bind_to_any_port(HOST);
  16564. auto t = thread([&] { svr.listen_after_bind(); });
  16565. auto se = detail::scope_exit([&] {
  16566. svr.stop();
  16567. t.join();
  16568. ASSERT_FALSE(svr.is_running());
  16569. ASSERT_TRUE(handled);
  16570. std::remove(tmp_path.c_str());
  16571. });
  16572. svr.wait_until_ready();
  16573. auto fb = make_file_body(tmp_path);
  16574. ASSERT_GT(fb.first, 0u);
  16575. Client cli(HOST, port);
  16576. auto res =
  16577. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16579. EXPECT_EQ(StatusCode::OK_200, res->status);
  16580. }
  16581. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16582. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16583. {
  16584. std::ofstream ofs(path, std::ios::binary);
  16585. const std::string content(100, 'A');
  16586. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16587. }
  16588. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16589. auto body = make_file_body(path);
  16590. ASSERT_EQ(100u, body.first);
  16591. ASSERT_TRUE(static_cast<bool>(body.second));
  16592. // Rewritten shorter after its length was measured - and, on a server, after
  16593. // that length has already gone out as Content-Length.
  16594. {
  16595. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16596. const std::string content(10, 'A');
  16597. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16598. }
  16599. std::string written;
  16600. DataSink sink;
  16601. sink.write = [&](const char *d, size_t l) {
  16602. written.append(d, l);
  16603. return true;
  16604. };
  16605. // The provider has to report failure. write_content_with_progress() advances
  16606. // its offset only by what was written, so a provider that returns true
  16607. // without completing the length it promised is called again straight away,
  16608. // and again.
  16609. EXPECT_FALSE(body.second(0, body.first, sink));
  16610. EXPECT_EQ(std::string(10, 'A'), written);
  16611. }
  16612. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16613. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16614. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16615. {
  16616. std::ofstream ofs(path, std::ios::binary);
  16617. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16618. }
  16619. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16620. auto body = make_file_body(path);
  16621. ASSERT_EQ(content.size(), body.first);
  16622. ASSERT_TRUE(static_cast<bool>(body.second));
  16623. std::string written;
  16624. DataSink sink;
  16625. sink.write = [&](const char *d, size_t l) {
  16626. written.append(d, l);
  16627. return true;
  16628. };
  16629. EXPECT_TRUE(body.second(0, body.first, sink));
  16630. EXPECT_EQ(content, written);
  16631. }
  16632. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16633. static constexpr unsigned int number_of_tasks{1000000};
  16634. std::atomic_uint count{0};
  16635. std::unique_ptr<TaskQueue> task_queue{
  16636. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16637. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16638. auto queued = task_queue->enqueue(
  16639. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16640. EXPECT_TRUE(queued);
  16641. }
  16642. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16643. task_queue->shutdown();
  16644. #else
  16645. EXPECT_NO_THROW(task_queue->shutdown());
  16646. #endif
  16647. EXPECT_EQ(number_of_tasks, count.load());
  16648. }
  16649. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16650. static constexpr unsigned int number_of_tasks{1000000};
  16651. static constexpr unsigned int qlimit{2};
  16652. unsigned int queued_count{0};
  16653. std::atomic_uint count{0};
  16654. std::unique_ptr<TaskQueue> task_queue{
  16655. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16656. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16657. if (task_queue->enqueue(
  16658. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16659. queued_count++;
  16660. }
  16661. }
  16662. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16663. task_queue->shutdown();
  16664. #else
  16665. EXPECT_NO_THROW(task_queue->shutdown());
  16666. #endif
  16667. EXPECT_EQ(queued_count, count.load());
  16668. EXPECT_TRUE(queued_count <= number_of_tasks);
  16669. EXPECT_TRUE(queued_count >= qlimit);
  16670. }
  16671. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16672. // Use a short idle timeout so a dynamic thread spawns, times out and
  16673. // exits during the test, and the pool keeps working afterwards.
  16674. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16675. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16676. /*idle_timeout_sec=*/1}};
  16677. std::atomic_uint count{0};
  16678. std::condition_variable cv;
  16679. std::mutex mtx;
  16680. bool release = false;
  16681. // Block the base thread so the second task spawns a dynamic thread.
  16682. EXPECT_TRUE(task_queue->enqueue([&] {
  16683. std::unique_lock<std::mutex> lock(mtx);
  16684. while (!release) {
  16685. cv.wait(lock);
  16686. }
  16687. count++;
  16688. }));
  16689. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16690. // Let the dynamic thread finish its task and exceed the idle timeout.
  16691. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16692. {
  16693. std::unique_lock<std::mutex> lock(mtx);
  16694. release = true;
  16695. }
  16696. cv.notify_all();
  16697. // The pool must still accept and run tasks after the dynamic thread exited.
  16698. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16699. task_queue->shutdown();
  16700. EXPECT_EQ(3u, count.load());
  16701. }
  16702. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16703. static constexpr size_t number_of_tasks{32};
  16704. std::unique_ptr<TaskQueue> task_queue{
  16705. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16706. // Let the base threads go idle so the burst below finds them waiting.
  16707. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16708. std::mutex mtx;
  16709. std::condition_variable cv;
  16710. size_t running = 0;
  16711. bool release = false;
  16712. for (size_t i = 0; i < number_of_tasks; i++) {
  16713. EXPECT_TRUE(task_queue->enqueue([&] {
  16714. std::unique_lock<std::mutex> lock(mtx);
  16715. running++;
  16716. cv.notify_all();
  16717. cv.wait(lock, [&] { return release; });
  16718. }));
  16719. }
  16720. {
  16721. std::unique_lock<std::mutex> lock(mtx);
  16722. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16723. [&] { return running == number_of_tasks; }));
  16724. release = true;
  16725. }
  16726. cv.notify_all();
  16727. task_queue->shutdown();
  16728. }
  16729. TEST(TaskQueueTest, MaxQueuedRequests) {
  16730. static constexpr unsigned int qlimit{3};
  16731. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16732. std::condition_variable sem_cv;
  16733. std::mutex sem_mtx;
  16734. int credits = 0;
  16735. bool queued;
  16736. /* Fill up the queue with tasks that will block until we give them credits to
  16737. * complete. */
  16738. for (unsigned int n = 0; n <= qlimit;) {
  16739. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16740. std::unique_lock<std::mutex> lock(sem_mtx);
  16741. while (credits <= 0) {
  16742. sem_cv.wait(lock);
  16743. }
  16744. /* Consume the credit and signal the test code if they are all gone. */
  16745. if (--credits == 0) { sem_cv.notify_one(); }
  16746. });
  16747. if (n < qlimit) {
  16748. /* The first qlimit enqueues must succeed. */
  16749. EXPECT_TRUE(queued);
  16750. } else {
  16751. /* The last one will succeed only when the worker thread
  16752. * starts and dequeues the first blocking task. Although
  16753. * not necessary for the correctness of this test, we sleep for
  16754. * a short while to avoid busy waiting. */
  16755. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16756. }
  16757. if (queued) { n++; }
  16758. }
  16759. /* Further enqueues must fail since the queue is full. */
  16760. for (auto i = 0; i < 4; i++) {
  16761. queued = task_queue->enqueue([] {});
  16762. EXPECT_FALSE(queued);
  16763. }
  16764. /* Give the credits to allow the previous tasks to complete. */
  16765. {
  16766. std::unique_lock<std::mutex> lock(sem_mtx);
  16767. credits += qlimit + 1;
  16768. }
  16769. sem_cv.notify_all();
  16770. /* Wait for all the credits to be consumed. */
  16771. {
  16772. std::unique_lock<std::mutex> lock(sem_mtx);
  16773. while (credits > 0) {
  16774. sem_cv.wait(lock);
  16775. }
  16776. }
  16777. /* Check that we are able again to enqueue at least qlimit tasks. */
  16778. for (unsigned int i = 0; i < qlimit; i++) {
  16779. queued = task_queue->enqueue([] {});
  16780. EXPECT_TRUE(queued);
  16781. }
  16782. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16783. task_queue->shutdown();
  16784. #else
  16785. EXPECT_NO_THROW(task_queue->shutdown());
  16786. #endif
  16787. }
  16788. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16789. Server svr;
  16790. std::string method;
  16791. std::string body;
  16792. auto has_content_length = false;
  16793. auto has_transfer_encoding = false;
  16794. std::atomic<int> bad_requests{0};
  16795. // Leftover body bytes get parsed as a malformed request and answered with
  16796. // 400
  16797. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16798. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16799. });
  16800. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16801. res.set_redirect("/down", StatusCode::SeeOther_303);
  16802. });
  16803. svr.Get("/down", [&](const Request &req, Response &res) {
  16804. method = req.method;
  16805. body = req.body;
  16806. has_content_length = req.has_header("Content-Length");
  16807. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16808. res.set_content("ok", "text/plain");
  16809. });
  16810. auto port = svr.bind_to_any_port(HOST);
  16811. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16812. auto se = detail::scope_exit([&] {
  16813. svr.stop();
  16814. thread.join();
  16815. ASSERT_FALSE(svr.is_running());
  16816. });
  16817. svr.wait_until_ready();
  16818. const std::string payload = "SECRET-BODY";
  16819. auto check = [&](Client &cli, const Result &res) {
  16820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16821. EXPECT_EQ(StatusCode::OK_200, res->status);
  16822. EXPECT_EQ("ok", res->body);
  16823. EXPECT_EQ("GET", method);
  16824. EXPECT_TRUE(body.empty());
  16825. EXPECT_FALSE(has_content_length);
  16826. EXPECT_FALSE(has_transfer_encoding);
  16827. // Nothing of the original body may be left on the connection
  16828. auto res2 = cli.Get("/down");
  16829. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16830. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16831. EXPECT_EQ("ok", res2->body);
  16832. EXPECT_EQ(0, bad_requests);
  16833. };
  16834. // With content length
  16835. {
  16836. Client cli(HOST, port);
  16837. cli.set_keep_alive(true);
  16838. cli.set_follow_location(true);
  16839. auto res = cli.Post(
  16840. "/up", payload.size(),
  16841. [&](size_t offset, size_t length, DataSink &sink) {
  16842. return sink.write(payload.data() + offset, length);
  16843. },
  16844. "text/plain");
  16845. check(cli, res);
  16846. }
  16847. // Without content length (chunked)
  16848. {
  16849. Client cli(HOST, port);
  16850. cli.set_keep_alive(true);
  16851. cli.set_follow_location(true);
  16852. auto res = cli.Post(
  16853. "/up",
  16854. [&](size_t /*offset*/, DataSink &sink) {
  16855. sink.write(payload.data(), payload.size());
  16856. sink.done();
  16857. return true;
  16858. },
  16859. "text/plain");
  16860. check(cli, res);
  16861. }
  16862. }
  16863. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16864. Server svr;
  16865. std::string target;
  16866. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16867. // Echo the still-encoded name back in the Location
  16868. const std::string prefix = "/start/";
  16869. res.status = StatusCode::Found_302;
  16870. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16871. });
  16872. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16873. target = req.target;
  16874. res.set_content("ok", "text/plain");
  16875. });
  16876. auto port = svr.bind_to_any_port(HOST);
  16877. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16878. auto se = detail::scope_exit([&] {
  16879. svr.stop();
  16880. thread.join();
  16881. ASSERT_FALSE(svr.is_running());
  16882. });
  16883. svr.wait_until_ready();
  16884. // Decoding the Location path would turn the first four into a path
  16885. // separator, a query delimiter, a fragment delimiter and a different
  16886. // percent-encoded octet. The rest must keep reaching the server as they are.
  16887. const std::vector<std::string> names = {
  16888. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16889. };
  16890. for (auto path_encode : {true, false}) {
  16891. Client cli(HOST, port);
  16892. cli.set_follow_location(true);
  16893. cli.set_path_encode(path_encode);
  16894. for (const auto &name : names) {
  16895. target.clear();
  16896. auto res = cli.Get("/start/" + name);
  16897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16898. EXPECT_EQ(StatusCode::OK_200, res->status);
  16899. EXPECT_EQ("/dest/" + name, target);
  16900. }
  16901. }
  16902. }
  16903. TEST(RedirectTest, NotModifiedIsReturned) {
  16904. Server svr;
  16905. svr.Get("/cached", [](const Request &, Response &res) {
  16906. res.status = StatusCode::NotModified_304;
  16907. });
  16908. auto port = svr.bind_to_any_port(HOST);
  16909. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16910. auto se = detail::scope_exit([&] {
  16911. svr.stop();
  16912. thread.join();
  16913. ASSERT_FALSE(svr.is_running());
  16914. });
  16915. svr.wait_until_ready();
  16916. Client cli(HOST, port);
  16917. cli.set_follow_location(true);
  16918. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16920. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16921. }
  16922. TEST(RedirectTest, NoLocationIsReturned) {
  16923. Server svr;
  16924. svr.Get("/no-location", [](const Request &, Response &res) {
  16925. res.status = StatusCode::Found_302;
  16926. res.set_content("no location", "text/plain");
  16927. });
  16928. auto port = svr.bind_to_any_port(HOST);
  16929. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16930. auto se = detail::scope_exit([&] {
  16931. svr.stop();
  16932. thread.join();
  16933. ASSERT_FALSE(svr.is_running());
  16934. });
  16935. svr.wait_until_ready();
  16936. Client cli(HOST, port);
  16937. cli.set_follow_location(true);
  16938. auto res = cli.Get("/no-location");
  16939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16940. EXPECT_EQ(StatusCode::Found_302, res->status);
  16941. EXPECT_EQ("no location", res->body);
  16942. // The callbacks see the body of the response that is returned
  16943. auto handler_called = false;
  16944. auto progress_called = false;
  16945. std::string body;
  16946. auto res2 = cli.Get(
  16947. "/no-location",
  16948. [&](const Response &) {
  16949. handler_called = true;
  16950. return true;
  16951. },
  16952. [&](const char *data, size_t data_length) {
  16953. body.append(data, data_length);
  16954. return true;
  16955. },
  16956. [&](size_t, size_t) {
  16957. progress_called = true;
  16958. return true;
  16959. });
  16960. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16961. EXPECT_EQ(StatusCode::Found_302, res2->status);
  16962. EXPECT_TRUE(handler_called);
  16963. EXPECT_TRUE(progress_called);
  16964. EXPECT_EQ("no location", body);
  16965. }
  16966. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16967. Server svr;
  16968. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16969. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16970. });
  16971. svr.Get("/hello", [](const Request &req, Response &res) {
  16972. res.set_content(req.get_param_value("key"), "text/plain");
  16973. });
  16974. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16975. auto se = detail::scope_exit([&] {
  16976. svr.stop();
  16977. thread.join();
  16978. ASSERT_FALSE(svr.is_running());
  16979. });
  16980. svr.wait_until_ready();
  16981. {
  16982. Client cli(HOST, PORT);
  16983. cli.set_follow_location(true);
  16984. auto res = cli.Get("/");
  16985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16986. EXPECT_EQ(StatusCode::OK_200, res->status);
  16987. EXPECT_EQ("val&key2=val2", res->body);
  16988. }
  16989. }
  16990. #endif
  16991. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16992. Server svr;
  16993. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16994. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16995. });
  16996. svr.Get("/hello", [](const Request &req, Response &res) {
  16997. res.set_content(req.get_param_value("key"), "text/plain");
  16998. });
  16999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17000. auto se = detail::scope_exit([&] {
  17001. svr.stop();
  17002. thread.join();
  17003. ASSERT_FALSE(svr.is_running());
  17004. });
  17005. svr.wait_until_ready();
  17006. {
  17007. Client cli(HOST, PORT);
  17008. cli.set_follow_location(true);
  17009. auto res = cli.Get("/");
  17010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17011. EXPECT_EQ(StatusCode::OK_200, res->status);
  17012. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17013. }
  17014. }
  17015. TEST(RedirectTest, RedirectWithPlusInPath) {
  17016. Server svr;
  17017. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17018. res.set_redirect("/a+b");
  17019. });
  17020. // Route pattern uses regex; escape + as \\+
  17021. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17022. res.set_content(req.path, "text/plain");
  17023. });
  17024. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17025. auto se = detail::scope_exit([&] {
  17026. svr.stop();
  17027. thread.join();
  17028. ASSERT_FALSE(svr.is_running());
  17029. });
  17030. svr.wait_until_ready();
  17031. {
  17032. Client cli(HOST, PORT);
  17033. cli.set_follow_location(true);
  17034. auto res = cli.Get("/");
  17035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17036. EXPECT_EQ(StatusCode::OK_200, res->status);
  17037. EXPECT_EQ("/a+b", res->body);
  17038. }
  17039. }
  17040. TEST(RedirectTest, ResolveRelativeLocation) {
  17041. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17042. const std::vector<std::pair<std::string, std::string>> cases = {
  17043. {"g", "/b/c/g"},
  17044. {"./g", "/b/c/g"},
  17045. {"g/", "/b/c/g/"},
  17046. {"?y", "/b/c/d;p?y"},
  17047. {"g?y", "/b/c/g?y"},
  17048. {"#s", "/b/c/d;p?q#s"},
  17049. {"g#s", "/b/c/g#s"},
  17050. {"g?y#s", "/b/c/g?y#s"},
  17051. {";x", "/b/c/;x"},
  17052. {"g;x", "/b/c/g;x"},
  17053. {".", "/b/c/"},
  17054. {"./", "/b/c/"},
  17055. {"..", "/b/"},
  17056. {"../", "/b/"},
  17057. {"../g", "/b/g"},
  17058. {"../..", "/"},
  17059. {"../../", "/"},
  17060. {"../../g", "/g"},
  17061. {"../../../g", "/g"},
  17062. {"g.", "/b/c/g."},
  17063. {".g", "/b/c/.g"},
  17064. {"g..", "/b/c/g.."},
  17065. {"..g", "/b/c/..g"},
  17066. {"./../g", "/b/g"},
  17067. {"./g/.", "/b/c/g/"},
  17068. {"g/./h", "/b/c/g/h"},
  17069. {"g/../h", "/b/c/h"},
  17070. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17071. {"g;x=1/../y", "/b/c/y"},
  17072. {"g?y/./x", "/b/c/g?y/./x"},
  17073. {"g#s/../x", "/b/c/g#s/../x"},
  17074. // Not relative-path references, so left for parse_url.
  17075. {"/g", "/g"},
  17076. {"//g", "//g"},
  17077. {"http://g/x", "http://g/x"},
  17078. {"g:h", "g:h"},
  17079. };
  17080. for (const auto &c : cases) {
  17081. EXPECT_EQ(c.second,
  17082. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17083. << c.first;
  17084. }
  17085. }
  17086. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17087. Server svr;
  17088. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17089. res.set_redirect(req.get_param_value("to"));
  17090. });
  17091. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17092. res.set_content(req.target, "text/plain");
  17093. });
  17094. svr.Get("/other", [](const Request &req, Response &res) {
  17095. res.set_content(req.target, "text/plain");
  17096. });
  17097. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17098. auto se = detail::scope_exit([&] {
  17099. svr.stop();
  17100. thread.join();
  17101. ASSERT_FALSE(svr.is_running());
  17102. });
  17103. svr.wait_until_ready();
  17104. const std::vector<std::pair<std::string, std::string>> cases = {
  17105. {"next", "/dir/next"},
  17106. {"./next?x=1", "/dir/next?x=1"},
  17107. {"../other", "/other"},
  17108. };
  17109. for (const auto &c : cases) {
  17110. Client cli(HOST, PORT);
  17111. cli.set_follow_location(true);
  17112. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17113. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17114. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17115. EXPECT_EQ(c.second, res->body) << c.first;
  17116. }
  17117. }
  17118. #ifdef CPPHTTPLIB_SSL_ENABLED
  17119. TEST(RedirectTest, Issue2185_Online) {
  17120. SSLClient client("github.com");
  17121. client.set_follow_location(true);
  17122. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17123. "Coollab-Windows.zip");
  17124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17125. EXPECT_EQ(StatusCode::OK_200, res->status);
  17126. EXPECT_EQ(9920427U, res->body.size());
  17127. }
  17128. #endif
  17129. TEST(VulnerabilityTest, CRLFInjection) {
  17130. Server svr;
  17131. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17132. res.set_content("Hello 1", "text/plain");
  17133. });
  17134. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17135. res.set_content("Hello 2", "text/plain");
  17136. });
  17137. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17138. res.set_content("Hello 3", "text/plain");
  17139. });
  17140. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17141. res.set_content("Hello 4", "text/plain");
  17142. });
  17143. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17144. for (const auto &x : req.headers) {
  17145. auto key = x.first;
  17146. EXPECT_STRNE("evil", key.c_str());
  17147. }
  17148. });
  17149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17150. auto se = detail::scope_exit([&] {
  17151. svr.stop();
  17152. thread.join();
  17153. ASSERT_FALSE(svr.is_running());
  17154. });
  17155. svr.wait_until_ready();
  17156. {
  17157. Client cli(HOST, PORT);
  17158. cli.Post("/test1", "A=B",
  17159. "application/x-www-form-urlencoded\r\nevil: hello1");
  17160. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17161. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17162. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17163. }
  17164. }
  17165. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17166. auto server_thread = std::thread([] {
  17167. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17168. default_socket_options(srv);
  17169. sockaddr_in addr{};
  17170. addr.sin_family = AF_INET;
  17171. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17172. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17173. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17174. ::listen(srv, 1);
  17175. sockaddr_in cli_addr{};
  17176. socklen_t cli_len = sizeof(cli_addr);
  17177. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17178. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17179. std::string buf_all;
  17180. char buf[2048];
  17181. ssize_t n;
  17182. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17183. buf_all.append(buf, static_cast<size_t>(n));
  17184. size_t pos;
  17185. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17186. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17187. auto e = request_block.find("\r\n");
  17188. if (e != std::string::npos) {
  17189. auto request_line = request_block.substr(0, e);
  17190. std::string msg =
  17191. "CRLF injection detected in request line: '" + request_line + "'";
  17192. EXPECT_FALSE(true) << msg;
  17193. }
  17194. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17195. ::send(cli,
  17196. #ifdef _WIN32
  17197. static_cast<const char *>(resp.c_str()),
  17198. static_cast<int>(resp.size()),
  17199. #else
  17200. resp.c_str(), resp.size(),
  17201. #endif
  17202. 0);
  17203. buf_all.erase(0, pos + 4);
  17204. }
  17205. }
  17206. detail::close_socket(cli);
  17207. detail::close_socket(srv);
  17208. });
  17209. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17210. auto cli = Client("127.0.0.1", PORT + 1);
  17211. auto headers = Headers{
  17212. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17213. {"Connection", "keep-alive"}};
  17214. auto res = cli.Get("/hi", headers);
  17215. EXPECT_FALSE(res);
  17216. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17217. server_thread.join();
  17218. }
  17219. // A request rejected before any byte reaches the socket must fail right away
  17220. // instead of waiting for a response the server will never send.
  17221. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17222. // The kernel completes the TCP handshake from the listen backlog, so the
  17223. // client connects, but nothing ever reads, responds or closes.
  17224. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17225. default_socket_options(srv);
  17226. sockaddr_in addr{};
  17227. addr.sin_family = AF_INET;
  17228. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17229. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17230. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17231. ASSERT_EQ(0, ::listen(srv, 8));
  17232. auto cli = Client("127.0.0.1", PORT + 1);
  17233. cli.set_read_timeout(10, 0);
  17234. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17235. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17236. std::chrono::steady_clock::now() - start)
  17237. .count();
  17238. };
  17239. {
  17240. Request req;
  17241. req.method = "GE T";
  17242. req.path = "/";
  17243. auto start = std::chrono::steady_clock::now();
  17244. auto res = cli.send(req);
  17245. EXPECT_FALSE(res);
  17246. EXPECT_EQ(Error::Write, res.error());
  17247. EXPECT_LT(elapsed_ms(start), 1000);
  17248. }
  17249. {
  17250. auto start = std::chrono::steady_clock::now();
  17251. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17252. EXPECT_FALSE(res);
  17253. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17254. EXPECT_LT(elapsed_ms(start), 1000);
  17255. }
  17256. EXPECT_FALSE(cli.is_socket_open());
  17257. detail::close_socket(srv);
  17258. }
  17259. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17260. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17261. default_socket_options(srv);
  17262. sockaddr_in addr{};
  17263. addr.sin_family = AF_INET;
  17264. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17265. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17266. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17267. ASSERT_EQ(0, ::listen(srv, 1));
  17268. std::string received;
  17269. auto server_thread = std::thread([&] {
  17270. auto sock = ::accept(srv, nullptr, nullptr);
  17271. if (sock == INVALID_SOCKET) { return; }
  17272. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17273. char buf[2048];
  17274. ssize_t n;
  17275. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17276. received.append(buf, static_cast<size_t>(n));
  17277. }
  17278. detail::close_socket(sock);
  17279. });
  17280. {
  17281. auto cli = Client("127.0.0.1", PORT + 1);
  17282. // "Z" sorts after the default headers, so writing straight to the socket
  17283. // would have sent the request line and those headers before the rejection.
  17284. auto handle =
  17285. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17286. EXPECT_FALSE(handle.is_valid());
  17287. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17288. }
  17289. server_thread.join();
  17290. detail::close_socket(srv);
  17291. EXPECT_TRUE(received.empty()) << received;
  17292. }
  17293. TEST(PathParamsTest, StaticMatch) {
  17294. const auto pattern = "/users/all";
  17295. detail::PathParamsMatcher matcher(pattern);
  17296. Request request;
  17297. request.path = "/users/all";
  17298. ASSERT_TRUE(matcher.match(request));
  17299. std::unordered_map<std::string, std::string> expected_params = {};
  17300. EXPECT_EQ(request.path_params, expected_params);
  17301. }
  17302. TEST(PathParamsTest, StaticMismatch) {
  17303. const auto pattern = "/users/all";
  17304. detail::PathParamsMatcher matcher(pattern);
  17305. Request request;
  17306. request.path = "/users/1";
  17307. ASSERT_FALSE(matcher.match(request));
  17308. }
  17309. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17310. const auto pattern = "/users/:id/subscriptions";
  17311. detail::PathParamsMatcher matcher(pattern);
  17312. Request request;
  17313. request.path = "/users/42/subscriptions";
  17314. ASSERT_TRUE(matcher.match(request));
  17315. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17316. EXPECT_EQ(request.path_params, expected_params);
  17317. }
  17318. TEST(PathParamsTest, SingleParamInTheEnd) {
  17319. const auto pattern = "/users/:id";
  17320. detail::PathParamsMatcher matcher(pattern);
  17321. Request request;
  17322. request.path = "/users/24";
  17323. ASSERT_TRUE(matcher.match(request));
  17324. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17325. EXPECT_EQ(request.path_params, expected_params);
  17326. }
  17327. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17328. const auto pattern = "/users/:id/";
  17329. detail::PathParamsMatcher matcher(pattern);
  17330. Request request;
  17331. request.path = "/users/42/";
  17332. ASSERT_TRUE(matcher.match(request));
  17333. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17334. EXPECT_EQ(request.path_params, expected_params);
  17335. }
  17336. TEST(PathParamsTest, EmptyParam) {
  17337. const auto pattern = "/users/:id/";
  17338. detail::PathParamsMatcher matcher(pattern);
  17339. Request request;
  17340. request.path = "/users//";
  17341. ASSERT_TRUE(matcher.match(request));
  17342. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17343. EXPECT_EQ(request.path_params, expected_params);
  17344. }
  17345. TEST(PathParamsTest, FragmentMismatch) {
  17346. const auto pattern = "/users/:id/";
  17347. detail::PathParamsMatcher matcher(pattern);
  17348. Request request;
  17349. request.path = "/admins/24/";
  17350. ASSERT_FALSE(matcher.match(request));
  17351. }
  17352. TEST(PathParamsTest, ExtraFragments) {
  17353. const auto pattern = "/users/:id";
  17354. detail::PathParamsMatcher matcher(pattern);
  17355. Request request;
  17356. request.path = "/users/42/subscriptions";
  17357. ASSERT_FALSE(matcher.match(request));
  17358. }
  17359. TEST(PathParamsTest, MissingTrailingParam) {
  17360. const auto pattern = "/users/:id";
  17361. detail::PathParamsMatcher matcher(pattern);
  17362. Request request;
  17363. request.path = "/users";
  17364. ASSERT_FALSE(matcher.match(request));
  17365. }
  17366. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17367. const auto pattern = "/users/:id/subscriptions";
  17368. detail::PathParamsMatcher matcher(pattern);
  17369. Request request;
  17370. request.path = "/users/subscriptions";
  17371. ASSERT_FALSE(matcher.match(request));
  17372. }
  17373. TEST(PathParamsTest, MultipleParams) {
  17374. const auto pattern = "/users/:userid/subscriptions/:subid";
  17375. detail::PathParamsMatcher matcher(pattern);
  17376. Request request;
  17377. request.path = "/users/42/subscriptions/2";
  17378. ASSERT_TRUE(matcher.match(request));
  17379. std::unordered_map<std::string, std::string> expected_params = {
  17380. {"userid", "42"}, {"subid", "2"}};
  17381. EXPECT_EQ(request.path_params, expected_params);
  17382. }
  17383. TEST(PathParamsTest, SequenceOfParams) {
  17384. const auto pattern = "/values/:x/:y/:z";
  17385. detail::PathParamsMatcher matcher(pattern);
  17386. Request request;
  17387. request.path = "/values/1/2/3";
  17388. ASSERT_TRUE(matcher.match(request));
  17389. std::unordered_map<std::string, std::string> expected_params = {
  17390. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17391. EXPECT_EQ(request.path_params, expected_params);
  17392. }
  17393. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17394. const auto pattern = "/prefix:suffix";
  17395. detail::PathParamsMatcher matcher(pattern);
  17396. Request request;
  17397. request.path = "/prefix:suffix";
  17398. ASSERT_TRUE(matcher.match(request));
  17399. const std::unordered_map<std::string, std::string> expected_params = {};
  17400. EXPECT_EQ(request.path_params, expected_params);
  17401. }
  17402. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17403. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17404. // calling thread's stack on a long enough path for a quantified pattern;
  17405. // RegexMatcher must refuse to run regex matching on paths beyond
  17406. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17407. detail::RegexMatcher matcher("/files/(.*)");
  17408. Request within_limit;
  17409. within_limit.path = "/files/" + std::string(10, 'A');
  17410. EXPECT_TRUE(matcher.match(within_limit));
  17411. Request over_limit;
  17412. over_limit.path =
  17413. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17414. EXPECT_FALSE(matcher.match(over_limit));
  17415. }
  17416. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17417. Server svr;
  17418. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17419. res.set_content("ok", "text/plain");
  17420. });
  17421. auto port = svr.bind_to_any_port(HOST);
  17422. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17423. auto se = detail::scope_exit([&] {
  17424. svr.stop();
  17425. thread.join();
  17426. ASSERT_FALSE(svr.is_running());
  17427. });
  17428. svr.wait_until_ready();
  17429. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17430. // request URI limit; this used to be able to crash the process.
  17431. std::string path =
  17432. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17433. std::string req = "GET " + path +
  17434. " HTTP/1.1\r\n"
  17435. "Host: " +
  17436. std::string(HOST) + ":" + std::to_string(port) +
  17437. "\r\n"
  17438. "Connection: close\r\n"
  17439. "\r\n";
  17440. std::string response;
  17441. ASSERT_TRUE(send_request(5, req, &response, port));
  17442. EXPECT_NE(std::string::npos, response.find("404"));
  17443. }
  17444. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17445. Server svr;
  17446. auto handler = [](const Request & /*req*/, Response &res) {
  17447. res.set_content("hit", "text/plain");
  17448. };
  17449. // No regex metacharacter, so this one is compared literally
  17450. svr.Get("/literal/route", handler);
  17451. // '.' is a regex metacharacter, so this one must keep regex semantics
  17452. svr.Get("/a.c", handler);
  17453. auto port = svr.bind_to_any_port(HOST);
  17454. std::thread t([&]() { svr.listen_after_bind(); });
  17455. auto se = detail::scope_exit([&] {
  17456. svr.stop();
  17457. t.join();
  17458. ASSERT_FALSE(svr.is_running());
  17459. });
  17460. svr.wait_until_ready();
  17461. Client cli(HOST, port);
  17462. struct {
  17463. const char *path;
  17464. int status;
  17465. } cases[] = {
  17466. {"/literal/route", StatusCode::OK_200},
  17467. {"/literal/routes", StatusCode::NotFound_404},
  17468. {"/literal/rout", StatusCode::NotFound_404},
  17469. {"/abc", StatusCode::OK_200},
  17470. {"/a.c", StatusCode::OK_200},
  17471. };
  17472. for (const auto &x : cases) {
  17473. auto res = cli.Get(x.path);
  17474. ASSERT_TRUE(res) << x.path;
  17475. EXPECT_EQ(x.status, res->status) << x.path;
  17476. }
  17477. }
  17478. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17479. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17480. // from exhausting the stack, so it must only constrain routes that actually
  17481. // run a regular expression. A literal route is matched by comparison and
  17482. // stays usable at any length.
  17483. Server svr;
  17484. const std::string pattern =
  17485. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17486. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17487. res.set_content("hit", "text/plain");
  17488. });
  17489. auto port = svr.bind_to_any_port(HOST);
  17490. std::thread t([&]() { svr.listen_after_bind(); });
  17491. auto se = detail::scope_exit([&] {
  17492. svr.stop();
  17493. t.join();
  17494. ASSERT_FALSE(svr.is_running());
  17495. });
  17496. svr.wait_until_ready();
  17497. Client cli(HOST, port);
  17498. auto res = cli.Get(pattern);
  17499. ASSERT_TRUE(res);
  17500. EXPECT_EQ(StatusCode::OK_200, res->status);
  17501. }
  17502. TEST(ParseUrlTest, VariousPatterns) {
  17503. {
  17504. detail::UrlComponents uc;
  17505. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17506. EXPECT_EQ("http", uc.scheme);
  17507. EXPECT_EQ("example.com", uc.host);
  17508. EXPECT_EQ("8080", uc.port);
  17509. EXPECT_EQ("/path", uc.path);
  17510. EXPECT_EQ("?q=1", uc.query);
  17511. }
  17512. {
  17513. detail::UrlComponents uc;
  17514. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17515. EXPECT_EQ("https", uc.scheme);
  17516. EXPECT_EQ("example.com", uc.host);
  17517. EXPECT_TRUE(uc.port.empty());
  17518. EXPECT_EQ("/path", uc.path);
  17519. }
  17520. {
  17521. detail::UrlComponents uc;
  17522. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17523. EXPECT_EQ("::1", uc.host);
  17524. EXPECT_EQ("8080", uc.port);
  17525. EXPECT_EQ("/path", uc.path);
  17526. }
  17527. {
  17528. detail::UrlComponents uc;
  17529. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17530. }
  17531. {
  17532. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17533. // the path while the connection still targets the bracketed host.
  17534. detail::UrlComponents uc;
  17535. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17536. }
  17537. {
  17538. detail::UrlComponents uc;
  17539. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17540. }
  17541. {
  17542. detail::UrlComponents uc;
  17543. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17544. EXPECT_EQ("::1", uc.host);
  17545. EXPECT_TRUE(uc.port.empty());
  17546. EXPECT_EQ("/path", uc.path);
  17547. }
  17548. {
  17549. detail::UrlComponents uc;
  17550. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17551. EXPECT_TRUE(uc.scheme.empty());
  17552. EXPECT_EQ("example.com", uc.host);
  17553. EXPECT_EQ("/path", uc.path);
  17554. EXPECT_EQ("?q=1", uc.query);
  17555. }
  17556. {
  17557. detail::UrlComponents uc;
  17558. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17559. EXPECT_TRUE(uc.host.empty());
  17560. EXPECT_EQ("/path", uc.path);
  17561. EXPECT_EQ("?q=1", uc.query);
  17562. }
  17563. {
  17564. detail::UrlComponents uc;
  17565. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17566. EXPECT_EQ("example.com", uc.host);
  17567. EXPECT_EQ("8080", uc.port);
  17568. }
  17569. {
  17570. // Unix socket path — must not be parsed as host
  17571. detail::UrlComponents uc;
  17572. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17573. EXPECT_TRUE(uc.host.empty());
  17574. }
  17575. {
  17576. detail::UrlComponents uc;
  17577. ASSERT_TRUE(detail::parse_url("", uc));
  17578. EXPECT_TRUE(uc.host.empty());
  17579. EXPECT_TRUE(uc.path.empty());
  17580. }
  17581. {
  17582. detail::UrlComponents uc;
  17583. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17584. }
  17585. {
  17586. detail::UrlComponents uc;
  17587. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17588. }
  17589. {
  17590. // Accepted by parse_url; callers restrict to http/https
  17591. detail::UrlComponents uc;
  17592. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17593. EXPECT_EQ("ftp", uc.scheme);
  17594. }
  17595. {
  17596. detail::UrlComponents uc;
  17597. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17598. }
  17599. {
  17600. detail::UrlComponents uc;
  17601. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17602. }
  17603. }
  17604. TEST(ParseUrlTest, FragmentHandling) {
  17605. {
  17606. detail::UrlComponents uc;
  17607. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17608. EXPECT_EQ("/path", uc.path);
  17609. EXPECT_TRUE(uc.query.empty());
  17610. }
  17611. {
  17612. detail::UrlComponents uc;
  17613. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17614. EXPECT_TRUE(uc.path.empty());
  17615. EXPECT_TRUE(uc.query.empty());
  17616. }
  17617. }
  17618. TEST(ParseUrlTest, UserinfoHandling) {
  17619. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17620. // parsers would see evil.com as the host.
  17621. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17622. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17623. for (auto url : urls) {
  17624. detail::UrlComponents uc;
  17625. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17626. }
  17627. }
  17628. TEST(ParseUrlTest, IPv6EdgeCases) {
  17629. {
  17630. detail::UrlComponents uc;
  17631. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17632. EXPECT_TRUE(uc.scheme.empty());
  17633. EXPECT_EQ("::1", uc.host);
  17634. EXPECT_EQ("8080", uc.port);
  17635. }
  17636. {
  17637. // Zone ID '%25' is not in [a-fA-F0-9:]
  17638. detail::UrlComponents uc;
  17639. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17640. }
  17641. }
  17642. TEST(ParseUrlTest, SchemeEdgeCases) {
  17643. {
  17644. detail::UrlComponents uc;
  17645. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17646. }
  17647. {
  17648. detail::UrlComponents uc;
  17649. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17650. }
  17651. {
  17652. detail::UrlComponents uc;
  17653. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17654. }
  17655. }
  17656. TEST(ParseUrlTest, PortEdgeCases) {
  17657. {
  17658. detail::UrlComponents uc;
  17659. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17660. EXPECT_TRUE(uc.port.empty());
  17661. EXPECT_EQ("/path", uc.path);
  17662. }
  17663. {
  17664. // parse_url accepts any port string; validation is done by parse_port
  17665. detail::UrlComponents uc;
  17666. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17667. EXPECT_EQ("abc", uc.port);
  17668. }
  17669. }
  17670. TEST(ParseUrlTest, WebSocketPatterns) {
  17671. {
  17672. detail::UrlComponents uc;
  17673. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17674. EXPECT_EQ("ws", uc.scheme);
  17675. EXPECT_EQ("echo.example.com", uc.host);
  17676. EXPECT_EQ("8080", uc.port);
  17677. EXPECT_EQ("/ws", uc.path);
  17678. }
  17679. {
  17680. detail::UrlComponents uc;
  17681. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17682. EXPECT_EQ("wss", uc.scheme);
  17683. EXPECT_EQ("echo.example.com", uc.host);
  17684. EXPECT_TRUE(uc.port.empty());
  17685. EXPECT_EQ("/ws", uc.path);
  17686. }
  17687. }
  17688. TEST(ParseUrlTest, QueryOnly) {
  17689. detail::UrlComponents uc;
  17690. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17691. EXPECT_TRUE(uc.host.empty());
  17692. EXPECT_TRUE(uc.path.empty());
  17693. EXPECT_EQ("?q=1&r=2", uc.query);
  17694. }
  17695. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17696. detail::UrlComponents uc;
  17697. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17698. EXPECT_TRUE(uc.scheme.empty());
  17699. EXPECT_EQ("example.com", uc.host);
  17700. EXPECT_EQ("443", uc.port);
  17701. EXPECT_EQ("/path", uc.path);
  17702. }
  17703. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17704. // If ipv6 regex working, regex match codepath is taken.
  17705. // else port will default to 80 in Client impl
  17706. int clientImplMagicPort = 80;
  17707. int port = 4321;
  17708. // above ports must be different to avoid false negative
  17709. EXPECT_NE(clientImplMagicPort, port);
  17710. std::string ipV6TestURL = "http://[ff06::c3]";
  17711. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17712. CLIENT_PRIVATE_KEY_FILE);
  17713. EXPECT_EQ(cli.port(), port);
  17714. }
  17715. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17716. auto file_path = "./www/dir/index.html";
  17717. auto dir_path = "./www/dir";
  17718. detail::FileStat stat_file(file_path);
  17719. EXPECT_TRUE(stat_file.is_file());
  17720. EXPECT_FALSE(stat_file.is_dir());
  17721. detail::FileStat stat_dir(dir_path);
  17722. EXPECT_FALSE(stat_dir.is_file());
  17723. EXPECT_TRUE(stat_dir.is_dir());
  17724. }
  17725. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17726. // IPv4 with default HTTP port (80)
  17727. EXPECT_EQ("example.com",
  17728. detail::make_host_and_port_string("example.com", 80, false));
  17729. // IPv4 with default HTTPS port (443)
  17730. EXPECT_EQ("example.com",
  17731. detail::make_host_and_port_string("example.com", 443, true));
  17732. // IPv4 with non-default HTTP port
  17733. EXPECT_EQ("example.com:8080",
  17734. detail::make_host_and_port_string("example.com", 8080, false));
  17735. // IPv4 with non-default HTTPS port
  17736. EXPECT_EQ("example.com:8443",
  17737. detail::make_host_and_port_string("example.com", 8443, true));
  17738. // IPv6 with default HTTP port (80)
  17739. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17740. // IPv6 with default HTTPS port (443)
  17741. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17742. // IPv6 with non-default HTTP port
  17743. EXPECT_EQ("[::1]:8080",
  17744. detail::make_host_and_port_string("::1", 8080, false));
  17745. // IPv6 with non-default HTTPS port
  17746. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17747. // IPv6 full address with default port
  17748. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17749. detail::make_host_and_port_string(
  17750. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17751. // IPv6 full address with non-default port
  17752. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17753. detail::make_host_and_port_string(
  17754. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17755. // IPv6 localhost with non-default port
  17756. EXPECT_EQ("[::1]:3000",
  17757. detail::make_host_and_port_string("::1", 3000, false));
  17758. // IPv6 with zone ID (link-local address) with default port
  17759. EXPECT_EQ("[fe80::1%eth0]",
  17760. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17761. // IPv6 with zone ID (link-local address) with non-default port
  17762. EXPECT_EQ("[fe80::1%eth0]:8080",
  17763. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17764. // Edge case: Port 443 with is_ssl=false (should add port)
  17765. EXPECT_EQ("example.com:443",
  17766. detail::make_host_and_port_string("example.com", 443, false));
  17767. // Edge case: Port 80 with is_ssl=true (should add port)
  17768. EXPECT_EQ("example.com:80",
  17769. detail::make_host_and_port_string("example.com", 80, true));
  17770. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17771. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17772. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17773. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17774. // Security fix: Already bracketed IPv6 should not get double brackets
  17775. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17776. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17777. EXPECT_EQ("[::1]:8080",
  17778. detail::make_host_and_port_string("[::1]", 8080, false));
  17779. EXPECT_EQ("[2001:db8::1]:8080",
  17780. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17781. EXPECT_EQ("[fe80::1%eth0]",
  17782. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17783. EXPECT_EQ("[fe80::1%eth0]:8080",
  17784. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17785. // Edge case: Empty host (should return as-is)
  17786. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17787. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17788. // This is a known limitation but shouldn't crash
  17789. EXPECT_EQ("[host:name]",
  17790. detail::make_host_and_port_string("host:name", 80, false));
  17791. // Port number edge cases (no validation, but should not crash)
  17792. EXPECT_EQ("example.com:0",
  17793. detail::make_host_and_port_string("example.com", 0, false));
  17794. EXPECT_EQ("example.com:-1",
  17795. detail::make_host_and_port_string("example.com", -1, false));
  17796. EXPECT_EQ("example.com:65535",
  17797. detail::make_host_and_port_string("example.com", 65535, false));
  17798. EXPECT_EQ("example.com:65536",
  17799. detail::make_host_and_port_string("example.com", 65536, false));
  17800. }
  17801. #ifdef CPPHTTPLIB_SSL_ENABLED
  17802. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17803. httplib::SSLClient cli("roblox.com", 443);
  17804. cli.set_follow_location(true);
  17805. auto res = cli.Get("/");
  17806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17807. EXPECT_EQ(StatusCode::OK_200, res->status);
  17808. }
  17809. #endif
  17810. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17811. Server svr;
  17812. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17813. EXPECT_EQ(res.status, 400);
  17814. });
  17815. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17816. auto se = detail::scope_exit([&] {
  17817. svr.stop();
  17818. thread.join();
  17819. ASSERT_FALSE(svr.is_running());
  17820. });
  17821. svr.wait_until_ready();
  17822. Client cli(HOST, PORT);
  17823. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17824. }
  17825. TEST(InvalidHeaderCharsTest, is_field_name) {
  17826. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17827. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17828. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17829. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17830. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17831. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17832. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17833. EXPECT_FALSE(detail::fields::is_field_name(""));
  17834. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17835. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17836. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17837. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17838. }
  17839. TEST(InvalidHeaderCharsTest, is_field_value) {
  17840. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17841. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17842. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17843. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17844. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17845. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17846. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17847. EXPECT_TRUE(detail::fields::is_field_value(""));
  17848. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17849. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17850. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17851. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17852. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17853. }
  17854. TEST(InvalidHeaderCharsTest, OnServer) {
  17855. Server svr;
  17856. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17857. std::string header = "Not Set";
  17858. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17859. res.set_header(header, "value");
  17860. res.set_content("Page Content Page Content", "text/plain");
  17861. });
  17862. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17863. std::string header = "Not Set";
  17864. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17865. res.set_header("X-Test", header);
  17866. res.set_content("Page Content Page Content", "text/plain");
  17867. });
  17868. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17869. auto se = detail::scope_exit([&] {
  17870. svr.stop();
  17871. thread.join();
  17872. ASSERT_FALSE(svr.is_running());
  17873. });
  17874. svr.wait_until_ready();
  17875. Client cli(HOST, PORT);
  17876. {
  17877. auto res = cli.Get(
  17878. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17880. EXPECT_EQ("Page Content Page Content", res->body);
  17881. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17882. }
  17883. {
  17884. auto res = cli.Get(
  17885. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17887. EXPECT_EQ("Page Content Page Content", res->body);
  17888. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17889. }
  17890. }
  17891. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17892. auto handled = false;
  17893. Server svr;
  17894. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17895. thread t = thread([&] { svr.listen(HOST, PORT); });
  17896. auto se = detail::scope_exit([&] {
  17897. svr.stop();
  17898. t.join();
  17899. ASSERT_FALSE(svr.is_running());
  17900. ASSERT_FALSE(handled);
  17901. });
  17902. svr.wait_until_ready();
  17903. auto req = "POST /test HTTP/1.1\r\n"
  17904. "Content-Length: x\r\n"
  17905. "\r\n";
  17906. std::string response;
  17907. ASSERT_TRUE(send_request(1, req, &response));
  17908. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17909. response.substr(0, response.find("\r\n")));
  17910. }
  17911. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17912. // case-insensitive, and a server that receives a 100-continue expectation in
  17913. // an HTTP/1.0 request MUST ignore it.
  17914. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17915. std::string response;
  17916. ASSERT_TRUE(send_request(1, req, &response, port));
  17917. *got_100 = response.find("100 Continue") != std::string::npos;
  17918. }
  17919. class ExpectTokenTest : public ::testing::Test {
  17920. protected:
  17921. void SetUp() override {
  17922. svr_.Post("/p", [](const Request &, Response &res) {
  17923. res.set_content("ok", "text/plain");
  17924. });
  17925. port_ = svr_.bind_to_any_port(HOST);
  17926. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17927. svr_.wait_until_ready();
  17928. }
  17929. void TearDown() override {
  17930. svr_.stop();
  17931. if (thread_.joinable()) { thread_.join(); }
  17932. }
  17933. std::string request(const char *version, const char *expect_value) const {
  17934. return std::string("POST /p ") + version +
  17935. "\r\n"
  17936. "Host: localhost\r\n"
  17937. "Content-Length: 2\r\n"
  17938. "Connection: close\r\n"
  17939. "Expect: " +
  17940. expect_value +
  17941. "\r\n"
  17942. "\r\n"
  17943. "hi";
  17944. }
  17945. Server svr_;
  17946. int port_ = 0;
  17947. thread thread_;
  17948. };
  17949. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17950. bool got_100 = false;
  17951. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17952. EXPECT_TRUE(got_100);
  17953. }
  17954. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17955. bool got_100 = true;
  17956. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17957. EXPECT_FALSE(got_100);
  17958. }
  17959. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17960. bool got_100 = false;
  17961. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17962. EXPECT_TRUE(got_100);
  17963. }
  17964. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17965. bool got_100 = false;
  17966. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17967. EXPECT_TRUE(got_100);
  17968. }
  17969. // `100 Continue` is sent only when the server starts reading the body, so a
  17970. // request rejected before that never invites the client to send it. The
  17971. // requests below carry the expectation but withhold the body, as a client
  17972. // waiting for `100 Continue` would.
  17973. // A POST that expects `100 Continue` and withholds its two-byte body.
  17974. static std::string expect_headers_only(const std::string &path) {
  17975. return "POST " + path +
  17976. " HTTP/1.1\r\n"
  17977. "Host: localhost\r\n"
  17978. "Content-Length: 2\r\n"
  17979. "Expect: 100-continue\r\n"
  17980. "\r\n";
  17981. }
  17982. class ExpectLazyContinueTest : public ::testing::Test {
  17983. protected:
  17984. void SetUp() override {
  17985. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17986. if (req.path == "/pre-routing") {
  17987. res.status = StatusCode::Unauthorized_401;
  17988. return Server::HandlerResponse::Handled;
  17989. }
  17990. return Server::HandlerResponse::Unhandled;
  17991. });
  17992. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17993. if (req.matched_route == "/pre-request") {
  17994. res.status = StatusCode::Forbidden_403;
  17995. return Server::HandlerResponse::Handled;
  17996. }
  17997. return Server::HandlerResponse::Unhandled;
  17998. });
  17999. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18000. res.set_content("ok", "text/plain");
  18001. });
  18002. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18003. res.set_content("ok", "text/plain");
  18004. });
  18005. svr_.Post("/reader-used", [](const Request &, Response &res,
  18006. const ContentReader &content_reader) {
  18007. std::string body;
  18008. content_reader([&](const char *data, size_t len) {
  18009. body.append(data, len);
  18010. return true;
  18011. });
  18012. res.set_content(body, "text/plain");
  18013. });
  18014. svr_.Post("/reader-unused",
  18015. [](const Request &, Response &res, const ContentReader &) {
  18016. res.set_content("ignored", "text/plain");
  18017. });
  18018. port_ = svr_.bind_to_any_port(HOST);
  18019. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18020. svr_.wait_until_ready();
  18021. }
  18022. void TearDown() override {
  18023. svr_.stop();
  18024. if (thread_.joinable()) { thread_.join(); }
  18025. }
  18026. // Sends `req` and reads until the server closes the connection. Returns
  18027. // false if the read had to wait for the client-side timeout instead.
  18028. bool send_until_closed(const std::string &req, std::string *resp) const {
  18029. auto start = std::chrono::steady_clock::now();
  18030. if (!send_request(3, req, resp, port_)) { return false; }
  18031. auto elapsed = std::chrono::steady_clock::now() - start;
  18032. return elapsed < std::chrono::seconds(2);
  18033. }
  18034. // The final response comes without `100 Continue`, and the server closes
  18035. // the connection since the body may or may not follow.
  18036. void expect_final_without_interim(const std::string &path,
  18037. const char *status_line) const {
  18038. std::string resp;
  18039. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18040. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18041. EXPECT_EQ(0u, resp.find(status_line));
  18042. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18043. }
  18044. Server svr_;
  18045. int port_ = 0;
  18046. thread thread_;
  18047. };
  18048. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18049. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18050. }
  18051. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18052. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18053. }
  18054. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18055. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18056. }
  18057. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18058. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18059. }
  18060. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18061. // The body follows once `100 Continue` has had time to arrive.
  18062. auto req = expect_headers_only("/reader-used");
  18063. req.insert(req.size() - 2, "Connection: close\r\n");
  18064. std::string resp;
  18065. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18066. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18067. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18068. EXPECT_NE(std::string::npos, resp.find("hi"));
  18069. }
  18070. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18071. // Large enough for the client to add `Expect: 100-continue` itself.
  18072. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18073. std::atomic<bool> body_sent{false};
  18074. Client cli(HOST, port_);
  18075. auto res = cli.Post(
  18076. "/pre-request", length,
  18077. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18078. body_sent = true;
  18079. std::string chunk(len, 'x');
  18080. sink.write(chunk.data(), chunk.size());
  18081. return true;
  18082. },
  18083. "application/octet-stream");
  18084. ASSERT_TRUE(res);
  18085. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18086. EXPECT_FALSE(body_sent);
  18087. }
  18088. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18089. Server svr;
  18090. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18091. return StatusCode::ExpectationFailed_417;
  18092. });
  18093. svr.Post("/p", [](const Request &, Response &res) {
  18094. res.set_content("ok", "text/plain");
  18095. });
  18096. auto port = svr.bind_to_any_port(HOST);
  18097. thread t = thread([&] { svr.listen_after_bind(); });
  18098. auto se = detail::scope_exit([&] {
  18099. svr.stop();
  18100. t.join();
  18101. });
  18102. svr.wait_until_ready();
  18103. std::string resp;
  18104. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18105. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18106. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18107. // Exactly one response: the route handler must not run after the 417.
  18108. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18109. }
  18110. #ifndef _WIN32
  18111. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18112. static constexpr char reject[] = "Unauthorized";
  18113. static constexpr char accept[] = "Upload accepted";
  18114. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18115. Server svr;
  18116. svr.set_expect_100_continue_handler(
  18117. [](const Request & /*req*/, Response &res) {
  18118. res.status = StatusCode::Unauthorized_401;
  18119. res.set_content(reject, "text/plain");
  18120. return res.status;
  18121. });
  18122. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18123. res.set_content(accept, "text/plain");
  18124. });
  18125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18126. auto se = detail::scope_exit([&] {
  18127. svr.stop();
  18128. thread.join();
  18129. ASSERT_FALSE(svr.is_running());
  18130. });
  18131. svr.wait_until_ready();
  18132. {
  18133. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18134. curl_easy_init(), &curl_easy_cleanup};
  18135. ASSERT_NE(curl, nullptr);
  18136. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18137. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18138. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18139. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18140. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18141. &curl_slist_free_all};
  18142. ASSERT_NE(list, nullptr);
  18143. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18144. struct read_data {
  18145. uint64_t read_size;
  18146. uint64_t total_size;
  18147. } data = {0, total_size};
  18148. using read_callback_t =
  18149. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18150. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18151. void *userdata) -> size_t {
  18152. read_data *d = (read_data *)userdata;
  18153. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18154. std::fill_n(ptr, size * nmemb, 'A');
  18155. d->read_size += size * nmemb;
  18156. return size * nmemb;
  18157. };
  18158. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18159. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18160. std::vector<char> buffer;
  18161. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18162. using write_callback_t =
  18163. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18164. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18165. void *userdata) -> size_t {
  18166. std::vector<char> *buf = (std::vector<char> *)userdata;
  18167. buf->reserve(buf->size() + size * nmemb + 1);
  18168. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18169. return size * nmemb;
  18170. };
  18171. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18172. {
  18173. const auto res = curl_easy_perform(curl.get());
  18174. ASSERT_EQ(res, CURLE_OK);
  18175. }
  18176. {
  18177. auto response_code = long{};
  18178. const auto res =
  18179. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18180. ASSERT_EQ(res, CURLE_OK);
  18181. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18182. }
  18183. {
  18184. auto dl = curl_off_t{};
  18185. const auto res =
  18186. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18187. ASSERT_EQ(res, CURLE_OK);
  18188. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18189. }
  18190. {
  18191. buffer.push_back('\0');
  18192. ASSERT_STRCASEEQ(buffer.data(), reject);
  18193. }
  18194. }
  18195. }
  18196. #endif
  18197. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18198. // Regression test for #2458.
  18199. //
  18200. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18201. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18202. // ticket can make the client socket spuriously readable during the
  18203. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18204. // the client withholds the body and then blocks reading a response that never
  18205. // comes, failing with `Failed to read connection`.
  18206. //
  18207. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18208. // within the timeout. This raw OpenSSL server deliberately never sends
  18209. // `100 Continue`; the client must still deliver the body and receive 200.
  18210. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18211. signal(SIGPIPE, SIG_IGN);
  18212. const auto port = PORT + 4;
  18213. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18214. ASSERT_NE(srv, INVALID_SOCKET);
  18215. int opt = 1;
  18216. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18217. sockaddr_in addr{};
  18218. addr.sin_family = AF_INET;
  18219. addr.sin_port = htons(static_cast<uint16_t>(port));
  18220. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18221. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18222. ASSERT_EQ(0, ::listen(srv, 1));
  18223. std::atomic<size_t> server_body_bytes{0};
  18224. auto server_thread = std::thread([&] {
  18225. sockaddr_in cli_addr{};
  18226. socklen_t cli_len = sizeof(cli_addr);
  18227. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18228. if (cli == INVALID_SOCKET) { return; }
  18229. // Bound the lifetime of the server side so a buggy client (which never
  18230. // sends the body) cannot make this thread block forever on join.
  18231. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18232. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18233. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18234. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18235. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18236. SSL *ssl = SSL_new(ctx);
  18237. SSL_set_fd(ssl, static_cast<int>(cli));
  18238. if (SSL_accept(ssl) > 0) {
  18239. // Read the request headers. Reading here also flushes the TLS 1.3
  18240. // session tickets to the client. Deliberately do NOT send
  18241. // `100 Continue`.
  18242. std::string buf;
  18243. char tmp[1024];
  18244. while (buf.find("\r\n\r\n") == std::string::npos) {
  18245. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18246. if (n <= 0) { break; }
  18247. buf.append(tmp, static_cast<size_t>(n));
  18248. }
  18249. // A correct client sends the body now; count what arrives.
  18250. auto pos = buf.find("\r\n\r\n");
  18251. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18252. while (body < 4096) {
  18253. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18254. if (n <= 0) { break; }
  18255. body += static_cast<size_t>(n);
  18256. }
  18257. server_body_bytes = body;
  18258. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18259. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18260. SSL_shutdown(ssl);
  18261. }
  18262. SSL_free(ssl);
  18263. detail::close_socket(cli);
  18264. SSL_CTX_free(ctx);
  18265. });
  18266. auto se = detail::scope_exit([&] {
  18267. server_thread.join();
  18268. detail::close_socket(srv);
  18269. });
  18270. SSLClient cli("127.0.0.1", port);
  18271. cli.enable_server_certificate_verification(false);
  18272. cli.set_connection_timeout(5, 0);
  18273. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18274. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18275. std::string body(4096, 'A');
  18276. auto res = cli.Put("/api/test", body, "application/json");
  18277. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18278. EXPECT_EQ(StatusCode::OK_200, res->status);
  18279. EXPECT_EQ(body.size(), server_body_bytes.load());
  18280. }
  18281. #endif
  18282. template <typename S, typename C>
  18283. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18284. svr.Get("/stream", [&](const Request &, Response &res) {
  18285. auto data = new std::string("01234567890123456789");
  18286. res.set_content_provider(
  18287. data->size(), "text/plain",
  18288. [&, data](size_t offset, size_t length, DataSink &sink) {
  18289. const size_t DATA_CHUNK_SIZE = 4;
  18290. const auto &d = *data;
  18291. std::this_thread::sleep_for(std::chrono::seconds(1));
  18292. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18293. return true;
  18294. },
  18295. [data](bool success) {
  18296. EXPECT_FALSE(success);
  18297. delete data;
  18298. });
  18299. });
  18300. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18301. auto i = new size_t(0);
  18302. res.set_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.write("abcd", 4);
  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. svr.Get("/chunked", [&](const Request &, Response &res) {
  18320. auto i = new size_t(0);
  18321. res.set_chunked_content_provider(
  18322. "text/plain",
  18323. [i](size_t, DataSink &sink) {
  18324. if (*i < 5) {
  18325. std::this_thread::sleep_for(std::chrono::seconds(1));
  18326. sink.os << "abcd";
  18327. (*i)++;
  18328. } else {
  18329. sink.done();
  18330. }
  18331. return true;
  18332. },
  18333. [i](bool success) {
  18334. EXPECT_FALSE(success);
  18335. delete i;
  18336. });
  18337. });
  18338. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18339. auto se = detail::scope_exit([&] {
  18340. svr.stop();
  18341. listen_thread.join();
  18342. ASSERT_FALSE(svr.is_running());
  18343. });
  18344. svr.wait_until_ready();
  18345. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18346. {
  18347. auto start = std::chrono::steady_clock::now();
  18348. auto res = cli.Get("/stream");
  18349. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18350. std::chrono::steady_clock::now() - start)
  18351. .count();
  18352. ASSERT_FALSE(res);
  18353. EXPECT_EQ(Error::Read, res.error());
  18354. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18355. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18356. }
  18357. {
  18358. auto start = std::chrono::steady_clock::now();
  18359. auto res = cli.Get("/stream_without_length");
  18360. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18361. std::chrono::steady_clock::now() - start)
  18362. .count();
  18363. ASSERT_FALSE(res);
  18364. EXPECT_EQ(Error::Read, res.error());
  18365. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18366. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18367. }
  18368. {
  18369. auto start = std::chrono::steady_clock::now();
  18370. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18371. EXPECT_EQ("abcd", string(data, data_length));
  18372. return true;
  18373. });
  18374. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18375. std::chrono::steady_clock::now() - start)
  18376. .count();
  18377. ASSERT_FALSE(res);
  18378. EXPECT_EQ(Error::Read, res.error());
  18379. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18380. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18381. }
  18382. }
  18383. TEST(MaxTimeoutTest, ContentStream) {
  18384. time_t timeout = 2000;
  18385. time_t threshold = 200;
  18386. Server svr;
  18387. Client cli("localhost", PORT);
  18388. max_timeout_test(svr, cli, timeout, threshold);
  18389. }
  18390. #ifdef CPPHTTPLIB_SSL_ENABLED
  18391. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18392. time_t timeout = 2000;
  18393. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18395. SSLClient cli("localhost", PORT);
  18396. cli.enable_server_certificate_verification(false);
  18397. max_timeout_test(svr, cli, timeout, threshold);
  18398. }
  18399. #endif
  18400. class EventDispatcher {
  18401. public:
  18402. EventDispatcher() {}
  18403. bool wait_event(DataSink *sink) {
  18404. unique_lock<mutex> lk(m_);
  18405. int id = id_;
  18406. // Wait with timeout to prevent hanging if client disconnects
  18407. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18408. [&] { return cid_ == id; })) {
  18409. return false; // Timeout occurred
  18410. }
  18411. sink->write(message_.data(), message_.size());
  18412. return true;
  18413. }
  18414. void send_event(const string &message) {
  18415. lock_guard<mutex> lk(m_);
  18416. cid_ = id_++;
  18417. message_ = message;
  18418. cv_.notify_all();
  18419. }
  18420. private:
  18421. mutex m_;
  18422. condition_variable cv_;
  18423. atomic_int id_{0};
  18424. atomic_int cid_{-1};
  18425. string message_;
  18426. };
  18427. TEST(ClientInThreadTest, Issue2068) {
  18428. EventDispatcher ed;
  18429. Server svr;
  18430. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18431. res.set_chunked_content_provider("text/event-stream",
  18432. [&](size_t /*offset*/, DataSink &sink) {
  18433. return ed.wait_event(&sink);
  18434. });
  18435. });
  18436. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18437. svr.wait_until_ready();
  18438. thread event_thread([&] {
  18439. int id = 0;
  18440. while (svr.is_running()) {
  18441. this_thread::sleep_for(chrono::milliseconds(500));
  18442. std::stringstream ss;
  18443. ss << "data: " << id << "\n\n";
  18444. ed.send_event(ss.str());
  18445. id++;
  18446. }
  18447. });
  18448. auto se = detail::scope_exit([&] {
  18449. svr.stop();
  18450. listen_thread.join();
  18451. event_thread.join();
  18452. ASSERT_FALSE(svr.is_running());
  18453. });
  18454. {
  18455. auto client = detail::make_unique<Client>(HOST, PORT);
  18456. client->set_read_timeout(std::chrono::minutes(10));
  18457. std::atomic<bool> stop{false};
  18458. std::thread t([&] {
  18459. client->Get("/event1",
  18460. [&](const char *, size_t) -> bool { return !stop; });
  18461. });
  18462. std::this_thread::sleep_for(std::chrono::seconds(2));
  18463. stop = true;
  18464. client->stop();
  18465. t.join();
  18466. // Reset client after thread has finished
  18467. client.reset();
  18468. }
  18469. }
  18470. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18471. auto handled = false;
  18472. Server svr;
  18473. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18474. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18475. auto se = detail::scope_exit([&] {
  18476. svr.stop();
  18477. t.join();
  18478. ASSERT_FALSE(svr.is_running());
  18479. ASSERT_FALSE(handled);
  18480. });
  18481. svr.wait_until_ready();
  18482. // Two Content-Length headers with different values — must be rejected
  18483. auto req = "POST /test HTTP/1.1\r\n"
  18484. "Content-Length: 5\r\n"
  18485. "Content-Length: 10\r\n"
  18486. "\r\n"
  18487. "hello";
  18488. std::string response;
  18489. ASSERT_TRUE(send_request(1, req, &response));
  18490. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18491. response.substr(0, response.find("\r\n")));
  18492. }
  18493. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18494. auto handled = false;
  18495. Server svr;
  18496. svr.Post("/test", [&](const Request &, Response &res) {
  18497. handled = true;
  18498. res.set_content("ok", "text/plain");
  18499. });
  18500. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18501. auto se = detail::scope_exit([&] {
  18502. svr.stop();
  18503. t.join();
  18504. ASSERT_FALSE(svr.is_running());
  18505. ASSERT_TRUE(handled);
  18506. });
  18507. svr.wait_until_ready();
  18508. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18509. auto req = "POST /test HTTP/1.1\r\n"
  18510. "Host: localhost\r\n"
  18511. "Content-Length: 5\r\n"
  18512. "Content-Length: 5\r\n"
  18513. "\r\n"
  18514. "hello";
  18515. std::string response;
  18516. ASSERT_TRUE(send_request(1, req, &response));
  18517. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18518. }
  18519. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18520. Server svr;
  18521. svr.Get("/test", [](const Request &, Response &res) {
  18522. res.set_content("ok", "text/plain");
  18523. });
  18524. auto port = svr.bind_to_any_port(HOST);
  18525. thread t = thread([&] { svr.listen_after_bind(); });
  18526. auto se = detail::scope_exit([&] {
  18527. svr.stop();
  18528. t.join();
  18529. ASSERT_FALSE(svr.is_running());
  18530. });
  18531. svr.wait_until_ready();
  18532. auto status_line = [&](const std::string &host_lines) {
  18533. std::string res;
  18534. send_request(
  18535. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18536. &res, port);
  18537. return res.substr(0, res.find("\r\n"));
  18538. };
  18539. const char *accepted[] = {
  18540. "Host: localhost\r\n",
  18541. "Host: a.example:8080\r\n",
  18542. "Host: my_service\r\n",
  18543. "Host: [::1]:8080\r\n",
  18544. "Host: [fe80::1%25eth0]\r\n",
  18545. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18546. };
  18547. for (auto host_lines : accepted) {
  18548. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18549. }
  18550. const char *rejected[] = {
  18551. "Host: a.example\r\nHost: b.example\r\n",
  18552. "Host: a.example\r\nHost: a.example\r\n",
  18553. "Host: a@b.example\r\n",
  18554. "Host: a.example/b\r\n",
  18555. "Host: a.example\\b\r\n",
  18556. "Host: a.example?b\r\n",
  18557. "Host: a.example#b\r\n",
  18558. "Host: a.example b.example\r\n",
  18559. };
  18560. for (auto host_lines : rejected) {
  18561. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18562. << host_lines;
  18563. }
  18564. }
  18565. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18566. Server svr;
  18567. svr.Get("/", [](const Request &req, Response &res) {
  18568. EXPECT_EQ(2U, req.trailers.size());
  18569. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18570. // Denied
  18571. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18572. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18573. // Accepted
  18574. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18575. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18576. EXPECT_TRUE(req.has_trailer("X-World"));
  18577. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18578. res.set_content("ok", "text/plain");
  18579. });
  18580. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18581. auto se = detail::scope_exit([&] {
  18582. svr.stop();
  18583. t.join();
  18584. ASSERT_FALSE(svr.is_running());
  18585. });
  18586. svr.wait_until_ready();
  18587. const std::string req = "GET / HTTP/1.1\r\n"
  18588. "Transfer-Encoding: chunked\r\n"
  18589. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18590. "\r\n"
  18591. "0\r\n"
  18592. "Content-Length: 10\r\n"
  18593. "Host: internal.local\r\n"
  18594. "Content-Type: malicious/content\r\n"
  18595. "Cookie: any\r\n"
  18596. "Set-Cookie: any\r\n"
  18597. "X-Forwarded-For: attacker.com\r\n"
  18598. "X-Real-Ip: 1.1.1.1\r\n"
  18599. "X-Hello: hello\r\n"
  18600. "X-World: world\r\n"
  18601. "\r\n";
  18602. std::string res;
  18603. ASSERT_TRUE(send_request(1, req, &res));
  18604. }
  18605. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18606. // several field lines, and the combined value is what has to be parsed. A
  18607. // Trailer field split across lines therefore declares every name it lists;
  18608. // reading only the first line silently drops the trailers the later lines
  18609. // declare. The prohibited-trailer filter still applies to every line.
  18610. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18611. Server svr;
  18612. size_t observed_trailer_count = 0;
  18613. std::string observed_hello;
  18614. std::string observed_world;
  18615. bool observed_content_length = true;
  18616. svr.Get("/", [&](const Request &req, Response &res) {
  18617. observed_trailer_count = req.trailers.size();
  18618. observed_hello = req.get_trailer_value("X-Hello");
  18619. observed_world = req.get_trailer_value("X-World");
  18620. observed_content_length = req.has_trailer("Content-Length");
  18621. res.set_content("ok", "text/plain");
  18622. });
  18623. auto port = svr.bind_to_any_port(HOST);
  18624. thread t = thread([&]() { svr.listen_after_bind(); });
  18625. auto se = detail::scope_exit([&] {
  18626. svr.stop();
  18627. t.join();
  18628. ASSERT_FALSE(svr.is_running());
  18629. });
  18630. svr.wait_until_ready();
  18631. const std::string req = "GET / HTTP/1.1\r\n"
  18632. "Host: localhost\r\n"
  18633. "Transfer-Encoding: chunked\r\n"
  18634. "Trailer: X-Hello\r\n"
  18635. "Trailer: X-World, Content-Length\r\n"
  18636. "\r\n"
  18637. "0\r\n"
  18638. "X-Hello: hello\r\n"
  18639. "X-World: world\r\n"
  18640. "Content-Length: 10\r\n"
  18641. "\r\n";
  18642. std::string res;
  18643. ASSERT_TRUE(send_request(1, req, &res, port));
  18644. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18645. // Accepted: both field lines contribute to the declared set
  18646. EXPECT_EQ(2U, observed_trailer_count);
  18647. EXPECT_EQ(observed_hello, "hello");
  18648. EXPECT_EQ(observed_world, "world");
  18649. // Denied: a prohibited name stays prohibited on a later field line
  18650. EXPECT_FALSE(observed_content_length);
  18651. }
  18652. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18653. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18654. // unbounded run of fields that are never declared, because the counter would
  18655. // only advance for declared fields.
  18656. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18657. Server svr;
  18658. bool handler_called = false;
  18659. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18660. handler_called = true;
  18661. res.set_content("ok", "text/plain");
  18662. });
  18663. auto port = svr.bind_to_any_port(HOST);
  18664. thread t = thread([&]() { svr.listen_after_bind(); });
  18665. auto se = detail::scope_exit([&] {
  18666. svr.stop();
  18667. t.join();
  18668. ASSERT_FALSE(svr.is_running());
  18669. });
  18670. svr.wait_until_ready();
  18671. // Declare nothing, then send far more undeclared trailer fields than the
  18672. // header-count limit. Parsing must stop and reject the request rather than
  18673. // read every line.
  18674. std::string req = "GET / HTTP/1.1\r\n"
  18675. "Transfer-Encoding: chunked\r\n"
  18676. "\r\n"
  18677. "0\r\n";
  18678. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18679. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18680. }
  18681. req += "\r\n";
  18682. std::string res;
  18683. ASSERT_TRUE(send_request(1, req, &res, port));
  18684. // The request is rejected before the handler runs.
  18685. EXPECT_FALSE(handler_called);
  18686. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18687. }
  18688. // The set of declared trailer names is capped so a peer cannot grow it without
  18689. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18690. // declared past the cap is not honored, even if the field is actually sent.
  18691. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18692. Server svr;
  18693. // One name inside the cap and one past it, so the test tracks the cap rather
  18694. // than a fixed count.
  18695. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18696. const std::string within_cap_name = "X-T-0";
  18697. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18698. bool observed_within_cap = false;
  18699. bool observed_past_cap = false;
  18700. svr.Get("/", [&](const Request &req, Response &res) {
  18701. observed_within_cap = req.has_trailer(within_cap_name);
  18702. observed_past_cap = req.has_trailer(past_cap_name);
  18703. res.set_content("ok", "text/plain");
  18704. });
  18705. auto port = svr.bind_to_any_port(HOST);
  18706. thread t = thread([&]() { svr.listen_after_bind(); });
  18707. auto se = detail::scope_exit([&] {
  18708. svr.stop();
  18709. t.join();
  18710. ASSERT_FALSE(svr.is_running());
  18711. });
  18712. svr.wait_until_ready();
  18713. // Declare more trailer names than the cap in a single Trailer field, then
  18714. // actually send the first (within the cap) and the last (past it).
  18715. std::string trailer_decl = "Trailer: ";
  18716. for (int i = 0; i < declared_count; i++) {
  18717. if (i != 0) { trailer_decl += ", "; }
  18718. trailer_decl += "X-T-" + std::to_string(i);
  18719. }
  18720. trailer_decl += "\r\n";
  18721. const std::string req = "GET / HTTP/1.1\r\n"
  18722. "Host: localhost\r\n"
  18723. "Transfer-Encoding: chunked\r\n" +
  18724. trailer_decl +
  18725. "\r\n"
  18726. "0\r\n" +
  18727. within_cap_name + ": a\r\n" + past_cap_name +
  18728. ": b\r\n"
  18729. "\r\n";
  18730. std::string res;
  18731. ASSERT_TRUE(send_request(1, req, &res, port));
  18732. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18733. // A name within the cap is honored; one declared past the cap is dropped.
  18734. EXPECT_TRUE(observed_within_cap);
  18735. EXPECT_FALSE(observed_past_cap);
  18736. }
  18737. // A direct client that is not listed in trusted_proxies must not be able to
  18738. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18739. // the peer address on the actual TCP connection determines whether the
  18740. // header is honored.
  18741. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18742. Server svr;
  18743. // Deliberately does NOT include the loopback address the test client
  18744. // actually connects from, so the direct connection is not a trusted proxy.
  18745. svr.set_trusted_proxies({"203.0.113.66"});
  18746. std::string observed_remote_addr;
  18747. svr.Get("/ip", [&](const Request &req, Response &res) {
  18748. observed_remote_addr = req.remote_addr;
  18749. res.set_content("ok", "text/plain");
  18750. });
  18751. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18752. auto se = detail::scope_exit([&] {
  18753. svr.stop();
  18754. t.join();
  18755. ASSERT_FALSE(svr.is_running());
  18756. });
  18757. svr.wait_until_ready();
  18758. Client cli(HOST, PORT);
  18759. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18761. EXPECT_EQ(StatusCode::OK_200, res->status);
  18762. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18763. // ignored entirely and the real connection-level address retained.
  18764. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18765. observed_remote_addr == "127.0.0.1");
  18766. }
  18767. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18768. Server svr;
  18769. std::string observed_remote_addr;
  18770. std::string observed_xff;
  18771. svr.Get("/ip", [&](const Request &req, Response &res) {
  18772. observed_remote_addr = req.remote_addr;
  18773. observed_xff = req.get_header_value("X-Forwarded-For");
  18774. res.set_content("ok", "text/plain");
  18775. });
  18776. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18777. auto se = detail::scope_exit([&] {
  18778. svr.stop();
  18779. t.join();
  18780. ASSERT_FALSE(svr.is_running());
  18781. });
  18782. svr.wait_until_ready();
  18783. Client cli(HOST, PORT);
  18784. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18786. EXPECT_EQ(StatusCode::OK_200, res->status);
  18787. EXPECT_EQ(observed_xff, "203.0.113.66");
  18788. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18789. observed_remote_addr == "127.0.0.1");
  18790. }
  18791. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18792. Server svr;
  18793. svr.set_trusted_proxies({"203.0.113.66"});
  18794. std::string observed_remote_addr;
  18795. std::string observed_xff;
  18796. svr.Get("/ip", [&](const Request &req, Response &res) {
  18797. observed_remote_addr = req.remote_addr;
  18798. observed_xff = req.get_header_value("X-Forwarded-For");
  18799. res.set_content("ok", "text/plain");
  18800. });
  18801. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18802. auto se = detail::scope_exit([&] {
  18803. svr.stop();
  18804. t.join();
  18805. ASSERT_FALSE(svr.is_running());
  18806. });
  18807. svr.wait_until_ready();
  18808. Client cli(HOST, PORT);
  18809. auto res = cli.Get("/ip");
  18810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18811. EXPECT_EQ(StatusCode::OK_200, res->status);
  18812. EXPECT_EQ(observed_xff, "");
  18813. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18814. observed_remote_addr == "127.0.0.1");
  18815. }
  18816. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  18817. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  18818. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  18819. Server svr;
  18820. svr.set_trusted_proxies({"127.0.0.1"});
  18821. svr.Get("/ip", [](const Request &req, Response &res) {
  18822. res.set_content(req.remote_addr, "text/plain");
  18823. });
  18824. auto port = svr.bind_to_any_port("::");
  18825. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  18826. thread t = thread([&] { svr.listen_after_bind(); });
  18827. auto se = detail::scope_exit([&] {
  18828. svr.stop();
  18829. t.join();
  18830. ASSERT_FALSE(svr.is_running());
  18831. });
  18832. svr.wait_until_ready();
  18833. Client cli("127.0.0.1", port);
  18834. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  18835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18836. EXPECT_EQ("198.51.100.23", res->body);
  18837. }
  18838. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  18839. Server svr;
  18840. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18841. svr.Get("/ip", [](const Request &req, Response &res) {
  18842. res.set_content(req.remote_addr, "text/plain");
  18843. });
  18844. auto port = svr.bind_to_any_port(HOST);
  18845. ASSERT_GT(port, 0);
  18846. thread t = thread([&] { svr.listen_after_bind(); });
  18847. auto se = detail::scope_exit([&] {
  18848. svr.stop();
  18849. t.join();
  18850. ASSERT_FALSE(svr.is_running());
  18851. });
  18852. svr.wait_until_ready();
  18853. Client cli(HOST, port);
  18854. auto res = cli.Get(
  18855. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  18856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18857. EXPECT_EQ("198.51.100.23", res->body);
  18858. }
  18859. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18860. Server svr;
  18861. // Include the loopback address the test client actually connects from, so
  18862. // the direct connection itself is recognized as the trusted proxy hop.
  18863. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18864. std::string observed_remote_addr;
  18865. std::string observed_xff;
  18866. svr.Get("/ip", [&](const Request &req, Response &res) {
  18867. observed_remote_addr = req.remote_addr;
  18868. observed_xff = req.get_header_value("X-Forwarded-For");
  18869. res.set_content("ok", "text/plain");
  18870. });
  18871. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18872. auto se = detail::scope_exit([&] {
  18873. svr.stop();
  18874. t.join();
  18875. ASSERT_FALSE(svr.is_running());
  18876. });
  18877. svr.wait_until_ready();
  18878. Client cli(HOST, PORT);
  18879. auto res = cli.Get(
  18880. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18882. EXPECT_EQ(StatusCode::OK_200, res->status);
  18883. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18884. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18885. }
  18886. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18887. Server svr;
  18888. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18889. std::string observed_remote_addr;
  18890. std::string observed_xff;
  18891. svr.Get("/ip", [&](const Request &req, Response &res) {
  18892. observed_remote_addr = req.remote_addr;
  18893. observed_xff = req.get_header_value("X-Forwarded-For");
  18894. res.set_content("ok", "text/plain");
  18895. });
  18896. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18897. auto se = detail::scope_exit([&] {
  18898. svr.stop();
  18899. t.join();
  18900. ASSERT_FALSE(svr.is_running());
  18901. });
  18902. svr.wait_until_ready();
  18903. Client cli(HOST, PORT);
  18904. auto res = cli.Get(
  18905. "/ip",
  18906. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18908. EXPECT_EQ(StatusCode::OK_200, res->status);
  18909. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18910. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18911. }
  18912. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18913. Server svr;
  18914. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18915. std::string observed_remote_addr;
  18916. std::string observed_xff;
  18917. svr.Get("/ip", [&](const Request &req, Response &res) {
  18918. observed_remote_addr = req.remote_addr;
  18919. observed_xff = req.get_header_value("X-Forwarded-For");
  18920. res.set_content("ok", "text/plain");
  18921. });
  18922. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18923. auto se = detail::scope_exit([&] {
  18924. svr.stop();
  18925. t.join();
  18926. ASSERT_FALSE(svr.is_running());
  18927. });
  18928. svr.wait_until_ready();
  18929. Client cli(HOST, PORT);
  18930. auto res = cli.Get(
  18931. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18933. EXPECT_EQ(StatusCode::OK_200, res->status);
  18934. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18935. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18936. // and must not be selected.
  18937. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18938. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18939. }
  18940. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18941. Server svr;
  18942. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18943. std::string observed_remote_addr;
  18944. svr.Get("/ip", [&](const Request &req, Response &res) {
  18945. observed_remote_addr = req.remote_addr;
  18946. res.set_content("ok", "text/plain");
  18947. });
  18948. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18949. auto se = detail::scope_exit([&] {
  18950. svr.stop();
  18951. t.join();
  18952. ASSERT_FALSE(svr.is_running());
  18953. });
  18954. svr.wait_until_ready();
  18955. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18956. // a forged address and the trusted proxy's own address; the forged value must
  18957. // not win over the address the trusted proxy actually recorded.
  18958. Client cli(HOST, PORT);
  18959. auto res = cli.Get(
  18960. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18962. EXPECT_EQ(StatusCode::OK_200, res->status);
  18963. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18964. }
  18965. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18966. Server svr;
  18967. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18968. std::string observed_remote_addr;
  18969. std::string observed_xff;
  18970. svr.Get("/ip", [&](const Request &req, Response &res) {
  18971. observed_remote_addr = req.remote_addr;
  18972. observed_xff = req.get_header_value("X-Forwarded-For");
  18973. res.set_content("ok", "text/plain");
  18974. });
  18975. thread t = thread([&]() { svr.listen(HOST, PORT); });
  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. Client cli(HOST, PORT);
  18983. auto res = cli.Get(
  18984. "/ip",
  18985. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18987. EXPECT_EQ(StatusCode::OK_200, res->status);
  18988. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18989. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18990. }
  18991. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18992. Server svr;
  18993. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18994. std::string observed_remote_addr;
  18995. std::string observed_xff;
  18996. svr.Get("/ip", [&](const Request &req, Response &res) {
  18997. observed_remote_addr = req.remote_addr;
  18998. observed_xff = req.get_header_value("X-Forwarded-For");
  18999. res.set_content("ok", "text/plain");
  19000. });
  19001. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19002. auto se = detail::scope_exit([&] {
  19003. svr.stop();
  19004. t.join();
  19005. ASSERT_FALSE(svr.is_running());
  19006. });
  19007. svr.wait_until_ready();
  19008. std::string raw_req =
  19009. "GET /ip HTTP/1.1\r\n"
  19010. "Host: localhost\r\n"
  19011. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19012. "Connection: close\r\n"
  19013. "\r\n";
  19014. std::string out;
  19015. ASSERT_TRUE(send_request(5, raw_req, &out));
  19016. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19017. // Header parser trims surrounding whitespace of the header value
  19018. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19019. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19020. }
  19021. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19022. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19023. // their own X-Forwarded-For as a separate field line rather than extending the
  19024. // one the client sent, so every occurrence has to be taken into account.
  19025. // Reading only the first one hands back the address the client chose.
  19026. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19027. Server svr;
  19028. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19029. std::string observed_remote_addr;
  19030. size_t observed_xff_count = 0;
  19031. svr.Get("/ip", [&](const Request &req, Response &res) {
  19032. observed_remote_addr = req.remote_addr;
  19033. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19034. res.set_content("ok", "text/plain");
  19035. });
  19036. auto port = svr.bind_to_any_port(HOST);
  19037. thread t = thread([&]() { svr.listen_after_bind(); });
  19038. auto se = detail::scope_exit([&] {
  19039. svr.stop();
  19040. t.join();
  19041. ASSERT_FALSE(svr.is_running());
  19042. });
  19043. svr.wait_until_ready();
  19044. // The client supplies the first field line; the trusted proxy appends the
  19045. // address it observed as a second one.
  19046. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19047. "Host: localhost\r\n"
  19048. "X-Forwarded-For: 1.2.3.4\r\n"
  19049. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19050. "Connection: close\r\n"
  19051. "\r\n";
  19052. std::string out;
  19053. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19054. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19055. EXPECT_EQ(observed_xff_count, 2U);
  19056. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19057. // The same chain spread over one field line per hop derives the same client
  19058. // address, i.e. the split and the comma-joined representations agree.
  19059. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19060. "Host: localhost\r\n"
  19061. "X-Forwarded-For: 1.2.3.4\r\n"
  19062. "X-Forwarded-For: 198.51.100.23\r\n"
  19063. "X-Forwarded-For: 192.0.2.45\r\n"
  19064. "Connection: close\r\n"
  19065. "\r\n";
  19066. out.clear();
  19067. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19068. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19069. EXPECT_EQ(observed_xff_count, 3U);
  19070. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19071. }
  19072. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19073. // crash the server (it used to call front() on an empty vector inside
  19074. // get_client_ip). The connection-level remote address must be retained instead.
  19075. static void run_malformed_xff_test(const std::string &xff_value) {
  19076. Server svr;
  19077. svr.set_trusted_proxies({"192.0.2.45"});
  19078. std::string observed_remote_addr;
  19079. svr.Get("/ip", [&](const Request &req, Response &res) {
  19080. observed_remote_addr = req.remote_addr;
  19081. res.set_content("ok", "text/plain");
  19082. });
  19083. int port = 0;
  19084. thread t = thread([&]() {
  19085. port = svr.bind_to_any_port(HOST);
  19086. svr.listen_after_bind();
  19087. });
  19088. auto se = detail::scope_exit([&] {
  19089. svr.stop();
  19090. t.join();
  19091. ASSERT_FALSE(svr.is_running());
  19092. });
  19093. svr.wait_until_ready();
  19094. Client cli(HOST, port);
  19095. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19097. EXPECT_EQ(StatusCode::OK_200, res->status);
  19098. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19099. observed_remote_addr == "127.0.0.1");
  19100. }
  19101. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19102. run_malformed_xff_test("");
  19103. }
  19104. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19105. run_malformed_xff_test(",");
  19106. }
  19107. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19108. run_malformed_xff_test(", , ,");
  19109. }
  19110. // The same rule applies to Accept: a request whose acceptable types are spread
  19111. // over several field lines must be negotiated against all of them.
  19112. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19113. // case-insensitive connection options. Comparing the whole field value against
  19114. // one option misses a client that sends several of them, and misses every
  19115. // casing but the one written in the comparison.
  19116. //
  19117. // Sends req, reads the response, then reuses the same socket for a second
  19118. // request to find out whether the server kept the connection.
  19119. static void probe_connection_reuse(int port, const std::string &req,
  19120. bool *announced_close, bool *reusable) {
  19121. auto error = Error::Success;
  19122. auto sock = detail::create_client_socket(
  19123. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19124. /*connection_timeout_sec=*/5, 0,
  19125. /*read_timeout_sec=*/1, 0,
  19126. /*write_timeout_sec=*/5, 0, std::string(), error);
  19127. ASSERT_NE(sock, INVALID_SOCKET);
  19128. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19129. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19130. "Host: localhost\r\n"
  19131. "Connection: close\r\n"
  19132. "\r\n";
  19133. std::string first_response;
  19134. std::string second_response;
  19135. detail::process_client_socket(
  19136. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19137. [&](Stream &strm) {
  19138. if (strm.write(req.data(), req.size()) !=
  19139. static_cast<ssize_t>(req.size())) {
  19140. return false;
  19141. }
  19142. char buf[512];
  19143. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19144. // Headers plus the two-byte body of the handler below
  19145. while (reader.getline()) {
  19146. first_response += reader.ptr();
  19147. if (first_response.find("ok") != std::string::npos) { break; }
  19148. }
  19149. if (strm.write(second.data(), second.size()) !=
  19150. static_cast<ssize_t>(second.size())) {
  19151. return true;
  19152. }
  19153. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19154. while (reader2.getline()) {
  19155. second_response += reader2.ptr();
  19156. if (second_response.find("ok") != std::string::npos) { break; }
  19157. }
  19158. return true;
  19159. });
  19160. *announced_close =
  19161. first_response.find("Connection: close") != std::string::npos;
  19162. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19163. }
  19164. class ConnectionTokenTest : public ::testing::Test {
  19165. protected:
  19166. void SetUp() override {
  19167. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19168. res.set_content("ok", "text/plain");
  19169. });
  19170. port_ = svr_.bind_to_any_port(HOST);
  19171. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19172. svr_.wait_until_ready();
  19173. }
  19174. void TearDown() override {
  19175. svr_.stop();
  19176. if (thread_.joinable()) { thread_.join(); }
  19177. }
  19178. Server svr_;
  19179. int port_ = 0;
  19180. thread thread_;
  19181. };
  19182. // "close" alongside another option still closes the connection, and the
  19183. // response says so rather than leaving the peer to discover it.
  19184. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19185. bool announced_close = false;
  19186. bool reusable = true;
  19187. probe_connection_reuse(port_,
  19188. "GET /keepalive HTTP/1.1\r\n"
  19189. "Host: localhost\r\n"
  19190. "Connection: keep-alive, close\r\n"
  19191. "\r\n",
  19192. &announced_close, &reusable);
  19193. EXPECT_TRUE(announced_close);
  19194. EXPECT_FALSE(reusable);
  19195. }
  19196. // "close" split over two field lines is the same list, so it is honored too.
  19197. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19198. bool announced_close = false;
  19199. bool reusable = true;
  19200. probe_connection_reuse(port_,
  19201. "GET /keepalive HTTP/1.1\r\n"
  19202. "Host: localhost\r\n"
  19203. "Connection: keep-alive\r\n"
  19204. "Connection: close\r\n"
  19205. "\r\n",
  19206. &announced_close, &reusable);
  19207. EXPECT_TRUE(announced_close);
  19208. EXPECT_FALSE(reusable);
  19209. }
  19210. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19211. // keep-alive in the spelling everyone actually sends keeps its connection.
  19212. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19213. bool announced_close = false;
  19214. bool reusable = false;
  19215. probe_connection_reuse(port_,
  19216. "GET /keepalive HTTP/1.0\r\n"
  19217. "Host: localhost\r\n"
  19218. "Connection: keep-alive\r\n"
  19219. "\r\n",
  19220. &announced_close, &reusable);
  19221. EXPECT_FALSE(announced_close);
  19222. EXPECT_TRUE(reusable);
  19223. }
  19224. // A token the value merely contains is not the token itself.
  19225. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19226. bool announced_close = false;
  19227. bool reusable = false;
  19228. probe_connection_reuse(port_,
  19229. "GET /keepalive HTTP/1.1\r\n"
  19230. "Host: localhost\r\n"
  19231. "Connection: notclose\r\n"
  19232. "\r\n",
  19233. &announced_close, &reusable);
  19234. EXPECT_FALSE(announced_close);
  19235. EXPECT_TRUE(reusable);
  19236. }
  19237. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19238. Server svr;
  19239. std::vector<std::string> observed_types;
  19240. svr.Get("/", [&](const Request &req, Response &res) {
  19241. observed_types = req.accept_content_types;
  19242. res.set_content("ok", "text/plain");
  19243. });
  19244. auto port = svr.bind_to_any_port(HOST);
  19245. thread t = thread([&]() { svr.listen_after_bind(); });
  19246. auto se = detail::scope_exit([&] {
  19247. svr.stop();
  19248. t.join();
  19249. ASSERT_FALSE(svr.is_running());
  19250. });
  19251. svr.wait_until_ready();
  19252. Client cli(HOST, port);
  19253. Headers headers;
  19254. headers.emplace("Accept", "text/plain;q=0.5");
  19255. headers.emplace("Accept", "application/json");
  19256. auto res = cli.Get("/", headers);
  19257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19258. EXPECT_EQ(StatusCode::OK_200, res->status);
  19259. // Sorted by q-value, so the second field line's type comes first
  19260. ASSERT_EQ(2U, observed_types.size());
  19261. EXPECT_EQ("application/json", observed_types[0]);
  19262. EXPECT_EQ("text/plain", observed_types[1]);
  19263. }
  19264. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19265. // empty field line must not contribute a bare comma to the combined value.
  19266. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19267. Server svr;
  19268. std::vector<std::string> observed_types;
  19269. svr.Get("/", [&](const Request &req, Response &res) {
  19270. observed_types = req.accept_content_types;
  19271. res.set_content("ok", "text/plain");
  19272. });
  19273. auto port = svr.bind_to_any_port(HOST);
  19274. thread t = thread([&]() { svr.listen_after_bind(); });
  19275. auto se = detail::scope_exit([&] {
  19276. svr.stop();
  19277. t.join();
  19278. ASSERT_FALSE(svr.is_running());
  19279. });
  19280. svr.wait_until_ready();
  19281. // Empty first field line, then a real one
  19282. std::string raw_req = "GET / HTTP/1.1\r\n"
  19283. "Host: localhost\r\n"
  19284. "Accept:\r\n"
  19285. "Accept: application/json\r\n"
  19286. "Connection: close\r\n"
  19287. "\r\n";
  19288. std::string out;
  19289. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19290. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19291. ASSERT_EQ(1U, observed_types.size());
  19292. EXPECT_EQ("application/json", observed_types[0]);
  19293. }
  19294. // The skip in get_combined_header_value() is what keeps an empty field line
  19295. // from contributing a bare comma. Only a trailing empty field line exercises
  19296. // it: a leading one is already covered by the "combined is still empty" check,
  19297. // and parse_accept_header() now ignores the empty element either way, so the
  19298. // request-level test above can no longer tell the two apart.
  19299. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19300. Headers headers;
  19301. headers.emplace("Accept", "text/html");
  19302. headers.emplace("Accept", "");
  19303. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19304. headers.clear();
  19305. headers.emplace("Accept", "");
  19306. headers.emplace("Accept", "application/json");
  19307. EXPECT_EQ("application/json",
  19308. detail::get_combined_header_value(headers, "Accept"));
  19309. }
  19310. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19311. // An encoding offered on a later Accept-Encoding field line is still offered.
  19312. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19313. Server svr;
  19314. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19315. res.set_content(std::string(1024, 'x'), "text/plain");
  19316. });
  19317. auto port = svr.bind_to_any_port(HOST);
  19318. thread t = thread([&]() { svr.listen_after_bind(); });
  19319. auto se = detail::scope_exit([&] {
  19320. svr.stop();
  19321. t.join();
  19322. ASSERT_FALSE(svr.is_running());
  19323. });
  19324. svr.wait_until_ready();
  19325. Client cli(HOST, port);
  19326. cli.set_decompress(false);
  19327. Headers headers;
  19328. headers.emplace("Accept-Encoding", "identity");
  19329. headers.emplace("Accept-Encoding", "gzip");
  19330. auto res = cli.Get("/", headers);
  19331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19332. EXPECT_EQ(StatusCode::OK_200, res->status);
  19333. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19334. }
  19335. #endif
  19336. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19337. // Transfer-Encoding is not its body.
  19338. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19339. Server svr;
  19340. svr.set_payload_max_length(8);
  19341. svr.Post("/test", [](const Request &, Response &res) {
  19342. res.set_content("ok", "text/plain");
  19343. });
  19344. auto port = svr.bind_to_any_port(HOST);
  19345. ASSERT_GT(port, 0);
  19346. thread t = thread([&] { svr.listen_after_bind(); });
  19347. auto se = detail::scope_exit([&] {
  19348. svr.stop();
  19349. t.join();
  19350. ASSERT_FALSE(svr.is_running());
  19351. });
  19352. svr.wait_until_ready();
  19353. std::string resp;
  19354. ASSERT_TRUE(send_request(1,
  19355. "POST /test HTTP/1.1\r\n"
  19356. "Host: localhost\r\n"
  19357. "Connection: close\r\n"
  19358. "\r\n" +
  19359. std::string(16, 'X'),
  19360. &resp, port));
  19361. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19362. }
  19363. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19364. Server svr;
  19365. svr.Post("/post", [&](const Request &req, Response &res) {
  19366. res.set_content(req.body, "text/plain");
  19367. });
  19368. svr.Put("/put", [&](const Request &req, Response &res) {
  19369. res.set_content(req.body, "text/plain");
  19370. });
  19371. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19372. res.set_content(req.body, "text/plain");
  19373. });
  19374. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19375. res.set_content(req.body, "text/plain");
  19376. });
  19377. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19378. auto se = detail::scope_exit([&] {
  19379. svr.stop();
  19380. t.join();
  19381. ASSERT_FALSE(svr.is_running());
  19382. });
  19383. svr.wait_until_ready();
  19384. std::string resp;
  19385. // POST without Content-Length
  19386. ASSERT_TRUE(send_request(5,
  19387. "POST /post HTTP/1.1\r\n"
  19388. "Host: localhost\r\n"
  19389. "Connection: close\r\n"
  19390. "\r\n",
  19391. &resp));
  19392. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19393. // PUT without Content-Length
  19394. resp.clear();
  19395. ASSERT_TRUE(send_request(5,
  19396. "PUT /put HTTP/1.1\r\n"
  19397. "Host: localhost\r\n"
  19398. "Connection: close\r\n"
  19399. "\r\n",
  19400. &resp));
  19401. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19402. // PATCH without Content-Length
  19403. resp.clear();
  19404. ASSERT_TRUE(send_request(5,
  19405. "PATCH /patch HTTP/1.1\r\n"
  19406. "Host: localhost\r\n"
  19407. "Connection: close\r\n"
  19408. "\r\n",
  19409. &resp));
  19410. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19411. // DELETE without Content-Length
  19412. resp.clear();
  19413. ASSERT_TRUE(send_request(5,
  19414. "DELETE /delete HTTP/1.1\r\n"
  19415. "Host: localhost\r\n"
  19416. "Connection: close\r\n"
  19417. "\r\n",
  19418. &resp));
  19419. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19420. }
  19421. //==============================================================================
  19422. // open_stream() Tests
  19423. //==============================================================================
  19424. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19425. std::string result;
  19426. char buf[8192];
  19427. ssize_t n;
  19428. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19429. result.append(buf, static_cast<size_t>(n));
  19430. }
  19431. return result;
  19432. }
  19433. // Mock stream for unit tests
  19434. class MockStream : public Stream {
  19435. public:
  19436. std::string data;
  19437. size_t pos = 0;
  19438. ssize_t error_after = -1; // -1 = no error
  19439. explicit MockStream(const std::string &d, ssize_t err = -1)
  19440. : data(d), error_after(err) {}
  19441. bool is_readable() const override { return true; }
  19442. bool wait_readable() const override { return true; }
  19443. bool wait_writable() const override { return true; }
  19444. ssize_t read(char *ptr, size_t size) override {
  19445. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19446. if (pos >= data.size()) return 0;
  19447. size_t limit =
  19448. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19449. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19450. std::memcpy(ptr, data.data() + pos, to_read);
  19451. pos += to_read;
  19452. return static_cast<ssize_t>(to_read);
  19453. }
  19454. ssize_t write(const char *, size_t) override { return -1; }
  19455. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19456. ip = "127.0.0.1";
  19457. port = 0;
  19458. }
  19459. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19460. ip = "127.0.0.1";
  19461. port = 0;
  19462. }
  19463. socket_t socket() const override { return INVALID_SOCKET; }
  19464. time_t duration() const override { return 0; }
  19465. };
  19466. TEST(StreamHandleTest, Basic) {
  19467. ClientImpl::StreamHandle handle;
  19468. EXPECT_FALSE(handle.is_valid());
  19469. handle.response = detail::make_unique<Response>();
  19470. handle.error = Error::Connection;
  19471. EXPECT_FALSE(handle.is_valid());
  19472. handle.error = Error::Success;
  19473. EXPECT_TRUE(handle.is_valid());
  19474. }
  19475. TEST(BodyReaderTest, Basic) {
  19476. MockStream stream("Hello, World!");
  19477. detail::BodyReader reader;
  19478. reader.stream = &stream;
  19479. reader.content_length = 13;
  19480. char buf[32];
  19481. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19482. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19483. EXPECT_TRUE(reader.eof);
  19484. }
  19485. TEST(BodyReaderTest, NoStream) {
  19486. detail::BodyReader reader;
  19487. char buf[32];
  19488. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19489. EXPECT_EQ(Error::Connection, reader.last_error);
  19490. }
  19491. TEST(BodyReaderTest, Error) {
  19492. MockStream stream("Hello, World!", 5);
  19493. detail::BodyReader reader;
  19494. reader.stream = &stream;
  19495. reader.content_length = 13;
  19496. char buf[32];
  19497. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19498. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19499. EXPECT_EQ(Error::Read, reader.last_error);
  19500. }
  19501. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19502. // Mock-based StreamHandle tests relying on private internals are removed.
  19503. class OpenStreamTest : public ::testing::Test {
  19504. protected:
  19505. void SetUp() override {
  19506. svr_.Get("/hello", [](const Request &, Response &res) {
  19507. res.set_content("Hello World!", "text/plain");
  19508. });
  19509. svr_.Get("/large", [](const Request &, Response &res) {
  19510. res.set_content(std::string(10000, 'X'), "text/plain");
  19511. });
  19512. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19513. res.set_content("Hello World!", "image/jpeg");
  19514. res.set_header("Content-Encoding", "UTF-8");
  19515. });
  19516. svr_.Get("/chunked", [](const Request &, Response &res) {
  19517. res.set_chunked_content_provider("text/plain",
  19518. [](size_t offset, DataSink &sink) {
  19519. if (offset < 15) {
  19520. sink.write("chunk", 5);
  19521. return true;
  19522. }
  19523. sink.done();
  19524. return true;
  19525. });
  19526. });
  19527. svr_.Get("/compressible", [](const Request &, Response &res) {
  19528. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19529. DataSink &sink) {
  19530. if (offset < 100 * 1024) {
  19531. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19532. sink.write(chunk.data(), chunk.size());
  19533. return true;
  19534. }
  19535. sink.done();
  19536. return true;
  19537. });
  19538. });
  19539. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19540. [](const Request & /*req*/, Response &res) {
  19541. auto i = new int(0);
  19542. res.set_header("Trailer", "Content-Length, X-Allowed");
  19543. res.set_chunked_content_provider(
  19544. "text/plain",
  19545. [i](size_t /*offset*/, DataSink &sink) {
  19546. switch (*i) {
  19547. case 0: sink.os << "123"; break;
  19548. case 1: sink.os << "456"; break;
  19549. case 2: sink.os << "789"; break;
  19550. case 3: {
  19551. sink.done_with_trailer(
  19552. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19553. } break;
  19554. }
  19555. (*i)++;
  19556. return true;
  19557. },
  19558. [i](bool success) {
  19559. EXPECT_TRUE(success);
  19560. delete i;
  19561. });
  19562. });
  19563. // Echo headers endpoint for header-related tests
  19564. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19565. std::string body;
  19566. for (const auto &h : req.headers) {
  19567. body.append(h.first);
  19568. body.push_back(':');
  19569. body.append(h.second);
  19570. body.push_back('\n');
  19571. }
  19572. res.set_content(body, "text/plain");
  19573. });
  19574. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19575. std::string body;
  19576. for (const auto &h : req.headers) {
  19577. body.append(h.first);
  19578. body.push_back(':');
  19579. body.append(h.second);
  19580. body.push_back('\n');
  19581. }
  19582. res.set_content(body, "text/plain");
  19583. });
  19584. port_ = svr_.bind_to_any_port("127.0.0.1");
  19585. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19586. svr_.wait_until_ready();
  19587. }
  19588. void TearDown() override {
  19589. svr_.stop();
  19590. if (thread_.joinable()) thread_.join();
  19591. }
  19592. Server svr_;
  19593. std::thread thread_;
  19594. int port_ = 0;
  19595. };
  19596. TEST_F(OpenStreamTest, Basic) {
  19597. Client cli("127.0.0.1", port_);
  19598. auto handle = cli.open_stream("GET", "/hello");
  19599. EXPECT_TRUE(handle.is_valid());
  19600. EXPECT_EQ("Hello World!", read_all(handle));
  19601. }
  19602. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19603. Client cli("127.0.0.1", port_);
  19604. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19605. ASSERT_TRUE(handle.is_valid());
  19606. EXPECT_EQ("Hello World!", read_all(handle));
  19607. }
  19608. TEST_F(OpenStreamTest, SmallBuffer) {
  19609. Client cli("127.0.0.1", port_);
  19610. auto handle = cli.open_stream("GET", "/hello");
  19611. std::string result;
  19612. char buf[4];
  19613. ssize_t n;
  19614. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19615. result.append(buf, static_cast<size_t>(n));
  19616. EXPECT_EQ("Hello World!", result);
  19617. }
  19618. TEST_F(OpenStreamTest, DefaultHeaders) {
  19619. Client cli("127.0.0.1", port_);
  19620. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19621. {
  19622. auto handle = cli.open_stream("GET", "/echo-headers");
  19623. ASSERT_TRUE(handle.is_valid());
  19624. auto body = read_all(handle);
  19625. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19626. std::string::npos);
  19627. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19628. std::string::npos);
  19629. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19630. }
  19631. // open_stream POST with body and no explicit content_type should NOT add
  19632. // text/plain Content-Type (behavior differs from non-streaming path), but
  19633. // should include Content-Length
  19634. {
  19635. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19636. ASSERT_TRUE(handle.is_valid());
  19637. auto body = read_all(handle);
  19638. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19639. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19640. }
  19641. // open_stream POST with explicit Content-Type should preserve it
  19642. {
  19643. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19644. {{"Content-Type", "application/custom"}},
  19645. "{}", "application/custom");
  19646. ASSERT_TRUE(handle.is_valid());
  19647. auto body = read_all(handle);
  19648. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19649. }
  19650. // User-specified User-Agent must not be overwritten for stream API
  19651. {
  19652. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19653. {{"User-Agent", "MyAgent/1.2"}});
  19654. ASSERT_TRUE(handle.is_valid());
  19655. auto body = read_all(handle);
  19656. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19657. }
  19658. }
  19659. TEST_F(OpenStreamTest, Large) {
  19660. Client cli("127.0.0.1", port_);
  19661. auto handle = cli.open_stream("GET", "/large");
  19662. EXPECT_EQ(10000u, read_all(handle).size());
  19663. }
  19664. TEST_F(OpenStreamTest, ConnectionError) {
  19665. Client cli("127.0.0.1", 9999);
  19666. auto handle = cli.open_stream("GET", "/hello");
  19667. EXPECT_FALSE(handle.is_valid());
  19668. }
  19669. TEST_F(OpenStreamTest, Chunked) {
  19670. Client cli("127.0.0.1", port_);
  19671. auto handle = cli.open_stream("GET", "/chunked");
  19672. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19673. "Transfer-Encoding") == "chunked");
  19674. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19675. }
  19676. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19677. Client cli("127.0.0.1", port_);
  19678. auto handle =
  19679. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19680. ASSERT_TRUE(handle.is_valid());
  19681. // Consume body to allow trailers to be received/parsed
  19682. auto body = read_all(handle);
  19683. // Explicitly parse trailers (ensure trailers are available for assertion)
  19684. handle.parse_trailers_if_needed();
  19685. EXPECT_EQ(std::string("123456789"), body);
  19686. // The response should include a Trailer header declaring both names
  19687. ASSERT_TRUE(handle.response);
  19688. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19689. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19690. handle.response->get_header_value("Trailer"));
  19691. // Prohibited trailer must not be present
  19692. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19693. // Allowed trailer should be present
  19694. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19695. EXPECT_EQ(std::string("yes"),
  19696. handle.response->get_trailer_value("X-Allowed"));
  19697. // Verify trailers are NOT present as regular headers
  19698. EXPECT_EQ(std::string(""),
  19699. handle.response->get_header_value("Content-Length"));
  19700. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19701. }
  19702. // Accepts one connection on an OS-assigned port, which it hands over through
  19703. // port_promise, reads the request head and sends back response. after_send,
  19704. // if given, runs on the connection before it is closed.
  19705. static std::thread
  19706. serve_single_response(std::promise<int> &port_promise,
  19707. const std::string &response,
  19708. std::function<void(socket_t)> after_send = nullptr) {
  19709. return std::thread([&port_promise, response, after_send] {
  19710. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19711. default_socket_options(srv);
  19712. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19713. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19714. sockaddr_in addr{};
  19715. addr.sin_family = AF_INET;
  19716. addr.sin_port = htons(0); // Let OS assign a free port
  19717. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19718. int opt = 1;
  19719. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19720. #ifdef _WIN32
  19721. reinterpret_cast<const char *>(&opt),
  19722. #else
  19723. &opt,
  19724. #endif
  19725. sizeof(opt));
  19726. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19727. ::listen(srv, 1) != 0) {
  19728. port_promise.set_value(-1);
  19729. detail::close_socket(srv);
  19730. return;
  19731. }
  19732. socklen_t addr_len = sizeof(addr);
  19733. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19734. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19735. sockaddr_in cli_addr{};
  19736. socklen_t cli_len = sizeof(cli_addr);
  19737. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19738. if (cli != INVALID_SOCKET) {
  19739. // Read the complete HTTP request (until the blank line that terminates
  19740. // headers) before sending the response. If the server closes the socket
  19741. // while the client's request data is still unread in the kernel receive
  19742. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19743. // connection on both sides: it discards the client's receive buffer
  19744. // (which already holds our response) and causes any in-progress write on
  19745. // the client to fail with ECONNRESET. Reading all request data first
  19746. // ensures close() emits a graceful FIN.
  19747. {
  19748. char rbuf[256];
  19749. std::string req;
  19750. while (req.find("\r\n\r\n") == std::string::npos) {
  19751. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19752. if (n <= 0) { break; }
  19753. req.append(rbuf, static_cast<size_t>(n));
  19754. }
  19755. }
  19756. ::send(cli,
  19757. #ifdef _WIN32
  19758. static_cast<const char *>(response.c_str()),
  19759. static_cast<int>(response.size()),
  19760. #else
  19761. response.c_str(), response.size(),
  19762. #endif
  19763. 0);
  19764. if (after_send) { after_send(cli); }
  19765. detail::close_socket(cli);
  19766. }
  19767. detail::close_socket(srv);
  19768. });
  19769. }
  19770. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19771. #ifndef _WIN32
  19772. signal(SIGPIPE, SIG_IGN);
  19773. #endif
  19774. std::promise<int> port_promise;
  19775. auto port_future = port_promise.get_future();
  19776. auto server_thread =
  19777. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19778. "Content-Type: text/plain\r\n"
  19779. "Content-Length: not-a-number\r\n"
  19780. "Connection: close\r\n"
  19781. "\r\n"
  19782. "hello");
  19783. auto port = port_future.get();
  19784. ASSERT_GT(port, 0);
  19785. Client cli("127.0.0.1", port);
  19786. auto handle = cli.open_stream("GET", "/");
  19787. EXPECT_FALSE(handle.is_valid());
  19788. server_thread.join();
  19789. }
  19790. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19791. #ifndef _WIN32
  19792. signal(SIGPIPE, SIG_IGN);
  19793. #endif
  19794. std::promise<int> port_promise;
  19795. auto port_future = port_promise.get_future();
  19796. auto server_thread = serve_single_response(
  19797. port_promise, "HTTP/1.1 200 OK\r\n"
  19798. "Content-Type: text/plain\r\n"
  19799. "Content-Length: 99999999999999999999999999\r\n"
  19800. "Connection: close\r\n"
  19801. "\r\n"
  19802. "hello");
  19803. auto port = port_future.get();
  19804. ASSERT_GT(port, 0);
  19805. // Historically std::stoull would throw std::out_of_range here and crash
  19806. // the process, then parsing silently clamped to a bogus framing length and
  19807. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19808. // so the stream fails to open, matching the not-a-number case above. The
  19809. // process still must NOT terminate.
  19810. Client cli("127.0.0.1", port);
  19811. auto handle = cli.open_stream("GET", "/");
  19812. EXPECT_FALSE(handle.is_valid());
  19813. server_thread.join();
  19814. }
  19815. // Serves `response` to the single request `fn` makes with a fresh client.
  19816. template <typename Fn>
  19817. static void with_single_response(const std::string &response, Fn fn) {
  19818. #ifndef _WIN32
  19819. signal(SIGPIPE, SIG_IGN);
  19820. #endif
  19821. std::promise<int> port_promise;
  19822. auto port_future = port_promise.get_future();
  19823. auto server_thread = serve_single_response(port_promise, response);
  19824. auto se = detail::scope_exit([&] { server_thread.join(); });
  19825. auto port = port_future.get();
  19826. ASSERT_GT(port, 0);
  19827. Client cli("127.0.0.1", port);
  19828. fn(cli);
  19829. }
  19830. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19831. // Neither Content-Length nor chunked: the body ends at the close
  19832. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19833. "Connection: close\r\n"
  19834. "\r\n"
  19835. "hello";
  19836. with_single_response(close_delimited, [](Client &cli) {
  19837. auto handle = cli.open_stream("GET", "/");
  19838. ASSERT_TRUE(handle.is_valid());
  19839. EXPECT_EQ("hello", read_all(handle));
  19840. EXPECT_FALSE(handle.has_read_error());
  19841. });
  19842. // A close before the end of the Content-Length is still an error
  19843. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19844. "Content-Length: 10\r\n"
  19845. "\r\n"
  19846. "hello";
  19847. with_single_response(short_content_length, [](Client &cli) {
  19848. auto handle = cli.open_stream("GET", "/");
  19849. ASSERT_TRUE(handle.is_valid());
  19850. read_all(handle);
  19851. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19852. });
  19853. // So is a close before the last chunk
  19854. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19855. "Transfer-Encoding: chunked\r\n"
  19856. "\r\n"
  19857. "5\r\nhello\r\n";
  19858. with_single_response(short_chunked, [](Client &cli) {
  19859. auto handle = cli.open_stream("GET", "/");
  19860. ASSERT_TRUE(handle.is_valid());
  19861. read_all(handle);
  19862. EXPECT_TRUE(handle.has_read_error());
  19863. });
  19864. }
  19865. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19866. const char *responses[] = {
  19867. "HTTP/1.1 103 Early Hints\r\n"
  19868. "Link: </style.css>; rel=preload\r\n"
  19869. "\r\n"
  19870. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19871. "HTTP/1.1 100 Continue\r\n"
  19872. "X-Note: interim\r\n"
  19873. "\r\n"
  19874. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19875. };
  19876. for (auto response : responses) {
  19877. with_single_response(response, [](Client &cli) {
  19878. auto res = cli.Get("/");
  19879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19880. EXPECT_EQ(StatusCode::OK_200, res->status);
  19881. EXPECT_EQ("ok", res->body);
  19882. });
  19883. }
  19884. }
  19885. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19886. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19887. const std::string final_response =
  19888. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19889. std::string interims;
  19890. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19891. interims += interim;
  19892. }
  19893. with_single_response(interims + final_response, [](Client &cli) {
  19894. auto res = cli.Get("/");
  19895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19896. EXPECT_EQ("ok", res->body);
  19897. });
  19898. with_single_response(interims + interim + final_response, [](Client &cli) {
  19899. auto res = cli.Get("/");
  19900. ASSERT_FALSE(res);
  19901. EXPECT_EQ(Error::Read, res.error());
  19902. });
  19903. }
  19904. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19905. #ifndef _WIN32
  19906. signal(SIGPIPE, SIG_IGN);
  19907. #endif
  19908. // The server answers the head without asking for the body. Bytes it then
  19909. // reads on the connection would be taken for the body the request declared.
  19910. auto closed_by_client = false;
  19911. std::promise<int> port_promise;
  19912. auto server_thread = serve_single_response(
  19913. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19914. [&](socket_t sock) {
  19915. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19916. char buf[256];
  19917. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19918. });
  19919. Client cli("127.0.0.1", port_promise.get_future().get());
  19920. cli.set_keep_alive(true);
  19921. cli.set_read_timeout(1, 0);
  19922. // Long enough for the client to send Expect: 100-continue.
  19923. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19925. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19926. cli.Get("/second");
  19927. server_thread.join();
  19928. EXPECT_TRUE(closed_by_client);
  19929. }
  19930. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19931. // Long enough for the client to send Expect: 100-continue
  19932. with_single_response(
  19933. "HTTP/1.1 103 Early Hints\r\n"
  19934. "Link: </style.css>; rel=preload\r\n"
  19935. "\r\n"
  19936. "HTTP/1.1 401 Unauthorized\r\n"
  19937. "Content-Length: 0\r\n\r\n",
  19938. [](Client &cli) {
  19939. cli.set_read_timeout(2, 0);
  19940. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19942. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19943. });
  19944. }
  19945. #ifdef CPPHTTPLIB_SSL_ENABLED
  19946. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19947. #ifndef _WIN32
  19948. signal(SIGPIPE, SIG_IGN);
  19949. #endif
  19950. auto reused = false;
  19951. std::promise<int> port_promise;
  19952. auto server_thread = serve_single_response(
  19953. port_promise,
  19954. "HTTP/1.1 401 Unauthorized\r\n"
  19955. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19956. "Content-Length: 0\r\n\r\n",
  19957. [&](socket_t sock) {
  19958. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19959. char buf[256];
  19960. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19961. });
  19962. Client cli("127.0.0.1", port_promise.get_future().get());
  19963. cli.set_keep_alive(true);
  19964. cli.set_digest_auth("user", "pass");
  19965. cli.set_read_timeout(1, 0);
  19966. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19967. server_thread.join();
  19968. EXPECT_FALSE(reused);
  19969. }
  19970. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19971. // Any other answer to CONNECT would read as the origin's response.
  19972. struct {
  19973. const char *response;
  19974. bool passed_on;
  19975. } cases[] = {
  19976. {"HTTP/1.1 201 Created\r\n"
  19977. "Set-Cookie: session=from-proxy\r\n"
  19978. "Content-Length: 0\r\n\r\n",
  19979. false},
  19980. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19981. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19982. "Content-Length: 0\r\n\r\n",
  19983. true},
  19984. };
  19985. for (const auto &c : cases) {
  19986. std::promise<int> port_promise;
  19987. auto server_thread = serve_single_response(port_promise, c.response);
  19988. SSLClient cli("example.com", 443);
  19989. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19990. auto res = cli.Get("/");
  19991. server_thread.join();
  19992. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19993. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19994. if (res) {
  19995. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19996. }
  19997. }
  19998. }
  19999. #endif
  20000. // Records the client's error logger calls as "error METHOD path", or
  20001. // "error null" for a call without a request
  20002. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20003. return [&log](const Error &err, const Request *req) {
  20004. log.push_back(to_string(err) + " " +
  20005. (req ? req->method + " " + req->path : "null"));
  20006. };
  20007. }
  20008. // A failed request is reported once, with the request the caller made
  20009. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20010. Server svr;
  20011. svr.Get("/big", [](const Request &, Response &res) {
  20012. res.set_content(std::string(100000, 'b'), "text/plain");
  20013. });
  20014. auto port = svr.bind_to_any_port(HOST);
  20015. std::thread t([&]() { svr.listen_after_bind(); });
  20016. auto se = detail::scope_exit([&] {
  20017. svr.stop();
  20018. t.join();
  20019. });
  20020. svr.wait_until_ready();
  20021. Client cli(HOST, port);
  20022. std::vector<std::string> log;
  20023. cli.set_error_logger(record_errors(log));
  20024. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20025. cli.Get("/big", [](const char *, size_t) { return false; });
  20026. EXPECT_EQ(expected, log);
  20027. log.clear();
  20028. cli.Get("/big", [](size_t, size_t) { return false; });
  20029. EXPECT_EQ(expected, log);
  20030. }
  20031. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20032. // Fails while the body is read
  20033. auto broken = [](const Request &, Response &res) {
  20034. res.set_content_provider(10, "text/plain",
  20035. [](size_t, size_t, DataSink &) { return false; });
  20036. };
  20037. Server other;
  20038. other.Get("/broken", broken);
  20039. auto other_port = other.bind_to_any_port(HOST);
  20040. std::thread other_t([&]() { other.listen_after_bind(); });
  20041. auto other_se = detail::scope_exit([&] {
  20042. other.stop();
  20043. other_t.join();
  20044. });
  20045. other.wait_until_ready();
  20046. Server svr;
  20047. svr.Get("/broken", broken);
  20048. svr.Get("/same-origin",
  20049. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20050. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20051. res.set_redirect("http://" + std::string(HOST) + ":" +
  20052. std::to_string(other_port) + "/broken");
  20053. });
  20054. auto port = svr.bind_to_any_port(HOST);
  20055. std::thread t([&]() { svr.listen_after_bind(); });
  20056. auto se = detail::scope_exit([&] {
  20057. svr.stop();
  20058. t.join();
  20059. });
  20060. svr.wait_until_ready();
  20061. Client cli(HOST, port);
  20062. cli.set_follow_location(true);
  20063. std::vector<std::string> log;
  20064. cli.set_error_logger(record_errors(log));
  20065. for (auto path : {"/same-origin", "/cross-origin"}) {
  20066. log.clear();
  20067. auto res = cli.Get(path);
  20068. ASSERT_FALSE(res);
  20069. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20070. log);
  20071. }
  20072. }
  20073. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20074. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20075. std::vector<std::string> log;
  20076. cli.set_error_logger(record_errors(log));
  20077. auto handle = cli.open_stream("GET", "/x");
  20078. EXPECT_FALSE(handle.is_valid());
  20079. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20080. log);
  20081. });
  20082. }
  20083. #ifdef CPPHTTPLIB_SSL_ENABLED
  20084. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20085. // Not a TLS server, so the handshake fails. It waits for a request line in
  20086. // the handshake bytes, so a short read timeout lets it close quickly.
  20087. Server svr;
  20088. svr.set_read_timeout(0, 100000);
  20089. svr.Get("/x", [](const Request &, Response &res) {
  20090. res.set_content("x", "text/plain");
  20091. });
  20092. auto port = svr.bind_to_any_port(HOST);
  20093. std::thread t([&]() { svr.listen_after_bind(); });
  20094. auto se = detail::scope_exit([&] {
  20095. svr.stop();
  20096. t.join();
  20097. });
  20098. svr.wait_until_ready();
  20099. std::vector<std::string> log;
  20100. SSLClient cli(HOST, port);
  20101. cli.enable_server_certificate_verification(false);
  20102. cli.set_error_logger(record_errors(log));
  20103. auto res = cli.Get("/x");
  20104. ASSERT_FALSE(res);
  20105. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20106. log.clear();
  20107. auto handle = cli.open_stream("GET", "/x");
  20108. EXPECT_FALSE(handle.is_valid());
  20109. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20110. log.clear();
  20111. SSLClient no_ca(HOST, port);
  20112. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20113. no_ca.set_error_logger(record_errors(log));
  20114. res = no_ca.Get("/x");
  20115. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20116. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20117. }
  20118. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20119. #ifndef _WIN32
  20120. signal(SIGPIPE, SIG_IGN);
  20121. #endif
  20122. // Refused, answered with a challenge, or closed without an answer
  20123. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20124. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20125. "Content-Length: 0\r\n\r\n",
  20126. ""}) {
  20127. std::promise<int> port_promise;
  20128. auto server_thread = serve_single_response(port_promise, response);
  20129. SSLClient cli("example.com", 443);
  20130. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20131. std::vector<std::string> log;
  20132. cli.set_error_logger(record_errors(log));
  20133. auto res = cli.Get("/");
  20134. server_thread.join();
  20135. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20136. << response;
  20137. }
  20138. }
  20139. #endif
  20140. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20141. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20142. // the chunked coding and drop Content-Length, so a front-end that trusts
  20143. // Content-Length would disagree about where the body ends (response
  20144. // smuggling). The client must reject such a response.
  20145. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20146. for (const char *te : {"chunked", "gzip, chunked"}) {
  20147. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20148. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20149. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20150. "5\r\nhello\r\n0\r\n\r\n";
  20151. with_single_response(response, [&](Client &cli) {
  20152. auto res = cli.Get("/");
  20153. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20154. EXPECT_EQ(Error::Read, res.error()) << te;
  20155. });
  20156. with_single_response(response, [&](Client &cli) {
  20157. auto handle = cli.open_stream("GET", "/");
  20158. EXPECT_FALSE(handle.is_valid()) << te;
  20159. EXPECT_EQ(Error::Read, handle.error) << te;
  20160. });
  20161. }
  20162. }
  20163. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20164. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20165. // closing the connection (unlike a request, which must be rejected).
  20166. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20167. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20168. "Transfer-Encoding: chunked\r\n"
  20169. "Connection: close\r\n"
  20170. "\r\n"
  20171. "5\r\nhello\r\n0\r\n\r\n",
  20172. "HTTP/1.1 200 OK\r\n"
  20173. "Transfer-Encoding: gzip\r\n"
  20174. "Connection: close\r\n"
  20175. "\r\n"
  20176. "hello"}) {
  20177. with_single_response(response, [&](Client &cli) {
  20178. auto res = cli.Get("/");
  20179. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20180. EXPECT_EQ("hello", res->body);
  20181. });
  20182. with_single_response(response, [&](Client &cli) {
  20183. auto handle = cli.open_stream("GET", "/");
  20184. ASSERT_TRUE(handle.is_valid()) << response;
  20185. EXPECT_EQ("hello", read_all(handle));
  20186. });
  20187. }
  20188. }
  20189. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20190. // framing headers describe nothing to read and must not be rejected.
  20191. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20192. const std::string framing = "Content-Length: 5\r\n"
  20193. "Transfer-Encoding: chunked\r\n"
  20194. "Connection: close\r\n"
  20195. "\r\n";
  20196. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20197. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20198. });
  20199. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20200. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20201. });
  20202. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20203. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20204. with_single_response(response, [&](Client &cli) {
  20205. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20206. });
  20207. with_single_response(response, [&](Client &cli) {
  20208. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20209. });
  20210. }
  20211. }
  20212. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20213. // header section, so a stream opened on one has nothing to read, whatever
  20214. // framing or coding headers it carries.
  20215. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20216. struct Case {
  20217. const char *method;
  20218. const char *status;
  20219. };
  20220. // A reader of the declared body reports an early close when nothing
  20221. // follows, and hands back what does.
  20222. struct Framing {
  20223. const char *headers;
  20224. const char *after;
  20225. };
  20226. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20227. Case{"GET", "304 Not Modified"}}) {
  20228. for (const auto &f :
  20229. {Framing{"Content-Length: 5\r\n", ""},
  20230. Framing{"Content-Length: 5\r\n", "hello"},
  20231. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20232. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20233. // Not decoded, so a build without Brotli opens it too
  20234. Framing{"Content-Encoding: br\r\n", ""}}) {
  20235. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20236. "Connection: close\r\n"
  20237. "\r\n" +
  20238. f.after;
  20239. with_single_response(response, [&](Client &cli) {
  20240. auto handle = cli.open_stream(c.method, "/");
  20241. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20242. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20243. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20244. });
  20245. }
  20246. }
  20247. }
  20248. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20249. // response, is faulty framing, so the connection is not reused after it.
  20250. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20251. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20252. "Content-Length: 0\r\n"
  20253. "Transfer-Encoding: chunked\r\n"
  20254. "\r\n"
  20255. "5\r\nhello\r\n0\r\n\r\n",
  20256. "HTTP/1.0 200 Connection established\r\n"
  20257. "Connection: keep-alive\r\n"
  20258. "Transfer-Encoding: chunked\r\n"
  20259. "\r\n"
  20260. "5\r\nhello\r\n0\r\n\r\n"}) {
  20261. with_single_response(response, [&](Client &cli) {
  20262. cli.set_keep_alive(true);
  20263. auto res = cli.Get("/");
  20264. ASSERT_TRUE(res) << response;
  20265. EXPECT_EQ("hello", res->body);
  20266. EXPECT_FALSE(cli.is_socket_open()) << response;
  20267. });
  20268. }
  20269. }
  20270. // A payload max length of 0 means no limit, however the body is framed.
  20271. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20272. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20273. "Transfer-Encoding: chunked\r\n"
  20274. "\r\n"
  20275. "5\r\nhello\r\n0\r\n\r\n",
  20276. "HTTP/1.1 200 OK\r\n"
  20277. "Connection: close\r\n"
  20278. "\r\n"
  20279. "hello"}) {
  20280. with_single_response(response, [&](Client &cli) {
  20281. cli.set_payload_max_length(0);
  20282. auto res = cli.Get("/");
  20283. ASSERT_TRUE(res) << response;
  20284. EXPECT_EQ("hello", res->body) << response;
  20285. });
  20286. }
  20287. }
  20288. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20289. Server svr;
  20290. svr.set_payload_max_length(0);
  20291. svr.Post("/echo", [](const Request &req, Response &res) {
  20292. res.set_content(req.body, "text/plain");
  20293. });
  20294. auto port = svr.bind_to_any_port(HOST);
  20295. thread t = thread([&] { svr.listen_after_bind(); });
  20296. auto se = detail::scope_exit([&] {
  20297. svr.stop();
  20298. t.join();
  20299. ASSERT_FALSE(svr.is_running());
  20300. });
  20301. svr.wait_until_ready();
  20302. Client cli(HOST, port);
  20303. auto res = cli.Post(
  20304. "/echo",
  20305. [](size_t /*offset*/, DataSink &sink) {
  20306. sink.write("hello", 5);
  20307. sink.done();
  20308. return true;
  20309. },
  20310. "text/plain");
  20311. ASSERT_TRUE(res);
  20312. EXPECT_EQ(StatusCode::OK_200, res->status);
  20313. EXPECT_EQ("hello", res->body);
  20314. }
  20315. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20316. TEST_F(OpenStreamTest, Gzip) {
  20317. Client cli("127.0.0.1", port_);
  20318. auto handle = cli.open_stream("GET", "/compressible", {},
  20319. {{"Accept-Encoding", "gzip"}});
  20320. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20321. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20322. }
  20323. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20324. Client cli("127.0.0.1", port_);
  20325. auto handle =
  20326. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20327. {{"Accept-Encoding", "gzip"}});
  20328. ASSERT_TRUE(handle.is_valid());
  20329. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20330. EXPECT_EQ("123456789", read_all(handle));
  20331. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20332. }
  20333. #endif
  20334. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20335. TEST_F(OpenStreamTest, Brotli) {
  20336. Client cli("127.0.0.1", port_);
  20337. auto handle =
  20338. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20339. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20340. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20341. }
  20342. #endif
  20343. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20344. TEST_F(OpenStreamTest, Zstd) {
  20345. Client cli("127.0.0.1", port_);
  20346. auto handle = cli.open_stream("GET", "/compressible", {},
  20347. {{"Accept-Encoding", "zstd"}});
  20348. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20349. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20350. }
  20351. #endif
  20352. #ifdef CPPHTTPLIB_SSL_ENABLED
  20353. class SSLOpenStreamTest : public ::testing::Test {
  20354. protected:
  20355. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20356. void SetUp() override {
  20357. svr_.Get("/hello", [](const Request &, Response &res) {
  20358. res.set_content("Hello SSL World!", "text/plain");
  20359. });
  20360. svr_.Get("/chunked", [](const Request &, Response &res) {
  20361. res.set_chunked_content_provider("text/plain",
  20362. [](size_t offset, DataSink &sink) {
  20363. if (offset < 15) {
  20364. sink.write("chunk", 5);
  20365. return true;
  20366. }
  20367. sink.done();
  20368. return true;
  20369. });
  20370. });
  20371. svr_.Post("/echo", [](const Request &req, Response &res) {
  20372. res.set_content(req.body, req.get_header_value("Content-Type"));
  20373. });
  20374. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20375. std::string body = req.body;
  20376. res.set_chunked_content_provider(
  20377. "text/plain", [body](size_t offset, DataSink &sink) {
  20378. if (offset < body.size()) {
  20379. sink.write(body.data() + offset, body.size() - offset);
  20380. }
  20381. sink.done();
  20382. return true;
  20383. });
  20384. });
  20385. port_ = svr_.bind_to_any_port("127.0.0.1");
  20386. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20387. svr_.wait_until_ready();
  20388. }
  20389. void TearDown() override {
  20390. svr_.stop();
  20391. if (thread_.joinable()) thread_.join();
  20392. }
  20393. SSLServer svr_;
  20394. std::thread thread_;
  20395. int port_ = 0;
  20396. };
  20397. TEST_F(SSLOpenStreamTest, Basic) {
  20398. SSLClient cli("127.0.0.1", port_);
  20399. cli.enable_server_certificate_verification(false);
  20400. auto handle = cli.open_stream("GET", "/hello");
  20401. ASSERT_TRUE(handle.is_valid());
  20402. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20403. }
  20404. TEST_F(SSLOpenStreamTest, Chunked) {
  20405. SSLClient cli("127.0.0.1", port_);
  20406. cli.enable_server_certificate_verification(false);
  20407. auto handle = cli.open_stream("GET", "/chunked");
  20408. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20409. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20410. "Transfer-Encoding") == "chunked");
  20411. auto body = read_all(handle);
  20412. EXPECT_EQ("chunkchunkchunk", body);
  20413. }
  20414. TEST_F(SSLOpenStreamTest, Post) {
  20415. SSLClient cli("127.0.0.1", port_);
  20416. cli.enable_server_certificate_verification(false);
  20417. auto handle =
  20418. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20419. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20420. EXPECT_EQ(200, handle.response->status);
  20421. auto body = read_all(handle);
  20422. EXPECT_EQ("Hello SSL POST", body);
  20423. }
  20424. TEST_F(SSLOpenStreamTest, PostChunked) {
  20425. SSLClient cli("127.0.0.1", port_);
  20426. cli.enable_server_certificate_verification(false);
  20427. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20428. "Chunked SSL Data", "text/plain");
  20429. ASSERT_TRUE(handle.is_valid());
  20430. EXPECT_EQ(200, handle.response->status);
  20431. auto body = read_all(handle);
  20432. EXPECT_EQ("Chunked SSL Data", body);
  20433. }
  20434. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20435. // Content-Length is terminated by the server closing the connection. When the
  20436. // SSL peer sends a close_notify after the body, the client must treat it as a
  20437. // clean EOF and return a successful response rather than an error.
  20438. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20439. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20440. ASSERT_TRUE(svr.is_valid());
  20441. svr.set_keep_alive_max_count(1);
  20442. const std::string expected_body = "Hello from connection-close response!";
  20443. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20444. res.set_content_provider("text/plain",
  20445. [&](size_t offset, DataSink &sink) -> bool {
  20446. if (offset < expected_body.size()) {
  20447. sink.write(expected_body.data() + offset,
  20448. expected_body.size() - offset);
  20449. }
  20450. sink.done();
  20451. return true;
  20452. });
  20453. });
  20454. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20455. auto se = detail::scope_exit([&] {
  20456. svr.stop();
  20457. listen_thread.join();
  20458. ASSERT_FALSE(svr.is_running());
  20459. });
  20460. svr.wait_until_ready();
  20461. SSLClient cli(HOST, PORT);
  20462. cli.enable_server_certificate_verification(false);
  20463. auto res = cli.Get("/no-content-length");
  20464. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20465. EXPECT_EQ(StatusCode::OK_200, res->status);
  20466. EXPECT_EQ(expected_body, res->body);
  20467. }
  20468. #endif // CPPHTTPLIB_SSL_ENABLED
  20469. //==============================================================================
  20470. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20471. // results for various scenarios.
  20472. //==============================================================================
  20473. TEST(ParityTest, GetVsOpenStream) {
  20474. Server svr;
  20475. const std::string path = "/parity";
  20476. const std::string content = "Parity test content: hello world";
  20477. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20478. res.set_content(content, "text/plain");
  20479. });
  20480. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20481. auto se = detail::scope_exit([&] {
  20482. svr.stop();
  20483. t.join();
  20484. ASSERT_FALSE(svr.is_running());
  20485. });
  20486. svr.wait_until_ready();
  20487. Client cli(HOST, PORT);
  20488. // Non-stream path
  20489. auto r1 = cli.Get(path);
  20490. ASSERT_TRUE(r1);
  20491. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20492. // Stream path
  20493. auto h = cli.open_stream("GET", path);
  20494. ASSERT_TRUE(h.is_valid());
  20495. EXPECT_EQ(r1->body, read_all(h));
  20496. }
  20497. // Helper to compress data with provided compressor type T
  20498. template <typename Compressor>
  20499. static std::string compress_payload_for_parity(const std::string &in) {
  20500. std::string out;
  20501. Compressor compressor;
  20502. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20503. [&](const char *data, size_t n) {
  20504. out.append(data, n);
  20505. return true;
  20506. });
  20507. EXPECT_TRUE(ok);
  20508. return out;
  20509. }
  20510. // Helper function for compression parity tests
  20511. template <typename Compressor>
  20512. static void test_compression_parity(const std::string &original,
  20513. const std::string &path,
  20514. const std::string &encoding) {
  20515. const std::string compressed =
  20516. compress_payload_for_parity<Compressor>(original);
  20517. Server svr;
  20518. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20519. res.set_content(compressed, "application/octet-stream");
  20520. res.set_header("Content-Encoding", encoding);
  20521. });
  20522. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20523. auto se = detail::scope_exit([&] {
  20524. svr.stop();
  20525. t.join();
  20526. ASSERT_FALSE(svr.is_running());
  20527. });
  20528. svr.wait_until_ready();
  20529. Client cli(HOST, PORT);
  20530. // Non-streaming
  20531. {
  20532. auto res = cli.Get(path);
  20533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20534. EXPECT_EQ(StatusCode::OK_200, res->status);
  20535. EXPECT_EQ(original, res->body);
  20536. }
  20537. // Streaming
  20538. {
  20539. auto h = cli.open_stream("GET", path);
  20540. ASSERT_TRUE(h.is_valid());
  20541. EXPECT_EQ(original, read_all(h));
  20542. }
  20543. }
  20544. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20545. TEST(ParityTest, Gzip) {
  20546. test_compression_parity<detail::gzip_compressor>(
  20547. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20548. }
  20549. #endif
  20550. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20551. TEST(ParityTest, Brotli) {
  20552. test_compression_parity<detail::brotli_compressor>(
  20553. "Hello, brotli parity test payload", "/parity-br", "br");
  20554. }
  20555. #endif
  20556. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20557. TEST(ParityTest, Zstd) {
  20558. test_compression_parity<detail::zstd_compressor>(
  20559. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20560. }
  20561. #endif
  20562. //==============================================================================
  20563. // New Stream API Tests
  20564. //==============================================================================
  20565. inline std::string read_body(httplib::stream::Result &result) {
  20566. std::string body;
  20567. while (result.next()) {
  20568. body.append(result.data(), result.size());
  20569. }
  20570. return body;
  20571. }
  20572. TEST(ClientConnectionTest, Basic) {
  20573. httplib::ClientConnection conn;
  20574. EXPECT_FALSE(conn.is_open());
  20575. conn.sock = 1;
  20576. EXPECT_TRUE(conn.is_open());
  20577. httplib::ClientConnection conn2(std::move(conn));
  20578. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20579. conn2.sock = INVALID_SOCKET;
  20580. }
  20581. // Unified test server for all stream::* tests
  20582. class StreamApiTest : public ::testing::Test {
  20583. protected:
  20584. void SetUp() override {
  20585. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20586. res.set_content("Hello World!", "text/plain");
  20587. });
  20588. svr_.Get("/echo-params",
  20589. [](const httplib::Request &req, httplib::Response &res) {
  20590. std::string r;
  20591. for (const auto &p : req.params) {
  20592. if (!r.empty()) r += "&";
  20593. r += p.first + "=" + p.second;
  20594. }
  20595. res.set_content(r, "text/plain");
  20596. });
  20597. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20598. res.set_content(req.body, req.get_header_value("Content-Type"));
  20599. });
  20600. svr_.Post("/echo-headers",
  20601. [](const httplib::Request &req, httplib::Response &res) {
  20602. std::string r;
  20603. for (const auto &h : req.headers)
  20604. r += h.first + ": " + h.second + "\n";
  20605. res.set_content(r, "text/plain");
  20606. });
  20607. svr_.Post("/echo-params",
  20608. [](const httplib::Request &req, httplib::Response &res) {
  20609. std::string r = "params:";
  20610. for (const auto &p : req.params)
  20611. r += p.first + "=" + p.second + ";";
  20612. res.set_content(r + " body:" + req.body, "text/plain");
  20613. });
  20614. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20615. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20616. });
  20617. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20618. res.set_content("PUT:" + req.body, "text/plain");
  20619. });
  20620. svr_.Patch("/echo",
  20621. [](const httplib::Request &req, httplib::Response &res) {
  20622. res.set_content("PATCH:" + req.body, "text/plain");
  20623. });
  20624. svr_.Delete(
  20625. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20626. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20627. "text/plain");
  20628. });
  20629. svr_.Get("/head-test",
  20630. [](const httplib::Request &, httplib::Response &res) {
  20631. res.set_content("body for HEAD", "text/plain");
  20632. });
  20633. svr_.Options("/options",
  20634. [](const httplib::Request &, httplib::Response &res) {
  20635. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20636. });
  20637. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20638. svr_.wait_until_ready();
  20639. }
  20640. void TearDown() override {
  20641. svr_.stop();
  20642. if (thread_.joinable()) thread_.join();
  20643. }
  20644. httplib::Server svr_;
  20645. std::thread thread_;
  20646. };
  20647. // stream::Get tests
  20648. TEST_F(StreamApiTest, GetBasic) {
  20649. httplib::Client cli(HOST, PORT);
  20650. auto result = httplib::stream::Get(cli, "/hello");
  20651. ASSERT_TRUE(result.is_valid());
  20652. EXPECT_EQ(200, result.status());
  20653. EXPECT_EQ("Hello World!", read_body(result));
  20654. }
  20655. TEST_F(StreamApiTest, GetWithParams) {
  20656. httplib::Client cli(HOST, PORT);
  20657. httplib::Params params{{"foo", "bar"}};
  20658. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20659. ASSERT_TRUE(result.is_valid());
  20660. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20661. }
  20662. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20663. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20664. httplib::Client cli(HOST, PORT);
  20665. cli.set_payload_max_length(0);
  20666. auto result = httplib::stream::Get(cli, "/hello");
  20667. ASSERT_TRUE(result.is_valid());
  20668. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20669. EXPECT_EQ("Hello World!", read_body(result));
  20670. }
  20671. #endif
  20672. TEST_F(StreamApiTest, GetConnectionError) {
  20673. httplib::Client cli(HOST, 9999);
  20674. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20675. }
  20676. TEST_F(StreamApiTest, Get404) {
  20677. httplib::Client cli(HOST, PORT);
  20678. auto result = httplib::stream::Get(cli, "/nonexistent");
  20679. EXPECT_TRUE(result.is_valid());
  20680. EXPECT_EQ(404, result.status());
  20681. }
  20682. // stream::Post tests
  20683. TEST_F(StreamApiTest, PostBasic) {
  20684. httplib::Client cli(HOST, PORT);
  20685. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20686. "application/json");
  20687. ASSERT_TRUE(result.is_valid());
  20688. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20689. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20690. }
  20691. TEST_F(StreamApiTest, PostWithHeaders) {
  20692. httplib::Client cli(HOST, PORT);
  20693. httplib::Headers headers{{"X-Custom", "value"}};
  20694. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20695. "text/plain");
  20696. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20697. }
  20698. TEST_F(StreamApiTest, PostWithParams) {
  20699. httplib::Client cli(HOST, PORT);
  20700. httplib::Params params{{"k", "v"}};
  20701. auto result =
  20702. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20703. auto body = read_body(result);
  20704. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20705. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20706. }
  20707. TEST_F(StreamApiTest, PostLarge) {
  20708. httplib::Client cli(HOST, PORT);
  20709. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20710. size_t total = 0;
  20711. while (result.next()) {
  20712. total += result.size();
  20713. }
  20714. EXPECT_EQ(100u * 1024u, total);
  20715. }
  20716. // stream::Put/Patch tests
  20717. TEST_F(StreamApiTest, PutAndPatch) {
  20718. httplib::Client cli(HOST, PORT);
  20719. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20720. EXPECT_EQ("PUT:test", read_body(put));
  20721. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20722. EXPECT_EQ("PATCH:test", read_body(patch));
  20723. }
  20724. // stream::Delete tests
  20725. TEST_F(StreamApiTest, Delete) {
  20726. httplib::Client cli(HOST, PORT);
  20727. auto del1 = httplib::stream::Delete(cli, "/resource");
  20728. EXPECT_EQ("Deleted", read_body(del1));
  20729. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20730. EXPECT_EQ("Deleted:data", read_body(del2));
  20731. }
  20732. // stream::Head/Options tests
  20733. TEST_F(StreamApiTest, HeadAndOptions) {
  20734. httplib::Client cli(HOST, PORT);
  20735. auto head = httplib::stream::Head(cli, "/head-test");
  20736. EXPECT_TRUE(head.is_valid());
  20737. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20738. auto opts = httplib::stream::Options(cli, "/options");
  20739. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20740. }
  20741. // SSL stream::* tests
  20742. #ifdef CPPHTTPLIB_SSL_ENABLED
  20743. class SSLStreamApiTest : public ::testing::Test {
  20744. protected:
  20745. void SetUp() override {
  20746. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20747. res.set_content("Hello SSL!", "text/plain");
  20748. });
  20749. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20750. res.set_content(req.body, "text/plain");
  20751. });
  20752. port_ = svr_.bind_to_any_port("127.0.0.1");
  20753. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20754. svr_.wait_until_ready();
  20755. }
  20756. void TearDown() override {
  20757. svr_.stop();
  20758. if (thread_.joinable()) thread_.join();
  20759. }
  20760. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20761. std::thread thread_;
  20762. int port_ = 0;
  20763. };
  20764. TEST_F(SSLStreamApiTest, GetAndPost) {
  20765. httplib::SSLClient cli("127.0.0.1", port_);
  20766. cli.enable_server_certificate_verification(false);
  20767. auto get = httplib::stream::Get(cli, "/hello");
  20768. EXPECT_EQ("Hello SSL!", read_body(get));
  20769. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20770. EXPECT_EQ("test", read_body(post));
  20771. }
  20772. #endif
  20773. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20774. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20775. // BodyReader
  20776. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20777. // Test that read timeout during streaming is detected
  20778. // Use a large content-length response where server delays mid-stream
  20779. Server svr;
  20780. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20781. // Send a large response with delay in the middle
  20782. res.set_content_provider(
  20783. 1000, // content_length
  20784. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20785. if (offset < 100) {
  20786. // Send first 100 bytes immediately
  20787. std::string data(100, 'A');
  20788. sink.write(data.c_str(), data.size());
  20789. return true;
  20790. }
  20791. // Then delay longer than client timeout
  20792. std::this_thread::sleep_for(std::chrono::seconds(3));
  20793. std::string data(900, 'B');
  20794. sink.write(data.c_str(), data.size());
  20795. return true;
  20796. });
  20797. });
  20798. auto port = 8091;
  20799. std::thread t([&]() { svr.listen("localhost", port); });
  20800. svr.wait_until_ready();
  20801. Client cli("localhost", port);
  20802. cli.set_read_timeout(1, 0); // 1 second timeout
  20803. auto handle = cli.open_stream("GET", "/slow-stream");
  20804. ASSERT_TRUE(handle.is_valid());
  20805. char buf[256];
  20806. ssize_t total = 0;
  20807. ssize_t n;
  20808. bool got_error = false;
  20809. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20810. total += n;
  20811. }
  20812. if (n < 0) {
  20813. got_error = true;
  20814. // Should be timeout or read error
  20815. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20816. handle.get_read_error() == Error::Read)
  20817. << "Actual error: " << to_string(handle.get_read_error());
  20818. }
  20819. // Either we got an error, or we got less data than expected
  20820. EXPECT_TRUE(got_error || total < 1000)
  20821. << "Expected timeout but got all " << total << " bytes";
  20822. svr.stop();
  20823. t.join();
  20824. }
  20825. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20826. // Test connection closed detection via BodyReader
  20827. Server svr;
  20828. std::atomic<bool> close_now{false};
  20829. svr.Get("/will-close", [&](const Request &, Response &res) {
  20830. res.set_content_provider(
  20831. 10000, // Large content_length that we won't fully send
  20832. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20833. if (offset < 100) {
  20834. std::string data(100, 'X');
  20835. sink.write(data.c_str(), data.size());
  20836. return true;
  20837. }
  20838. // Wait for signal then abort
  20839. while (!close_now) {
  20840. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20841. }
  20842. return false; // Abort - server will close connection
  20843. });
  20844. });
  20845. auto port = 8092;
  20846. std::thread t([&]() { svr.listen("localhost", port); });
  20847. svr.wait_until_ready();
  20848. Client cli("localhost", port);
  20849. auto handle = cli.open_stream("GET", "/will-close");
  20850. ASSERT_TRUE(handle.is_valid());
  20851. char buf[256];
  20852. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20853. EXPECT_GT(n, 0) << "First read should succeed";
  20854. // Signal server to close
  20855. close_now = true;
  20856. // Keep reading until error or EOF
  20857. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20858. // Keep reading
  20859. }
  20860. // Should get an error since content_length wasn't satisfied
  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. #ifdef CPPHTTPLIB_SSL_ENABLED
  20870. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20871. // Test that read timeout during SSL streaming is detected
  20872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20873. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20874. res.set_content_provider(
  20875. 1000, "text/plain",
  20876. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20877. if (offset < 100) {
  20878. std::string data(100, 'A');
  20879. sink.write(data.c_str(), data.size());
  20880. return true;
  20881. }
  20882. std::this_thread::sleep_for(std::chrono::seconds(3));
  20883. std::string data(900, 'B');
  20884. sink.write(data.c_str(), data.size());
  20885. return true;
  20886. });
  20887. });
  20888. auto port = 8093;
  20889. std::thread t([&]() { svr.listen("localhost", port); });
  20890. svr.wait_until_ready();
  20891. SSLClient cli("localhost", port);
  20892. cli.enable_server_certificate_verification(false);
  20893. cli.set_read_timeout(1, 0); // 1 second timeout
  20894. auto handle = cli.open_stream("GET", "/slow-stream");
  20895. ASSERT_TRUE(handle.is_valid());
  20896. char buf[256];
  20897. ssize_t total = 0;
  20898. ssize_t n;
  20899. bool got_error = false;
  20900. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20901. total += n;
  20902. }
  20903. if (n < 0) {
  20904. got_error = true;
  20905. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20906. handle.get_read_error() == Error::Read)
  20907. << "Actual error: " << to_string(handle.get_read_error());
  20908. }
  20909. EXPECT_TRUE(got_error || total < 1000)
  20910. << "Expected timeout but got all " << total << " bytes";
  20911. svr.stop();
  20912. t.join();
  20913. }
  20914. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20915. // Test SSL connection closed detection
  20916. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20917. std::atomic<bool> close_now{false};
  20918. svr.Get("/will-close", [&](const Request &, Response &res) {
  20919. res.set_content_provider(
  20920. 10000, "text/plain",
  20921. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20922. if (offset < 100) {
  20923. std::string data(100, 'X');
  20924. sink.write(data.c_str(), data.size());
  20925. return true;
  20926. }
  20927. while (!close_now) {
  20928. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20929. }
  20930. return false;
  20931. });
  20932. });
  20933. auto port = 8094;
  20934. std::thread t([&]() { svr.listen("localhost", port); });
  20935. svr.wait_until_ready();
  20936. SSLClient cli("localhost", port);
  20937. cli.enable_server_certificate_verification(false);
  20938. auto handle = cli.open_stream("GET", "/will-close");
  20939. ASSERT_TRUE(handle.is_valid());
  20940. char buf[256];
  20941. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20942. EXPECT_GT(n, 0);
  20943. // Signal server to close
  20944. close_now = true;
  20945. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20946. // Keep reading
  20947. }
  20948. if (n < 0) {
  20949. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20950. handle.get_read_error() == Error::Read)
  20951. << "Actual error: " << to_string(handle.get_read_error());
  20952. }
  20953. svr.stop();
  20954. t.join();
  20955. }
  20956. #endif
  20957. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20958. using namespace httplib;
  20959. // Create a test file
  20960. const char *fname = "etag_testfile.txt";
  20961. const char *content = "etag-content";
  20962. {
  20963. std::ofstream ofs(fname);
  20964. ofs << content;
  20965. ASSERT_TRUE(ofs.good());
  20966. }
  20967. Server svr;
  20968. svr.set_mount_point("/static", ".");
  20969. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20970. svr.wait_until_ready();
  20971. Client cli(HOST, PORT);
  20972. // First request: should get 200 with ETag header
  20973. auto res1 = cli.Get("/static/etag_testfile.txt");
  20974. ASSERT_TRUE(res1);
  20975. ASSERT_EQ(200, res1->status);
  20976. ASSERT_TRUE(res1->has_header("ETag"));
  20977. std::string etag = res1->get_header_value("ETag");
  20978. EXPECT_FALSE(etag.empty());
  20979. // Verify ETag format: W/"hex-hex"
  20980. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20981. EXPECT_EQ('W', etag[0]);
  20982. EXPECT_EQ('/', etag[1]);
  20983. EXPECT_EQ('"', etag[2]);
  20984. EXPECT_EQ('"', etag.back());
  20985. // Exact match: expect 304 Not Modified
  20986. Headers h2 = {{"If-None-Match", etag}};
  20987. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20988. ASSERT_TRUE(res2);
  20989. EXPECT_EQ(304, res2->status);
  20990. // Wildcard match: expect 304 Not Modified
  20991. Headers h3 = {{"If-None-Match", "*"}};
  20992. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20993. ASSERT_TRUE(res3);
  20994. EXPECT_EQ(304, res3->status);
  20995. // Non-matching ETag: expect 200
  20996. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20997. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20998. ASSERT_TRUE(res4);
  20999. EXPECT_EQ(200, res4->status);
  21000. // Multiple ETags with one matching: expect 304
  21001. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21002. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21003. ASSERT_TRUE(res5);
  21004. EXPECT_EQ(304, res5->status);
  21005. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21006. // that equivalent to the single comma-separated list above, so the match on
  21007. // the second line must still be found.
  21008. Headers h6;
  21009. h6.emplace("If-None-Match", "W/\"other\"");
  21010. h6.emplace("If-None-Match", etag);
  21011. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21012. ASSERT_TRUE(res6);
  21013. EXPECT_EQ(304, res6->status);
  21014. svr.stop();
  21015. t.join();
  21016. std::remove(fname);
  21017. }
  21018. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21019. using namespace httplib;
  21020. Server svr;
  21021. svr.set_mount_point("/static", ".");
  21022. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21023. svr.wait_until_ready();
  21024. Client cli(HOST, PORT);
  21025. // Send If-None-Match: * to a non-existent file
  21026. Headers h = {{"If-None-Match", "*"}};
  21027. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21029. EXPECT_EQ(404, res->status);
  21030. svr.stop();
  21031. t.join();
  21032. }
  21033. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21034. using namespace httplib;
  21035. // Create a test file
  21036. const char *fname = "etag_boundary_testfile.txt";
  21037. const char *content = "boundary-test";
  21038. {
  21039. std::ofstream ofs(fname);
  21040. ofs << content;
  21041. ASSERT_TRUE(ofs.good());
  21042. }
  21043. Server svr;
  21044. svr.set_mount_point("/static", ".");
  21045. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21046. svr.wait_until_ready();
  21047. Client cli(HOST, PORT);
  21048. // Get the actual ETag
  21049. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21050. ASSERT_TRUE(res1);
  21051. ASSERT_EQ(200, res1->status);
  21052. ASSERT_TRUE(res1->has_header("ETag"));
  21053. std::string etag = res1->get_header_value("ETag");
  21054. // Test 1: Very long ETag value (longer than actual ETag)
  21055. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21056. Headers h1 = {{"If-None-Match", "W/"
  21057. "\"very-long-etag-value-that-is-much-longer-"
  21058. "than-the-actual-etag-value\""}};
  21059. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21060. ASSERT_TRUE(res2);
  21061. EXPECT_EQ(200, res2->status); // Should not match
  21062. // Test 2: Long string followed by wildcard
  21063. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21064. // string)
  21065. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21066. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21067. ASSERT_TRUE(res3);
  21068. EXPECT_EQ(304, res3->status); // Should match on "*"
  21069. // Test 3: Wildcard followed by long string
  21070. // Should match on "*" immediately and return 304
  21071. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21072. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21073. ASSERT_TRUE(res4);
  21074. EXPECT_EQ(304, res4->status); // Should match on "*"
  21075. // Test 4: Multiple long non-matching values
  21076. // Should NOT match and return 200 (test that all comparisons are safe)
  21077. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21078. "W/\"second-long-non-matching-value\", "
  21079. "W/\"third-long-non-matching-value\""}};
  21080. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21081. ASSERT_TRUE(res5);
  21082. EXPECT_EQ(200, res5->status); // Should not match
  21083. // Test 5: Single character that is not "*" (edge case)
  21084. Headers h5 = {{"If-None-Match", "X"}};
  21085. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21086. ASSERT_TRUE(res6);
  21087. EXPECT_EQ(200, res6->status); // Should not match
  21088. svr.stop();
  21089. t.join();
  21090. std::remove(fname);
  21091. }
  21092. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21093. using namespace httplib;
  21094. // Create a test file
  21095. const char *fname = "ims_testfile.txt";
  21096. const char *content = "if-modified-since-test";
  21097. {
  21098. std::ofstream ofs(fname);
  21099. ofs << content;
  21100. ASSERT_TRUE(ofs.good());
  21101. }
  21102. Server svr;
  21103. svr.set_mount_point("/static", ".");
  21104. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21105. svr.wait_until_ready();
  21106. Client cli(HOST, PORT);
  21107. // First request: should get 200 with Last-Modified header
  21108. auto res1 = cli.Get("/static/ims_testfile.txt");
  21109. ASSERT_TRUE(res1);
  21110. ASSERT_EQ(200, res1->status);
  21111. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21112. std::string last_modified = res1->get_header_value("Last-Modified");
  21113. EXPECT_FALSE(last_modified.empty());
  21114. // If-Modified-Since with same time: expect 304
  21115. Headers h2 = {{"If-Modified-Since", last_modified}};
  21116. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21117. ASSERT_TRUE(res2);
  21118. EXPECT_EQ(304, res2->status);
  21119. // If-Modified-Since with future time: expect 304
  21120. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21121. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21122. ASSERT_TRUE(res3);
  21123. EXPECT_EQ(304, res3->status);
  21124. // If-Modified-Since with past time: expect 200
  21125. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21126. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21127. ASSERT_TRUE(res4);
  21128. EXPECT_EQ(200, res4->status);
  21129. // If-None-Match takes precedence over If-Modified-Since
  21130. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21131. ASSERT_TRUE(res1->has_header("ETag"));
  21132. std::string etag = res1->get_header_value("ETag");
  21133. Headers h5 = {{"If-None-Match", etag},
  21134. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21135. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21136. ASSERT_TRUE(res5);
  21137. EXPECT_EQ(304, res5->status);
  21138. svr.stop();
  21139. t.join();
  21140. std::remove(fname);
  21141. }
  21142. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21143. using namespace httplib;
  21144. Server svr;
  21145. // Endpoint that returns compressible content
  21146. svr.Get("/compressible", [](const Request &, Response &res) {
  21147. // Return a large enough body to trigger compression
  21148. std::string body(1000, 'a');
  21149. res.set_content(body, "text/plain");
  21150. });
  21151. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21152. svr.wait_until_ready();
  21153. Client cli(HOST, PORT);
  21154. // Request with gzip support: should get Vary header when compressed
  21155. cli.set_compress(true);
  21156. auto res1 = cli.Get("/compressible");
  21157. ASSERT_TRUE(res1);
  21158. EXPECT_EQ(200, res1->status);
  21159. // If Content-Encoding is set, Vary should also be set
  21160. if (res1->has_header("Content-Encoding")) {
  21161. EXPECT_TRUE(res1->has_header("Vary"));
  21162. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21163. }
  21164. // Request without Accept-Encoding header: should not have compression
  21165. Headers h_no_compress;
  21166. auto res2 = cli.Get("/compressible", h_no_compress);
  21167. ASSERT_TRUE(res2);
  21168. EXPECT_EQ(200, res2->status);
  21169. // Verify Vary header is present when compression is applied
  21170. // (the exact behavior depends on server configuration)
  21171. svr.stop();
  21172. t.join();
  21173. }
  21174. TEST(ETagTest, IfRangeWithETag) {
  21175. using namespace httplib;
  21176. // Create a test file with known content
  21177. const char *fname = "if_range_testfile.txt";
  21178. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21179. {
  21180. std::ofstream ofs(fname);
  21181. ofs << content;
  21182. ASSERT_TRUE(ofs.good());
  21183. }
  21184. Server svr;
  21185. svr.set_mount_point("/static", ".");
  21186. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21187. svr.wait_until_ready();
  21188. Client cli(HOST, PORT);
  21189. // First request: get ETag
  21190. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21191. ASSERT_TRUE(res1);
  21192. ASSERT_EQ(200, res1->status);
  21193. ASSERT_TRUE(res1->has_header("ETag"));
  21194. std::string etag = res1->get_header_value("ETag");
  21195. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21196. // Since our server generates weak ETags (W/"..."), If-Range with our
  21197. // ETag should NOT result in partial content - it should return full content.
  21198. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21199. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21200. ASSERT_TRUE(res2);
  21201. // Weak ETag in If-Range -> full content (200), not partial (206)
  21202. EXPECT_EQ(200, res2->status);
  21203. EXPECT_EQ(content, res2->body);
  21204. EXPECT_FALSE(res2->has_header("Content-Range"));
  21205. // Range request with non-matching If-Range (ETag): should get 200 (full
  21206. // content)
  21207. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21208. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21209. ASSERT_TRUE(res3);
  21210. EXPECT_EQ(200, res3->status);
  21211. EXPECT_EQ(content, res3->body);
  21212. EXPECT_FALSE(res3->has_header("Content-Range"));
  21213. // Range request with strong ETag (hypothetical - our server doesn't generate
  21214. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21215. // should return full content)
  21216. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21217. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21218. ASSERT_TRUE(res4);
  21219. EXPECT_EQ(200, res4->status);
  21220. EXPECT_EQ(content, res4->body);
  21221. EXPECT_FALSE(res4->has_header("Content-Range"));
  21222. svr.stop();
  21223. t.join();
  21224. std::remove(fname);
  21225. }
  21226. TEST(ETagTest, IfRangeWithDate) {
  21227. using namespace httplib;
  21228. // Create a test file
  21229. const char *fname = "if_range_date_testfile.txt";
  21230. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21231. {
  21232. std::ofstream ofs(fname);
  21233. ofs << content;
  21234. ASSERT_TRUE(ofs.good());
  21235. }
  21236. Server svr;
  21237. svr.set_mount_point("/static", ".");
  21238. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21239. svr.wait_until_ready();
  21240. Client cli(HOST, PORT);
  21241. // First request: get Last-Modified
  21242. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21243. ASSERT_TRUE(res1);
  21244. ASSERT_EQ(200, res1->status);
  21245. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21246. std::string last_modified = res1->get_header_value("Last-Modified");
  21247. // Range request with matching If-Range (date): should get 206
  21248. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21249. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21250. ASSERT_TRUE(res2);
  21251. EXPECT_EQ(206, res2->status);
  21252. EXPECT_EQ("FGHIJ", res2->body);
  21253. // Range request with old If-Range date: should get 200 (full content)
  21254. Headers h3 = {{"Range", "bytes=5-9"},
  21255. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21256. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21257. ASSERT_TRUE(res3);
  21258. EXPECT_EQ(200, res3->status);
  21259. EXPECT_EQ(content, res3->body);
  21260. // Range request with future If-Range date: should get 206
  21261. Headers h4 = {{"Range", "bytes=0-4"},
  21262. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21263. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21264. ASSERT_TRUE(res4);
  21265. EXPECT_EQ(206, res4->status);
  21266. EXPECT_EQ("ABCDE", res4->body);
  21267. svr.stop();
  21268. t.join();
  21269. std::remove(fname);
  21270. }
  21271. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21272. using namespace httplib;
  21273. const char *fname = "etag_malformed.txt";
  21274. const char *content = "malformed-etag";
  21275. {
  21276. std::ofstream ofs(fname);
  21277. ofs << content;
  21278. ASSERT_TRUE(ofs.good());
  21279. }
  21280. Server svr;
  21281. svr.set_mount_point("/static", ".");
  21282. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21283. svr.wait_until_ready();
  21284. Client cli(HOST, PORT);
  21285. // baseline: should get 200 and an ETag
  21286. auto res1 = cli.Get("/static/etag_malformed.txt");
  21287. ASSERT_TRUE(res1);
  21288. ASSERT_EQ(200, res1->status);
  21289. ASSERT_TRUE(res1->has_header("ETag"));
  21290. // Malformed ETag value (missing quotes) should be treated as non-matching
  21291. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21292. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21293. ASSERT_TRUE(res_bad);
  21294. EXPECT_EQ(200, res_bad->status);
  21295. // Whitespace-only header value should be considered invalid / non-matching
  21296. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21297. "Host: localhost\r\n"
  21298. "If-None-Match: \r\n"
  21299. "Connection: close\r\n"
  21300. "\r\n";
  21301. std::string out;
  21302. ASSERT_TRUE(send_request(5, raw_req, &out));
  21303. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21304. svr.stop();
  21305. t.join();
  21306. std::remove(fname);
  21307. }
  21308. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21309. using namespace httplib;
  21310. const char *fname = "ims_invalid_format.txt";
  21311. const char *content = "ims-bad-format";
  21312. {
  21313. std::ofstream ofs(fname);
  21314. ofs << content;
  21315. ASSERT_TRUE(ofs.good());
  21316. }
  21317. Server svr;
  21318. svr.set_mount_point("/static", ".");
  21319. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21320. svr.wait_until_ready();
  21321. Client cli(HOST, PORT);
  21322. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21323. ASSERT_TRUE(res1);
  21324. ASSERT_EQ(200, res1->status);
  21325. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21326. // If-Modified-Since with invalid format should not result in 304
  21327. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21328. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21329. ASSERT_TRUE(res_bad);
  21330. EXPECT_EQ(200, res_bad->status);
  21331. // If-Range with invalid date format should be treated as mismatch -> full
  21332. // content (200)
  21333. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21334. {"If-Range", "invalid-date"}};
  21335. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21336. ASSERT_TRUE(res_ifrange);
  21337. EXPECT_EQ(200, res_ifrange->status);
  21338. svr.stop();
  21339. t.join();
  21340. std::remove(fname);
  21341. }
  21342. TEST(ETagTest, IfRangeWithMalformedETag) {
  21343. using namespace httplib;
  21344. const char *fname = "ifrange_malformed.txt";
  21345. const std::string content = "0123456789";
  21346. {
  21347. std::ofstream ofs(fname);
  21348. ofs << content;
  21349. ASSERT_TRUE(ofs.good());
  21350. }
  21351. Server svr;
  21352. svr.set_mount_point("/static", ".");
  21353. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21354. svr.wait_until_ready();
  21355. Client cli(HOST, PORT);
  21356. // First request: get ETag
  21357. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21358. ASSERT_TRUE(res1);
  21359. ASSERT_EQ(200, res1->status);
  21360. ASSERT_TRUE(res1->has_header("ETag"));
  21361. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21362. // full content (200)
  21363. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21364. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21365. ASSERT_TRUE(res2);
  21366. EXPECT_EQ(200, res2->status);
  21367. EXPECT_EQ(content, res2->body);
  21368. svr.stop();
  21369. t.join();
  21370. std::remove(fname);
  21371. }
  21372. TEST(ETagTest, ExtremeLargeDateValues) {
  21373. using namespace httplib;
  21374. const char *fname = "ims_extreme_date.txt";
  21375. const char *content = "ims-extreme-date";
  21376. {
  21377. std::ofstream ofs(fname);
  21378. ofs << content;
  21379. ASSERT_TRUE(ofs.good());
  21380. }
  21381. Server svr;
  21382. svr.set_mount_point("/static", ".");
  21383. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21384. svr.wait_until_ready();
  21385. Client cli(HOST, PORT);
  21386. auto res1 = cli.Get(std::string("/static/") + fname);
  21387. ASSERT_TRUE(res1);
  21388. ASSERT_EQ(200, res1->status);
  21389. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21390. // Extremely large year that may overflow date parsing routines.
  21391. Headers h_large_date = {
  21392. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21393. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21394. ASSERT_TRUE(res_bad);
  21395. // Expect server to treat this as invalid/mismatch and return full content
  21396. EXPECT_EQ(200, res_bad->status);
  21397. // If-Range with extremely large date should be treated as mismatch -> full
  21398. // content (200)
  21399. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21400. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21401. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21402. ASSERT_TRUE(res_ifrange);
  21403. EXPECT_EQ(200, res_ifrange->status);
  21404. svr.stop();
  21405. t.join();
  21406. std::remove(fname);
  21407. }
  21408. TEST(ETagTest, NegativeFileModificationTime) {
  21409. using namespace httplib;
  21410. const char *fname = "ims_negative_mtime.txt";
  21411. const std::string content = "negative-mtime";
  21412. {
  21413. std::ofstream ofs(fname);
  21414. ofs << content;
  21415. ASSERT_TRUE(ofs.good());
  21416. }
  21417. // Try to set file mtime to a negative value. This may fail on some
  21418. // platforms/filesystems; if it fails, the test will still verify server
  21419. // behaves safely by performing a regular conditional request.
  21420. #if defined(__APPLE__) || defined(__linux__)
  21421. bool set_negative = false;
  21422. do {
  21423. struct timeval times[2];
  21424. // access time: now
  21425. times[0].tv_sec = time(nullptr);
  21426. times[0].tv_usec = 0;
  21427. // modification time: negative (e.g., -1)
  21428. times[1].tv_sec = -1;
  21429. times[1].tv_usec = 0;
  21430. if (utimes(fname, times) == 0) { set_negative = true; }
  21431. } while (0);
  21432. #else
  21433. bool set_negative = false;
  21434. #endif
  21435. Server svr;
  21436. svr.set_mount_point("/static", ".");
  21437. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21438. svr.wait_until_ready();
  21439. Client cli(HOST, PORT);
  21440. auto res1 = cli.Get(std::string("/static/") + fname);
  21441. ASSERT_TRUE(res1);
  21442. ASSERT_EQ(200, res1->status);
  21443. bool has_last_modified = res1->has_header("Last-Modified");
  21444. std::string last_modified;
  21445. if (has_last_modified) {
  21446. last_modified = res1->get_header_value("Last-Modified");
  21447. }
  21448. if (set_negative) {
  21449. // If we successfully set a negative mtime, ensure server returns a
  21450. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21451. // with an old date and ensure server handles it without crash.
  21452. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21453. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21454. ASSERT_TRUE(res2);
  21455. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21456. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21457. } else {
  21458. // Could not set negative mtime on this platform; fall back to verifying
  21459. // that normal invalid/malformed dates are treated safely (non-304).
  21460. Headers h_bad_date = {
  21461. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21462. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21463. ASSERT_TRUE(res_bad);
  21464. EXPECT_EQ(200, res_bad->status);
  21465. }
  21466. svr.stop();
  21467. t.join();
  21468. std::remove(fname);
  21469. }
  21470. //==============================================================================
  21471. // Integration Tests with Server
  21472. //==============================================================================
  21473. class SSEIntegrationTest : public ::testing::Test {
  21474. protected:
  21475. void SetUp() override {
  21476. stop_server_.store(false);
  21477. events_.clear();
  21478. server_ = httplib::detail::make_unique<Server>();
  21479. setup_server();
  21480. start_server();
  21481. }
  21482. void TearDown() override {
  21483. stop_server_.store(true);
  21484. event_cv_.notify_all();
  21485. server_->stop();
  21486. if (server_thread_.joinable()) { server_thread_.join(); }
  21487. }
  21488. void setup_server() {
  21489. // Simple SSE endpoint
  21490. server_->Get("/events", [this](const Request &req, Response &res) {
  21491. auto last_id = req.get_header_value("Last-Event-ID");
  21492. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21493. res.set_chunked_content_provider(
  21494. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21495. std::unique_lock<std::mutex> lock(event_mutex_);
  21496. if (event_cv_.wait_for(
  21497. lock, std::chrono::milliseconds(200), [this] {
  21498. return !events_.empty() || stop_server_.load();
  21499. })) {
  21500. if (stop_server_.load()) { return false; }
  21501. if (!events_.empty()) {
  21502. std::string event = events_.front();
  21503. events_.erase(events_.begin());
  21504. sink.write(event.data(), event.size());
  21505. return true;
  21506. }
  21507. }
  21508. return !stop_server_.load();
  21509. });
  21510. });
  21511. // Endpoint that returns error
  21512. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21513. res.status = 500;
  21514. res.set_content("Internal Server Error", "text/plain");
  21515. });
  21516. // Endpoint for custom event types
  21517. server_->Get("/custom-events", [](const Request &, Response &res) {
  21518. res.set_chunked_content_provider(
  21519. "text/event-stream", [](size_t offset, DataSink &sink) {
  21520. if (offset == 0) {
  21521. std::string event = "event: update\ndata: updated\n\n"
  21522. "event: delete\ndata: deleted\n\n";
  21523. sink.write(event.data(), event.size());
  21524. }
  21525. return false; // End stream after sending
  21526. });
  21527. });
  21528. }
  21529. void start_server() {
  21530. port_ = server_->bind_to_any_port(HOST);
  21531. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21532. // Wait for server to start
  21533. while (!server_->is_running()) {
  21534. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21535. }
  21536. }
  21537. int get_port() const { return port_; }
  21538. void send_event(const std::string &event) {
  21539. std::lock_guard<std::mutex> lock(event_mutex_);
  21540. events_.push_back(event);
  21541. event_cv_.notify_all();
  21542. }
  21543. std::unique_ptr<Server> server_;
  21544. std::thread server_thread_;
  21545. std::mutex event_mutex_;
  21546. std::condition_variable event_cv_;
  21547. std::vector<std::string> events_;
  21548. std::atomic<bool> stop_server_{false};
  21549. std::string last_received_event_id_;
  21550. int port_ = 0;
  21551. };
  21552. //==============================================================================
  21553. // SSE Parsing Tests
  21554. //==============================================================================
  21555. class SSEParsingTest : public SSEIntegrationTest {
  21556. protected:
  21557. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21558. // A trailing sentinel event tells when the whole stream has been parsed.
  21559. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21560. auto body = stream + "event: end\ndata: end\n\n";
  21561. server_->Get("/parse", [body](const Request &, Response &res) {
  21562. res.set_content(body, "text/event-stream");
  21563. });
  21564. return collect("/parse");
  21565. }
  21566. // Runs SSEClient against path until an "end" event arrives and returns the
  21567. // messages dispatched before it
  21568. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21569. Client client(HOST, get_port());
  21570. sse::SSEClient sse(client, path);
  21571. std::mutex mutex;
  21572. std::condition_variable cv;
  21573. std::vector<sse::SSEMessage> messages;
  21574. auto done = false;
  21575. sse.on_message([&](const sse::SSEMessage &msg) {
  21576. std::lock_guard<std::mutex> lock(mutex);
  21577. // Ignore a replay from a reconnect that races with stop()
  21578. if (!done) { messages.push_back(msg); }
  21579. });
  21580. sse.on_event("end", [&](const sse::SSEMessage &) {
  21581. std::lock_guard<std::mutex> lock(mutex);
  21582. done = true;
  21583. cv.notify_all();
  21584. });
  21585. sse.set_reconnect_interval(100);
  21586. sse.start_async();
  21587. {
  21588. std::unique_lock<std::mutex> lock(mutex);
  21589. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21590. }
  21591. sse.stop();
  21592. EXPECT_TRUE(done);
  21593. return messages;
  21594. }
  21595. };
  21596. TEST_F(SSEParsingTest, SingleLineData) {
  21597. auto msgs = parse("data: hello\n\n");
  21598. ASSERT_EQ(msgs.size(), 1u);
  21599. EXPECT_EQ(msgs[0].data, "hello");
  21600. EXPECT_EQ(msgs[0].event, "message");
  21601. }
  21602. TEST_F(SSEParsingTest, MultiLineData) {
  21603. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21604. ASSERT_EQ(msgs.size(), 1u);
  21605. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21606. }
  21607. TEST_F(SSEParsingTest, CustomEventType) {
  21608. auto msgs = parse("event: update\ndata: payload\n\n");
  21609. ASSERT_EQ(msgs.size(), 1u);
  21610. EXPECT_EQ(msgs[0].event, "update");
  21611. EXPECT_EQ(msgs[0].data, "payload");
  21612. }
  21613. TEST_F(SSEParsingTest, EventIdHandling) {
  21614. auto msgs = parse("id: 12345\ndata: test\n\n");
  21615. ASSERT_EQ(msgs.size(), 1u);
  21616. EXPECT_EQ(msgs[0].id, "12345");
  21617. }
  21618. TEST_F(SSEParsingTest, EmptyEventId) {
  21619. auto msgs = parse("id:\ndata: test\n\n");
  21620. ASSERT_EQ(msgs.size(), 1u);
  21621. EXPECT_EQ(msgs[0].id, "");
  21622. }
  21623. TEST_F(SSEParsingTest, CommentsIgnored) {
  21624. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21625. ASSERT_EQ(msgs.size(), 1u);
  21626. EXPECT_EQ(msgs[0].data, "hello");
  21627. EXPECT_EQ(msgs[0].event, "message");
  21628. }
  21629. TEST_F(SSEParsingTest, ColonInValue) {
  21630. auto msgs = parse("data: hello:world:test\n\n");
  21631. ASSERT_EQ(msgs.size(), 1u);
  21632. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21633. }
  21634. TEST_F(SSEParsingTest, FieldNameOnly) {
  21635. // A line without a colon is a field name with an empty value
  21636. auto msgs = parse("data\n\n");
  21637. ASSERT_EQ(msgs.size(), 1u);
  21638. EXPECT_EQ(msgs[0].data, "");
  21639. }
  21640. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21641. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21642. ASSERT_EQ(msgs.size(), 1u);
  21643. EXPECT_EQ(msgs[0].event, "update");
  21644. EXPECT_EQ(msgs[0].data, "hello");
  21645. }
  21646. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21647. auto msgs = parse("data\r\n\r\n");
  21648. ASSERT_EQ(msgs.size(), 1u);
  21649. EXPECT_EQ(msgs[0].data, "");
  21650. }
  21651. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21652. auto msgs = parse("event: update\rdata: hello\r\r");
  21653. ASSERT_EQ(msgs.size(), 1u);
  21654. EXPECT_EQ(msgs[0].event, "update");
  21655. EXPECT_EQ(msgs[0].data, "hello");
  21656. }
  21657. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21658. // Chunk boundaries fall inside every \r\n and right before the first one
  21659. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21660. "\n\r", "\nevent: end\ndata: end\n\n"};
  21661. server_->Get("/split", [chunks](const Request &, Response &res) {
  21662. auto i = std::make_shared<size_t>(0);
  21663. res.set_chunked_content_provider(
  21664. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21665. if (*i == chunks.size()) {
  21666. sink.done();
  21667. } else {
  21668. sink.write(chunks[*i].data(), chunks[*i].size());
  21669. (*i)++;
  21670. }
  21671. return true;
  21672. });
  21673. });
  21674. auto msgs = collect("/split");
  21675. ASSERT_EQ(msgs.size(), 1u);
  21676. EXPECT_EQ(msgs[0].event, "update");
  21677. EXPECT_EQ(msgs[0].data, "hello");
  21678. }
  21679. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21680. // Only a BOM at the start of the stream is ignored
  21681. auto msgs = parse("\xEF\xBB\xBF"
  21682. "data: first\n\n"
  21683. "\xEF\xBB\xBF"
  21684. "data: second\n\n");
  21685. ASSERT_EQ(msgs.size(), 1u);
  21686. EXPECT_EQ(msgs[0].data, "first");
  21687. }
  21688. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21689. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21690. ASSERT_EQ(msgs.size(), 1u);
  21691. EXPECT_EQ(msgs[0].data, "hello");
  21692. EXPECT_EQ(msgs[0].event, "message");
  21693. }
  21694. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21695. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21696. ASSERT_EQ(msgs.size(), 2u);
  21697. EXPECT_EQ(msgs[0].data, "hello");
  21698. EXPECT_EQ(msgs[1].data, "hello");
  21699. }
  21700. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21701. // An event without data is not dispatched, and its type must not leak
  21702. // into the next event
  21703. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21704. ASSERT_EQ(msgs.size(), 1u);
  21705. EXPECT_EQ(msgs[0].event, "message");
  21706. EXPECT_EQ(msgs[0].data, "hello");
  21707. }
  21708. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21709. // Also when the empty field replaces an earlier type
  21710. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21711. ASSERT_EQ(msgs.size(), 2u);
  21712. EXPECT_EQ(msgs[0].event, "message");
  21713. EXPECT_EQ(msgs[1].event, "message");
  21714. }
  21715. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21716. // The first connection sends only an id; the second echoes back the
  21717. // Last-Event-ID it was reconnected with
  21718. std::atomic<int> connection_count{0};
  21719. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21720. if (connection_count++ == 0) {
  21721. res.set_content("id: 42\n\n", "text/event-stream");
  21722. } else {
  21723. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21724. "\n\nevent: end\ndata: end\n\n",
  21725. "text/event-stream");
  21726. }
  21727. });
  21728. auto msgs = collect("/id-only");
  21729. ASSERT_EQ(msgs.size(), 1u);
  21730. EXPECT_EQ(msgs[0].data, "42");
  21731. }
  21732. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21733. // The first connection sets an id and then clears it with an empty one; the
  21734. // second reports whether it was reconnected with a Last-Event-ID
  21735. std::atomic<int> connection_count{0};
  21736. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21737. if (connection_count++ == 0) {
  21738. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21739. "text/event-stream");
  21740. } else {
  21741. res.set_content(
  21742. std::string("data: ") +
  21743. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21744. "\n\nevent: end\ndata: end\n\n",
  21745. "text/event-stream");
  21746. }
  21747. });
  21748. auto msgs = collect("/id-clear");
  21749. ASSERT_EQ(msgs.size(), 3u);
  21750. EXPECT_EQ(msgs[0].id, "1");
  21751. EXPECT_EQ(msgs[1].id, "");
  21752. EXPECT_EQ(msgs[2].data, "not sent");
  21753. }
  21754. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21755. // The first connection sets an id and then sends ids that cannot be carried
  21756. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21757. // with
  21758. std::atomic<int> connection_count{0};
  21759. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21760. if (connection_count++ == 0) {
  21761. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21762. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21763. "text/event-stream");
  21764. } else {
  21765. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21766. "\n\nevent: end\ndata: end\n\n",
  21767. "text/event-stream");
  21768. }
  21769. });
  21770. auto msgs = collect("/id-unsendable");
  21771. ASSERT_EQ(msgs.size(), 1u);
  21772. EXPECT_EQ(msgs[0].data, "42");
  21773. }
  21774. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21775. auto msgs = parse("event: notification\nid: evt-42\n"
  21776. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21777. ASSERT_EQ(msgs.size(), 1u);
  21778. EXPECT_EQ(msgs[0].event, "notification");
  21779. EXPECT_EQ(msgs[0].id, "evt-42");
  21780. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21781. }
  21782. TEST(SSEMessageTest, Clear) {
  21783. sse::SSEMessage msg;
  21784. msg.event = "custom";
  21785. msg.data = "some data";
  21786. msg.id = "123";
  21787. msg.clear();
  21788. EXPECT_EQ(msg.event, "message");
  21789. EXPECT_EQ(msg.data, "");
  21790. EXPECT_EQ(msg.id, "");
  21791. }
  21792. //==============================================================================
  21793. // SSE Integration Tests
  21794. //==============================================================================
  21795. // Test: Successful connection and on_open callback
  21796. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21797. // Add a simple endpoint that sends one event and closes
  21798. server_->Get("/simple-event", [](const Request &, Response &res) {
  21799. res.set_chunked_content_provider(
  21800. "text/event-stream", [](size_t offset, DataSink &sink) {
  21801. if (offset == 0) {
  21802. std::string event = "data: hello\n\n";
  21803. sink.write(event.data(), event.size());
  21804. }
  21805. return false; // Close stream after sending
  21806. });
  21807. });
  21808. Client client("localhost", get_port());
  21809. sse::SSEClient sse(client, "/simple-event");
  21810. std::atomic<bool> open_called{false};
  21811. std::atomic<bool> message_received{false};
  21812. sse.on_open([&open_called]() { open_called.store(true); });
  21813. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21814. if (msg.data == "hello") { message_received.store(true); }
  21815. });
  21816. sse.set_reconnect_interval(100);
  21817. sse.set_max_reconnect_attempts(1);
  21818. // Start async
  21819. sse.start_async();
  21820. // Wait for message to be processed
  21821. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21822. sse.stop();
  21823. EXPECT_TRUE(open_called.load());
  21824. EXPECT_TRUE(message_received.load());
  21825. }
  21826. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21827. // A data line that never ends.
  21828. server_->Get("/endless-line", [](const Request &, Response &res) {
  21829. res.set_chunked_content_provider(
  21830. "text/event-stream", [](size_t offset, DataSink &sink) {
  21831. if (offset == 0) { sink.write("data: ", 6); }
  21832. std::string chunk(64 * 1024, 'A');
  21833. return sink.write(chunk.data(), chunk.size());
  21834. });
  21835. });
  21836. Client client("localhost", get_port());
  21837. sse::SSEClient sse(client, "/endless-line");
  21838. std::atomic<bool> too_long{false};
  21839. sse.on_error([&](Error err) {
  21840. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21841. });
  21842. sse.set_max_reconnect_attempts(1);
  21843. sse.start_async();
  21844. for (int i = 0; i < 500 && !too_long; i++) {
  21845. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21846. }
  21847. sse.stop();
  21848. EXPECT_TRUE(too_long);
  21849. }
  21850. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21851. // Far more in all than the client's payload limit below.
  21852. server_->Get("/many-events", [](const Request &, Response &res) {
  21853. res.set_chunked_content_provider(
  21854. "text/event-stream", [](size_t offset, DataSink &sink) {
  21855. if (offset == 0) {
  21856. std::string events;
  21857. for (int i = 0; i < 1000; i++) {
  21858. events += "data: message\n\n";
  21859. }
  21860. sink.write(events.data(), events.size());
  21861. }
  21862. return false;
  21863. });
  21864. });
  21865. Client client("localhost", get_port());
  21866. client.set_payload_max_length(1024);
  21867. sse::SSEClient sse(client, "/many-events");
  21868. std::atomic<int> messages{0};
  21869. std::atomic<bool> too_large{false};
  21870. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21871. sse.on_error([&](Error err) {
  21872. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21873. });
  21874. sse.set_max_reconnect_attempts(1);
  21875. sse.start_async();
  21876. for (int i = 0; i < 500 && messages < 1000; i++) {
  21877. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21878. }
  21879. sse.stop();
  21880. EXPECT_GE(messages.load(), 1000);
  21881. EXPECT_FALSE(too_large);
  21882. }
  21883. // Test: on_message callback
  21884. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21885. // Endpoint that sends multiple events then closes
  21886. server_->Get("/multi-event", [](const Request &, Response &res) {
  21887. res.set_chunked_content_provider(
  21888. "text/event-stream", [](size_t offset, DataSink &sink) {
  21889. if (offset == 0) {
  21890. std::string events = "data: message1\n\ndata: message2\n\n";
  21891. sink.write(events.data(), events.size());
  21892. }
  21893. return false;
  21894. });
  21895. });
  21896. Client client("localhost", get_port());
  21897. sse::SSEClient sse(client, "/multi-event");
  21898. std::vector<std::string> received_messages;
  21899. std::mutex messages_mutex;
  21900. sse.on_message([&](const sse::SSEMessage &msg) {
  21901. std::lock_guard<std::mutex> lock(messages_mutex);
  21902. received_messages.push_back(msg.data);
  21903. });
  21904. sse.set_reconnect_interval(100);
  21905. sse.set_max_reconnect_attempts(1);
  21906. sse.start_async();
  21907. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21908. sse.stop();
  21909. std::lock_guard<std::mutex> lock(messages_mutex);
  21910. EXPECT_GE(received_messages.size(), 2u);
  21911. if (received_messages.size() >= 2) {
  21912. EXPECT_EQ(received_messages[0], "message1");
  21913. EXPECT_EQ(received_messages[1], "message2");
  21914. }
  21915. }
  21916. // Test: on_event for specific types
  21917. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21918. Client client("localhost", get_port());
  21919. sse::SSEClient sse(client, "/custom-events");
  21920. std::atomic<bool> update_received{false};
  21921. std::atomic<bool> delete_received{false};
  21922. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21923. if (msg.data == "updated") { update_received.store(true); }
  21924. });
  21925. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21926. if (msg.data == "deleted") { delete_received.store(true); }
  21927. });
  21928. sse.set_max_reconnect_attempts(1);
  21929. sse.start_async();
  21930. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21931. sse.stop();
  21932. EXPECT_TRUE(update_received.load());
  21933. EXPECT_TRUE(delete_received.load());
  21934. }
  21935. // Test: on_error callback on connection failure
  21936. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21937. // Connect to a non-existent port
  21938. Client client("localhost", 59999);
  21939. sse::SSEClient sse(client, "/events");
  21940. std::atomic<bool> error_called{false};
  21941. Error received_error = Error::Success;
  21942. sse.on_error([&](Error err) {
  21943. error_called.store(true);
  21944. received_error = err;
  21945. });
  21946. sse.set_reconnect_interval(50);
  21947. sse.set_max_reconnect_attempts(1);
  21948. sse.start_async();
  21949. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21950. sse.stop();
  21951. EXPECT_TRUE(error_called.load());
  21952. EXPECT_NE(received_error, Error::Success);
  21953. }
  21954. // Test: Last-Event-ID header sent on reconnect
  21955. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21956. // Endpoint that sends event with ID
  21957. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21958. res.set_chunked_content_provider(
  21959. "text/event-stream", [](size_t offset, DataSink &sink) {
  21960. if (offset == 0) {
  21961. std::string event = "id: evt-123\ndata: test\n\n";
  21962. sink.write(event.data(), event.size());
  21963. }
  21964. return false;
  21965. });
  21966. });
  21967. Client client("localhost", get_port());
  21968. sse::SSEClient sse(client, "/event-with-id");
  21969. std::atomic<bool> id_received{false};
  21970. sse.on_message([&](const sse::SSEMessage &msg) {
  21971. if (!msg.id.empty()) { id_received.store(true); }
  21972. });
  21973. sse.set_reconnect_interval(100);
  21974. sse.set_max_reconnect_attempts(1);
  21975. sse.start_async();
  21976. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21977. sse.stop();
  21978. EXPECT_TRUE(id_received.load());
  21979. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21980. }
  21981. // Test: Manual stop
  21982. TEST_F(SSEIntegrationTest, ManualStop) {
  21983. // Endpoint that sends one event and stays open briefly. The server outlives
  21984. // this test body, so the provider uses the fixture's flag, not a local.
  21985. server_->Get("/stay-open", [this](const Request &, Response &res) {
  21986. res.set_chunked_content_provider(
  21987. "text/event-stream", [this](size_t offset, DataSink &sink) {
  21988. if (offset == 0) {
  21989. std::string event = "data: connected\n\n";
  21990. sink.write(event.data(), event.size());
  21991. }
  21992. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  21993. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21994. }
  21995. return false;
  21996. });
  21997. });
  21998. Client client("localhost", get_port());
  21999. sse::SSEClient sse(client, "/stay-open");
  22000. std::atomic<bool> connected{false};
  22001. sse.on_open([&connected]() { connected.store(true); });
  22002. sse.set_reconnect_interval(100);
  22003. sse.set_max_reconnect_attempts(1);
  22004. sse.start_async();
  22005. // Wait for connection to establish
  22006. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22007. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22008. }
  22009. EXPECT_TRUE(connected.load());
  22010. EXPECT_TRUE(sse.is_connected());
  22011. // Signal handler to stop
  22012. stop_server_.store(true);
  22013. // Stop SSE client
  22014. sse.stop();
  22015. EXPECT_FALSE(sse.is_connected());
  22016. }
  22017. // Sends one event, then nothing until stop is set
  22018. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22019. return [&stop](const Request &, Response &res) {
  22020. res.set_chunked_content_provider(
  22021. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22022. if (offset == 0) {
  22023. std::string event = "data: hello\n\n";
  22024. sink.write(event.data(), event.size());
  22025. }
  22026. while (!stop.load()) {
  22027. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22028. }
  22029. return false;
  22030. });
  22031. };
  22032. }
  22033. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22034. static void check_stop_interrupts_blocked_read(Client &client) {
  22035. client.set_read_timeout(30, 0);
  22036. for (auto by_destructor : {false, true}) {
  22037. std::atomic<bool> received{false};
  22038. std::chrono::steady_clock::time_point start;
  22039. {
  22040. sse::SSEClient sse(client, "/idle-stream");
  22041. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22042. sse.start_async();
  22043. for (int i = 0; i < 500 && !received.load(); ++i) {
  22044. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22045. }
  22046. ASSERT_TRUE(received.load());
  22047. // Let the client block in the next read
  22048. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22049. start = std::chrono::steady_clock::now();
  22050. if (!by_destructor) { sse.stop(); }
  22051. }
  22052. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22053. std::chrono::seconds(2));
  22054. }
  22055. }
  22056. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22057. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22058. Client client("localhost", get_port());
  22059. check_stop_interrupts_blocked_read(client);
  22060. }
  22061. #ifdef CPPHTTPLIB_SSL_ENABLED
  22062. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22063. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22064. std::atomic<bool> done{false};
  22065. svr.Get("/idle-stream", idle_event_stream(done));
  22066. auto port = svr.bind_to_any_port(HOST);
  22067. std::thread t([&] { svr.listen_after_bind(); });
  22068. auto se = detail::scope_exit([&] {
  22069. done.store(true);
  22070. svr.stop();
  22071. t.join();
  22072. });
  22073. svr.wait_until_ready();
  22074. Client client("https://localhost:" + std::to_string(port));
  22075. client.enable_server_certificate_verification(false);
  22076. check_stop_interrupts_blocked_read(client);
  22077. }
  22078. #endif
  22079. // Test: SSEClient with custom headers
  22080. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22081. // Setup a server endpoint that checks for custom header
  22082. std::atomic<bool> header_received{false};
  22083. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22084. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22085. header_received.store(true);
  22086. }
  22087. res.set_chunked_content_provider("text/event-stream",
  22088. [](size_t, DataSink &) { return false; });
  22089. });
  22090. Client client("localhost", get_port());
  22091. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22092. sse::SSEClient sse(client, "/header-check", headers);
  22093. sse.set_max_reconnect_attempts(1);
  22094. sse.start_async();
  22095. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22096. sse.stop();
  22097. EXPECT_TRUE(header_received.load());
  22098. }
  22099. // Test: Reconnect interval configuration
  22100. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22101. Client client("localhost", get_port());
  22102. sse::SSEClient sse(client, "/events");
  22103. auto &result = sse.set_reconnect_interval(500);
  22104. // Builder pattern should return reference to self
  22105. EXPECT_EQ(&result, &sse);
  22106. }
  22107. // Test: Max reconnect attempts
  22108. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22109. // Connect to non-existent port to force reconnects
  22110. Client client("localhost", 59998);
  22111. sse::SSEClient sse(client, "/events");
  22112. std::atomic<int> error_count{0};
  22113. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22114. sse.set_reconnect_interval(50);
  22115. sse.set_max_reconnect_attempts(2);
  22116. auto start = std::chrono::steady_clock::now();
  22117. sse.start(); // Blocking call
  22118. auto end = std::chrono::steady_clock::now();
  22119. // Should have stopped after 2 failed attempts
  22120. EXPECT_GE(error_count.load(), 2);
  22121. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22122. auto duration =
  22123. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22124. #ifdef _WIN32
  22125. // Windows is much slower for socket connection failures
  22126. EXPECT_LT(duration.count(), 7000);
  22127. #else
  22128. EXPECT_LT(duration.count(), 1000);
  22129. #endif
  22130. }
  22131. // Test: Multi-line data in integration
  22132. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22133. // Endpoint with multi-line data
  22134. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22135. res.set_chunked_content_provider(
  22136. "text/event-stream", [](size_t offset, DataSink &sink) {
  22137. if (offset == 0) {
  22138. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22139. sink.write(event.data(), event.size());
  22140. }
  22141. return false;
  22142. });
  22143. });
  22144. Client client("localhost", get_port());
  22145. sse::SSEClient sse(client, "/multiline-data");
  22146. std::string received_data;
  22147. std::mutex data_mutex;
  22148. sse.on_message([&](const sse::SSEMessage &msg) {
  22149. std::lock_guard<std::mutex> lock(data_mutex);
  22150. received_data = msg.data;
  22151. });
  22152. sse.set_reconnect_interval(100);
  22153. sse.set_max_reconnect_attempts(1);
  22154. sse.start_async();
  22155. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22156. sse.stop();
  22157. std::lock_guard<std::mutex> lock(data_mutex);
  22158. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22159. }
  22160. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22161. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22162. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22163. DataSink &sink) {
  22164. if (offset == 0) {
  22165. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22166. sink.write(events.data(), events.size());
  22167. }
  22168. return false;
  22169. });
  22170. });
  22171. Client client("localhost", get_port());
  22172. sse::SSEClient sse(client, "/empty-data-lines");
  22173. std::mutex mutex;
  22174. std::condition_variable cv;
  22175. std::vector<std::string> received;
  22176. sse.on_message([&](const sse::SSEMessage &msg) {
  22177. std::lock_guard<std::mutex> lock(mutex);
  22178. received.push_back(msg.data);
  22179. cv.notify_all();
  22180. });
  22181. sse.set_max_reconnect_attempts(1);
  22182. sse.start_async();
  22183. {
  22184. std::unique_lock<std::mutex> lock(mutex);
  22185. cv.wait_for(lock, std::chrono::seconds(2),
  22186. [&] { return received.size() >= 3; });
  22187. }
  22188. sse.stop();
  22189. ASSERT_GE(received.size(), 3u);
  22190. EXPECT_EQ(received[0], "");
  22191. EXPECT_EQ(received[1], "\nhello");
  22192. EXPECT_EQ(received[2], "");
  22193. }
  22194. // Test: Auto-reconnect after server disconnection
  22195. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22196. std::atomic<int> connection_count{0};
  22197. std::atomic<int> message_count{0};
  22198. // Endpoint that sends one event and closes, forcing reconnect
  22199. server_->Get("/reconnect-test",
  22200. [&connection_count](const Request &, Response &res) {
  22201. connection_count.fetch_add(1);
  22202. res.set_chunked_content_provider(
  22203. "text/event-stream", [](size_t offset, DataSink &sink) {
  22204. if (offset == 0) {
  22205. std::string event = "data: hello\n\n";
  22206. sink.write(event.data(), event.size());
  22207. }
  22208. return false; // Close connection after sending
  22209. });
  22210. });
  22211. Client client("localhost", get_port());
  22212. sse::SSEClient sse(client, "/reconnect-test");
  22213. sse.on_message([&message_count](const sse::SSEMessage &) {
  22214. message_count.fetch_add(1);
  22215. });
  22216. sse.set_reconnect_interval(100);
  22217. sse.set_max_reconnect_attempts(3);
  22218. sse.start_async();
  22219. // Wait long enough for multiple reconnects
  22220. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22221. sse.stop();
  22222. // Should have connected multiple times (initial + reconnects)
  22223. EXPECT_GE(connection_count.load(), 2);
  22224. // Should have received messages from multiple connections
  22225. EXPECT_GE(message_count.load(), 2);
  22226. }
  22227. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22228. std::atomic<int> connection_count{0};
  22229. // Neither Content-Length nor chunked: the close ends the stream
  22230. server_->Get("/close-delimited",
  22231. [&connection_count](const Request &, Response &res) {
  22232. connection_count.fetch_add(1);
  22233. res.set_content_provider(
  22234. "text/event-stream", [](size_t offset, DataSink &sink) {
  22235. if (offset == 0) {
  22236. std::string event = "data: hello\n\n";
  22237. sink.write(event.data(), event.size());
  22238. } else {
  22239. sink.done();
  22240. }
  22241. return true;
  22242. });
  22243. });
  22244. Client client("localhost", get_port());
  22245. sse::SSEClient sse(client, "/close-delimited");
  22246. std::atomic<int> error_count{0};
  22247. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22248. sse.set_reconnect_interval(100);
  22249. sse.start_async();
  22250. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22251. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22252. }
  22253. sse.stop();
  22254. // Reconnects as after any end of the stream, but reports no error
  22255. EXPECT_GE(connection_count.load(), 2);
  22256. EXPECT_EQ(0, error_count.load());
  22257. }
  22258. // Test: A retry field that is not all ASCII digits is ignored
  22259. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22260. std::atomic<int> connection_count{0};
  22261. server_->Get("/bad-retry",
  22262. [&connection_count](const Request &, Response &res) {
  22263. connection_count.fetch_add(1);
  22264. res.set_chunked_content_provider(
  22265. "text/event-stream", [](size_t offset, DataSink &sink) {
  22266. if (offset == 0) {
  22267. std::string event = "retry: -1\ndata: hello\n\n";
  22268. sink.write(event.data(), event.size());
  22269. }
  22270. return false;
  22271. });
  22272. });
  22273. Client client("localhost", get_port());
  22274. sse::SSEClient sse(client, "/bad-retry");
  22275. sse.set_reconnect_interval(10000);
  22276. sse.start_async();
  22277. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22278. sse.stop();
  22279. EXPECT_EQ(connection_count.load(), 1);
  22280. }
  22281. // Test: A retry field of all ASCII digits sets the reconnection time
  22282. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22283. std::mutex mutex;
  22284. std::condition_variable cv;
  22285. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22286. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22287. {
  22288. std::lock_guard<std::mutex> lock(mutex);
  22289. connected_at.push_back(std::chrono::steady_clock::now());
  22290. cv.notify_all();
  22291. }
  22292. res.set_chunked_content_provider(
  22293. "text/event-stream", [](size_t offset, DataSink &sink) {
  22294. if (offset == 0) {
  22295. std::string event = "retry: 0\ndata: hello\n\n";
  22296. sink.write(event.data(), event.size());
  22297. }
  22298. return false;
  22299. });
  22300. });
  22301. Client client("localhost", get_port());
  22302. sse::SSEClient sse(client, "/zero-retry");
  22303. sse.set_reconnect_interval(10000);
  22304. sse.start_async();
  22305. {
  22306. std::unique_lock<std::mutex> lock(mutex);
  22307. cv.wait_for(lock, std::chrono::seconds(5),
  22308. [&] { return connected_at.size() >= 2; });
  22309. }
  22310. sse.stop();
  22311. // The server-supplied interval is applied, but never below 100ms, so
  22312. // "retry: 0" does not cause a busy reconnect loop
  22313. std::lock_guard<std::mutex> lock(mutex);
  22314. ASSERT_GE(connected_at.size(), 2u);
  22315. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22316. connected_at[1] - connected_at[0])
  22317. .count();
  22318. EXPECT_GE(interval_ms, 100);
  22319. }
  22320. // Test: Last-Event-ID sent on reconnect
  22321. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22322. std::atomic<int> connection_count{0};
  22323. std::vector<std::string> received_last_event_ids;
  22324. std::mutex id_mutex;
  22325. // Endpoint that checks Last-Event-ID header and sends event with ID
  22326. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22327. int conn = connection_count.fetch_add(1);
  22328. // Capture the Last-Event-ID header from each connection
  22329. {
  22330. std::lock_guard<std::mutex> lock(id_mutex);
  22331. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22332. }
  22333. res.set_chunked_content_provider(
  22334. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22335. if (offset == 0) {
  22336. std::string event =
  22337. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22338. sink.write(event.data(), event.size());
  22339. }
  22340. return false;
  22341. });
  22342. });
  22343. Client client("localhost", get_port());
  22344. sse::SSEClient sse(client, "/reconnect-with-id");
  22345. sse.set_reconnect_interval(100);
  22346. sse.set_max_reconnect_attempts(3);
  22347. sse.start_async();
  22348. // Wait for at least 2 connections
  22349. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22350. sse.stop();
  22351. // Verify behavior
  22352. std::lock_guard<std::mutex> lock(id_mutex);
  22353. EXPECT_GE(received_last_event_ids.size(), 2u);
  22354. // First connection should have no Last-Event-ID
  22355. if (!received_last_event_ids.empty()) {
  22356. EXPECT_EQ(received_last_event_ids[0], "");
  22357. }
  22358. // Second connection should have Last-Event-ID from first connection
  22359. if (received_last_event_ids.size() >= 2) {
  22360. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22361. }
  22362. }
  22363. // Test: set_headers updates headers used on reconnect
  22364. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22365. std::vector<std::string> received_tokens;
  22366. std::mutex token_mutex;
  22367. // Endpoint that captures Authorization header
  22368. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22369. {
  22370. std::lock_guard<std::mutex> lock(token_mutex);
  22371. received_tokens.push_back(req.get_header_value("Authorization"));
  22372. }
  22373. res.set_chunked_content_provider(
  22374. "text/event-stream", [](size_t offset, DataSink &sink) {
  22375. if (offset == 0) {
  22376. std::string event = "data: hello\n\n";
  22377. sink.write(event.data(), event.size());
  22378. }
  22379. return false; // Close connection to trigger reconnect
  22380. });
  22381. });
  22382. Client client("localhost", get_port());
  22383. Headers headers = {{"Authorization", "Bearer old-token"}};
  22384. sse::SSEClient sse(client, "/auth-check", headers);
  22385. // Update headers on each successful connection
  22386. sse.on_open(
  22387. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22388. sse.set_reconnect_interval(100);
  22389. sse.set_max_reconnect_attempts(3);
  22390. sse.start_async();
  22391. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22392. sse.stop();
  22393. std::lock_guard<std::mutex> lock(token_mutex);
  22394. ASSERT_GE(received_tokens.size(), 2u);
  22395. // First connection uses original header
  22396. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22397. // Second connection uses updated header from set_headers
  22398. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22399. }
  22400. // Test: 401 allows reconnection (so on_error can refresh headers)
  22401. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22402. std::atomic<int> connection_count{0};
  22403. // Endpoint: returns 401 on first attempt, 200 on second
  22404. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22405. int conn = connection_count.fetch_add(1);
  22406. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22407. res.status = StatusCode::Unauthorized_401;
  22408. res.set_content("Unauthorized", "text/plain");
  22409. return;
  22410. }
  22411. res.set_chunked_content_provider(
  22412. "text/event-stream", [](size_t offset, DataSink &sink) {
  22413. if (offset == 0) {
  22414. std::string event = "data: authenticated\n\n";
  22415. sink.write(event.data(), event.size());
  22416. }
  22417. return false;
  22418. });
  22419. });
  22420. Client client("localhost", get_port());
  22421. Headers headers = {{"Authorization", "Bearer expired"}};
  22422. sse::SSEClient sse(client, "/auth-retry", headers);
  22423. std::atomic<bool> message_received{false};
  22424. // Refresh token on error
  22425. sse.on_error(
  22426. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22427. sse.on_message([&](const sse::SSEMessage &msg) {
  22428. if (msg.data == "authenticated") { message_received.store(true); }
  22429. });
  22430. sse.set_reconnect_interval(100);
  22431. sse.set_max_reconnect_attempts(3);
  22432. sse.start_async();
  22433. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22434. sse.stop();
  22435. // Should have reconnected after 401 and succeeded with new token
  22436. EXPECT_GE(connection_count.load(), 2);
  22437. EXPECT_TRUE(message_received.load());
  22438. }
  22439. TEST(Issue2318Test, EmptyHostString) {
  22440. {
  22441. httplib::Client cli_empty("", PORT);
  22442. auto res = cli_empty.Get("/");
  22443. ASSERT_FALSE(res);
  22444. EXPECT_EQ(httplib::Error::Connection, res.error());
  22445. }
  22446. {
  22447. httplib::Client cli(" ", PORT);
  22448. auto res = cli.Get("/");
  22449. ASSERT_FALSE(res);
  22450. EXPECT_EQ(httplib::Error::Connection, res.error());
  22451. }
  22452. }
  22453. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22454. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22455. Server svr;
  22456. // Set a small payload limit (1KB)
  22457. svr.set_payload_max_length(1024);
  22458. svr.Post("/test", [&](const Request &req, Response &res) {
  22459. res.set_content("Body size: " + std::to_string(req.body.size()),
  22460. "text/plain");
  22461. });
  22462. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22463. auto se = detail::scope_exit([&] {
  22464. svr.stop();
  22465. listen_thread.join();
  22466. });
  22467. svr.wait_until_ready();
  22468. // Create data that compresses well but exceeds limit when decompressed
  22469. // 8KB of repeated null bytes compresses to a very small size
  22470. std::string original_data(8 * 1024, '\0');
  22471. // Compress the data using gzip
  22472. std::string compressed_data;
  22473. detail::gzip_compressor compressor;
  22474. compressor.compress(original_data.data(), original_data.size(), true,
  22475. [&](const char *data, size_t size) {
  22476. compressed_data.append(data, size);
  22477. return true;
  22478. });
  22479. // Verify compression worked (compressed should be much smaller)
  22480. ASSERT_LT(compressed_data.size(), original_data.size());
  22481. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22482. // Send compressed data with Content-Encoding: gzip
  22483. Client cli(HOST, PORT);
  22484. Headers headers = {{"Content-Encoding", "gzip"}};
  22485. auto res =
  22486. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22487. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22489. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22490. }
  22491. #endif
  22492. // ============================================================================
  22493. // OpenSSL-Specific Tests
  22494. // ============================================================================
  22495. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22496. X509 *readCertificate(const std::string &strFileName) {
  22497. std::ifstream inStream(strFileName);
  22498. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22499. std::istreambuf_iterator<char>());
  22500. if (strCertPEM.empty()) return (nullptr);
  22501. BIO *pbCert = BIO_new(BIO_s_mem());
  22502. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22503. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22504. BIO_free(pbCert);
  22505. return (pCert);
  22506. }
  22507. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22508. std::ifstream inStream(strFileName);
  22509. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22510. std::istreambuf_iterator<char>());
  22511. if (strPrivateKeyPEM.empty()) return (nullptr);
  22512. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22513. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22514. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22515. BIO_free(pbPrivKey);
  22516. return (pPrivateKey);
  22517. }
  22518. TEST(BindServerTest, UpdateCerts) {
  22519. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22520. int port = svr.bind_to_any_port("0.0.0.0");
  22521. ASSERT_TRUE(svr.is_valid());
  22522. ASSERT_TRUE(port > 0);
  22523. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22524. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22525. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22526. ASSERT_TRUE(cert != nullptr);
  22527. ASSERT_TRUE(ca_cert != nullptr);
  22528. ASSERT_TRUE(key != nullptr);
  22529. X509_STORE *cert_store = X509_STORE_new();
  22530. X509_STORE_add_cert(cert_store, ca_cert);
  22531. // svr.update_certs(cert, key, cert_store); // deprecated
  22532. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22533. CLIENT_CA_CERT_FILE);
  22534. ASSERT_TRUE(svr.is_valid());
  22535. svr.stop();
  22536. X509_STORE_free(cert_store);
  22537. X509_free(cert);
  22538. X509_free(ca_cert);
  22539. EVP_PKEY_free(key);
  22540. }
  22541. // Test that update_certs() updates client CA list correctly
  22542. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22543. // Start with file-based constructor
  22544. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22545. ASSERT_TRUE(svr.is_valid());
  22546. // Initially no client CA list should be set
  22547. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22548. ASSERT_TRUE(ssl_ctx != nullptr);
  22549. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22550. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22551. // Now update with client CA (PEM string)
  22552. std::string cert_pem, key_pem, ca_pem;
  22553. read_file(SERVER_CERT_FILE, cert_pem);
  22554. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22555. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22556. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22557. ASSERT_TRUE(svr.is_valid());
  22558. // Now client CA list should be set
  22559. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22560. ASSERT_TRUE(ca_list_after != nullptr);
  22561. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22562. }
  22563. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22564. // Test that the file-path SSLServer constructor properly sets the client CA
  22565. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22567. ASSERT_TRUE(svr.is_valid());
  22568. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22569. ASSERT_TRUE(ssl_ctx != nullptr);
  22570. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22571. ASSERT_TRUE(ca_list != nullptr);
  22572. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22573. }
  22574. #endif
  22575. // ============================================================================
  22576. // MbedTLS-Specific Tests
  22577. // ============================================================================
  22578. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22579. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22580. using namespace httplib::tls;
  22581. // Track if callback was invoked
  22582. bool callback_invoked = false;
  22583. // The callback receives void* ctx which is actually MbedTlsContext*
  22584. // We can access the mbedtls_ssl_config via the context
  22585. auto setup_callback = [&callback_invoked](void *ctx) {
  22586. callback_invoked = true;
  22587. // Cast to MbedTlsContext* to access the ssl config
  22588. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22589. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22590. // Use static variables to hold certificate data (simplified for test)
  22591. static mbedtls_x509_crt own_cert;
  22592. static mbedtls_pk_context own_key;
  22593. static mbedtls_x509_crt ca_chain;
  22594. static bool initialized = false;
  22595. if (!initialized) {
  22596. mbedtls_x509_crt_init(&own_cert);
  22597. mbedtls_pk_init(&own_key);
  22598. mbedtls_x509_crt_init(&ca_chain);
  22599. // Load server certificate
  22600. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22601. return false;
  22602. }
  22603. // Load server private key.
  22604. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22605. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22606. #if MBEDTLS_VERSION_MAJOR == 3
  22607. ,
  22608. mbedtls_ctr_drbg_random, nullptr
  22609. #endif
  22610. ) != 0) {
  22611. return false;
  22612. }
  22613. // Load CA chain for client verification
  22614. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22615. return false;
  22616. }
  22617. initialized = true;
  22618. }
  22619. // Configure the SSL config
  22620. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22621. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22622. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22623. // Set minimum TLS version using mbedTLS native API
  22624. #if MBEDTLS_VERSION_MAJOR >= 3
  22625. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22626. #else
  22627. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22628. MBEDTLS_SSL_MINOR_VERSION_3);
  22629. #endif
  22630. return true;
  22631. };
  22632. SSLServer svr(setup_callback);
  22633. ASSERT_TRUE(svr.is_valid());
  22634. ASSERT_TRUE(callback_invoked);
  22635. svr.Get("/test", [&](const Request &req, Response &res) {
  22636. res.set_content("test", "text/plain");
  22637. auto cert = req.peer_cert();
  22638. ASSERT_TRUE(static_cast<bool>(cert));
  22639. auto common_name = cert.subject_cn();
  22640. EXPECT_EQ("Common Name", common_name);
  22641. });
  22642. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22643. auto se = detail::scope_exit([&] {
  22644. svr.stop();
  22645. t.join();
  22646. ASSERT_FALSE(svr.is_running());
  22647. });
  22648. svr.wait_until_ready();
  22649. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22650. cli.enable_server_certificate_verification(false);
  22651. cli.set_connection_timeout(30);
  22652. auto res = cli.Get("/test");
  22653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22654. ASSERT_EQ(StatusCode::OK_200, res->status);
  22655. }
  22656. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22657. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22658. // keep-alive SSL session, which reads through that config in
  22659. // mbedtls_ssl_close_notify.
  22660. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22662. ASSERT_TRUE(svr.is_valid());
  22663. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22664. res.set_content("test", "text/plain");
  22665. });
  22666. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22667. auto se = detail::scope_exit([&] {
  22668. svr.stop();
  22669. t.join();
  22670. ASSERT_FALSE(svr.is_running());
  22671. });
  22672. svr.wait_until_ready();
  22673. {
  22674. SSLClient cli(HOST, PORT);
  22675. cli.enable_server_certificate_verification(false);
  22676. cli.set_keep_alive(true);
  22677. auto res = cli.Get("/test");
  22678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22679. ASSERT_EQ(StatusCode::OK_200, res->status);
  22680. // cli is destructed here with the keep-alive SSL session still open.
  22681. }
  22682. }
  22683. #endif
  22684. // WebSocket Tests
  22685. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22686. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22687. // defining the meaning of these bits has been negotiated.
  22688. auto make_frame = [](uint8_t first_byte) {
  22689. std::string frame;
  22690. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22691. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22692. frame += "Hello";
  22693. return frame;
  22694. };
  22695. // RSV1 set (0x40)
  22696. {
  22697. detail::BufferStream strm;
  22698. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22699. ws::Opcode opcode;
  22700. std::string payload;
  22701. bool fin;
  22702. EXPECT_EQ(
  22703. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22704. ws::impl::FrameRead::Fail);
  22705. }
  22706. // RSV2 set (0x20)
  22707. {
  22708. detail::BufferStream strm;
  22709. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22710. ws::Opcode opcode;
  22711. std::string payload;
  22712. bool fin;
  22713. EXPECT_EQ(
  22714. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22715. ws::impl::FrameRead::Fail);
  22716. }
  22717. // RSV3 set (0x10)
  22718. {
  22719. detail::BufferStream strm;
  22720. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22721. ws::Opcode opcode;
  22722. std::string payload;
  22723. bool fin;
  22724. EXPECT_EQ(
  22725. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22726. ws::impl::FrameRead::Fail);
  22727. }
  22728. // No RSV bits set - should succeed
  22729. {
  22730. detail::BufferStream strm;
  22731. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22732. ws::Opcode opcode;
  22733. std::string payload;
  22734. bool fin;
  22735. EXPECT_EQ(
  22736. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22737. ws::impl::FrameRead::Ok);
  22738. EXPECT_EQ(ws::Opcode::Text, opcode);
  22739. EXPECT_EQ("Hello", payload);
  22740. EXPECT_TRUE(fin);
  22741. }
  22742. }
  22743. TEST(WebSocketTest, ControlFrameValidation) {
  22744. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22745. // payload length <= 125.
  22746. // Ping with FIN=0 - must be rejected
  22747. {
  22748. detail::BufferStream strm;
  22749. std::string frame;
  22750. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22751. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  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::Fail);
  22759. }
  22760. // Close with FIN=0 - must be rejected
  22761. {
  22762. detail::BufferStream strm;
  22763. std::string frame;
  22764. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22765. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22766. strm.write(frame.data(), frame.size());
  22767. ws::Opcode opcode;
  22768. std::string payload;
  22769. bool fin;
  22770. EXPECT_EQ(
  22771. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22772. ws::impl::FrameRead::Fail);
  22773. }
  22774. // Ping with payload_len=126 (extended length) - must be rejected
  22775. {
  22776. detail::BufferStream strm;
  22777. std::string frame;
  22778. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22779. frame += static_cast<char>(126); // payload_len=126 (>125)
  22780. frame += static_cast<char>(0x00); // extended length high byte
  22781. frame += static_cast<char>(126); // extended length low byte
  22782. frame += std::string(126, 'x');
  22783. strm.write(frame.data(), frame.size());
  22784. ws::Opcode opcode;
  22785. std::string payload;
  22786. bool fin;
  22787. EXPECT_EQ(
  22788. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22789. ws::impl::FrameRead::Fail);
  22790. }
  22791. // Ping with FIN=1 and payload_len=125 - should succeed
  22792. {
  22793. detail::BufferStream strm;
  22794. std::string frame;
  22795. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22796. frame += static_cast<char>(125); // payload_len=125
  22797. frame += std::string(125, 'x');
  22798. strm.write(frame.data(), frame.size());
  22799. ws::Opcode opcode;
  22800. std::string payload;
  22801. bool fin;
  22802. EXPECT_EQ(
  22803. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22804. ws::impl::FrameRead::Ok);
  22805. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22806. EXPECT_EQ(125u, payload.size());
  22807. EXPECT_TRUE(fin);
  22808. }
  22809. }
  22810. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22811. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22812. // length MUST be 0.
  22813. // MSB set - must be rejected
  22814. {
  22815. detail::BufferStream strm;
  22816. std::string frame;
  22817. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22818. frame += static_cast<char>(127); // 64-bit extended length
  22819. frame += static_cast<char>(0x80); // MSB set (invalid)
  22820. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22821. strm.write(frame.data(), frame.size());
  22822. ws::Opcode opcode;
  22823. std::string payload;
  22824. bool fin;
  22825. EXPECT_EQ(
  22826. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22827. ws::impl::FrameRead::Fail);
  22828. }
  22829. // MSB clear - should pass length parsing (will be rejected by max_len,
  22830. // but that's a different check; use a small length to verify)
  22831. {
  22832. detail::BufferStream strm;
  22833. std::string frame;
  22834. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22835. frame += static_cast<char>(127); // 64-bit extended length
  22836. frame += std::string(7, '\0'); // high bytes = 0
  22837. frame += static_cast<char>(0x03); // length = 3
  22838. frame += "abc";
  22839. strm.write(frame.data(), frame.size());
  22840. ws::Opcode opcode;
  22841. std::string payload;
  22842. bool fin;
  22843. EXPECT_EQ(
  22844. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22845. ws::impl::FrameRead::Ok);
  22846. EXPECT_EQ(ws::Opcode::Text, opcode);
  22847. EXPECT_EQ("abc", payload);
  22848. }
  22849. }
  22850. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22851. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22852. // Valid UTF-8
  22853. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22854. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22855. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22856. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22857. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22858. // Invalid UTF-8
  22859. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22860. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22861. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22862. EXPECT_FALSE(
  22863. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22864. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22865. }
  22866. TEST(WebSocketTest, ConnectAndDisconnect) {
  22867. Server svr;
  22868. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22869. std::string msg;
  22870. while (ws.read(msg)) {}
  22871. });
  22872. auto port = svr.bind_to_any_port(HOST);
  22873. std::thread t([&]() { svr.listen_after_bind(); });
  22874. svr.wait_until_ready();
  22875. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22876. auto res = client.connect();
  22877. ASSERT_TRUE(res);
  22878. EXPECT_EQ(Error::Success, res.error());
  22879. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22880. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22881. EXPECT_TRUE(client.is_open());
  22882. client.close();
  22883. EXPECT_FALSE(client.is_open());
  22884. svr.stop();
  22885. t.join();
  22886. }
  22887. TEST(WebSocketTest, ValidURL) {
  22888. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22889. EXPECT_TRUE(ws1.is_valid());
  22890. ws::WebSocketClient ws2("ws://example.com/path");
  22891. EXPECT_TRUE(ws2.is_valid());
  22892. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22893. EXPECT_TRUE(ws3.is_valid());
  22894. #ifdef CPPHTTPLIB_SSL_ENABLED
  22895. ws::WebSocketClient wss1("wss://example.com/path");
  22896. EXPECT_TRUE(wss1.is_valid());
  22897. ws::WebSocketClient wss2("wss://example.com:443/path");
  22898. EXPECT_TRUE(wss2.is_valid());
  22899. #endif
  22900. }
  22901. TEST(WebSocketTest, InvalidURL) {
  22902. // No scheme
  22903. ws::WebSocketClient ws1("localhost:8080/path");
  22904. EXPECT_FALSE(ws1.is_valid());
  22905. // No path
  22906. ws::WebSocketClient ws2("ws://localhost:8080");
  22907. EXPECT_FALSE(ws2.is_valid());
  22908. // Empty string
  22909. ws::WebSocketClient ws3("");
  22910. EXPECT_FALSE(ws3.is_valid());
  22911. // Missing host
  22912. ws::WebSocketClient ws4("ws://:8080/path");
  22913. EXPECT_FALSE(ws4.is_valid());
  22914. // Port number overflow — should not crash
  22915. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22916. EXPECT_FALSE(ws5.is_valid());
  22917. // Port out of range
  22918. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22919. EXPECT_FALSE(ws6.is_valid());
  22920. }
  22921. TEST(WebSocketTest, UnsupportedScheme) {
  22922. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22923. ws::WebSocketClient ws1("http://localhost:8080/path");
  22924. EXPECT_FALSE(ws1.is_valid());
  22925. ws::WebSocketClient ws2("https://localhost:8080/path");
  22926. EXPECT_FALSE(ws2.is_valid());
  22927. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22928. EXPECT_FALSE(ws3.is_valid());
  22929. #else
  22930. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22931. std::invalid_argument);
  22932. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22933. std::invalid_argument);
  22934. #endif
  22935. }
  22936. TEST(WebSocketTest, ConnectWhenInvalid) {
  22937. ws::WebSocketClient ws("not a valid url");
  22938. EXPECT_FALSE(ws.is_valid());
  22939. auto res = ws.connect();
  22940. EXPECT_FALSE(res);
  22941. EXPECT_EQ(Error::Connection, res.error());
  22942. EXPECT_EQ(-1, res.status());
  22943. }
  22944. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22945. // Grab a port that is free, then close it again so nothing listens there
  22946. Server svr;
  22947. auto port = svr.bind_to_any_port(HOST);
  22948. svr.stop();
  22949. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22950. auto res = client.connect();
  22951. ASSERT_FALSE(res);
  22952. EXPECT_EQ(Error::Connection, res.error());
  22953. EXPECT_EQ(-1, res.status());
  22954. }
  22955. TEST(WebSocketTest, DefaultPort) {
  22956. ws::WebSocketClient ws1("ws://example.com/path");
  22957. EXPECT_TRUE(ws1.is_valid());
  22958. // ws:// defaults to port 80 (verified by successful parse)
  22959. #ifdef CPPHTTPLIB_SSL_ENABLED
  22960. ws::WebSocketClient ws2("wss://example.com/path");
  22961. EXPECT_TRUE(ws2.is_valid());
  22962. // wss:// defaults to port 443 (verified by successful parse)
  22963. #endif
  22964. }
  22965. TEST(WebSocketTest, IPv6LiteralAddress) {
  22966. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22967. EXPECT_TRUE(ws1.is_valid());
  22968. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22969. EXPECT_TRUE(ws2.is_valid());
  22970. }
  22971. TEST(WebSocketTest, ComplexPath) {
  22972. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22973. EXPECT_TRUE(ws1.is_valid());
  22974. ws::WebSocketClient ws2("ws://localhost:8080/");
  22975. EXPECT_TRUE(ws2.is_valid());
  22976. }
  22977. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22978. Server svr;
  22979. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22980. std::string msg;
  22981. while (ws.read(msg)) {}
  22982. });
  22983. auto port = svr.bind_to_any_port(HOST);
  22984. std::thread t([&]() { svr.listen_after_bind(); });
  22985. svr.wait_until_ready();
  22986. auto another_host = "example.com";
  22987. auto wrong_ip = "192.0.2.1";
  22988. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22989. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22990. ASSERT_TRUE(client.connect());
  22991. EXPECT_TRUE(client.is_open());
  22992. client.close();
  22993. svr.stop();
  22994. t.join();
  22995. }
  22996. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22997. Server svr;
  22998. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22999. std::string msg;
  23000. while (ws.read(msg)) {}
  23001. });
  23002. auto port = svr.bind_to_any_port(HOST);
  23003. std::thread t([&]() { svr.listen_after_bind(); });
  23004. svr.wait_until_ready();
  23005. auto wrong_ip = "192.0.2.1";
  23006. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23007. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23008. client.set_connection_timeout(1);
  23009. client.set_read_timeout(1);
  23010. client.set_write_timeout(1);
  23011. EXPECT_FALSE(client.connect());
  23012. EXPECT_FALSE(client.is_open());
  23013. svr.stop();
  23014. t.join();
  23015. }
  23016. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23017. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23018. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23019. // (RFC 6761) is only a map key and the Host header value.
  23020. auto host = "target.invalid";
  23021. Server svr;
  23022. std::string received_host;
  23023. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23024. received_host = req.get_header_value("Host");
  23025. std::string msg;
  23026. while (ws.read(msg)) {}
  23027. });
  23028. auto port = svr.bind_to_any_port(HOST);
  23029. std::thread t([&]() { svr.listen_after_bind(); });
  23030. // ASSERT_* below returns from the test body, which would leave t joinable
  23031. // and make ~thread call std::terminate.
  23032. auto se = detail::scope_exit([&] {
  23033. svr.stop();
  23034. if (t.joinable()) { t.join(); }
  23035. });
  23036. svr.wait_until_ready();
  23037. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23038. std::to_string(port) + "/ws");
  23039. client.set_hostname_addr_map({{host, HOST}});
  23040. ASSERT_TRUE(client.connect());
  23041. EXPECT_TRUE(client.is_open());
  23042. client.close();
  23043. svr.stop();
  23044. t.join();
  23045. // The mapping only redirects the connection; the identity stays host_.
  23046. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23047. }
  23048. class WebSocketIntegrationTest : public ::testing::Test {
  23049. protected:
  23050. void SetUp() override {
  23051. server_ = httplib::detail::make_unique<Server>();
  23052. setup_server();
  23053. start_server();
  23054. }
  23055. void TearDown() override {
  23056. server_->stop();
  23057. if (server_thread_.joinable()) { server_thread_.join(); }
  23058. }
  23059. void setup_server() {
  23060. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23061. std::string msg;
  23062. ws::ReadResult ret;
  23063. while ((ret = ws.read(msg))) {
  23064. if (ret == ws::Binary) {
  23065. ws.send(msg.data(), msg.size());
  23066. } else {
  23067. ws.send(msg);
  23068. }
  23069. }
  23070. });
  23071. server_->WebSocket("/ws-echo-string",
  23072. [](const Request &, ws::WebSocket &ws) {
  23073. std::string msg;
  23074. while (ws.read(msg)) {
  23075. ws.send("echo: " + msg);
  23076. }
  23077. });
  23078. server_->WebSocket(
  23079. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23080. // Echo back request metadata
  23081. ws.send("path:" + req.path);
  23082. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23083. std::string msg;
  23084. while (ws.read(msg)) {}
  23085. });
  23086. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23087. std::string msg;
  23088. ws.read(msg); // wait for a message
  23089. ws.close();
  23090. });
  23091. server_->WebSocket("/ws-close-status",
  23092. [](const Request &, ws::WebSocket &ws) {
  23093. std::string msg;
  23094. ws.read(msg); // wait for a message
  23095. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23096. });
  23097. server_->WebSocket(
  23098. "/ws-subprotocol",
  23099. [](const Request &, ws::WebSocket &ws) {
  23100. std::string msg;
  23101. while (ws.read(msg)) {
  23102. ws.send(msg);
  23103. }
  23104. },
  23105. [](const std::vector<std::string> &protocols) -> std::string {
  23106. for (const auto &p : protocols) {
  23107. if (p == "graphql-ws") { return p; }
  23108. }
  23109. return "";
  23110. });
  23111. server_->WebSocket(
  23112. "/ws-subprotocol-unoffered",
  23113. [](const Request &, ws::WebSocket &ws) {
  23114. std::string msg;
  23115. while (ws.read(msg)) {
  23116. ws.send(msg);
  23117. }
  23118. },
  23119. [](const std::vector<std::string> &) -> std::string {
  23120. return "admin";
  23121. });
  23122. }
  23123. void start_server() {
  23124. port_ = server_->bind_to_any_port(HOST);
  23125. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23126. server_->wait_until_ready();
  23127. }
  23128. std::unique_ptr<Server> server_;
  23129. std::thread server_thread_;
  23130. int port_ = 0;
  23131. };
  23132. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23133. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23134. "/ws-echo");
  23135. ASSERT_TRUE(client.connect());
  23136. ASSERT_TRUE(client.is_open());
  23137. ASSERT_TRUE(client.send("Hello WebSocket"));
  23138. std::string msg;
  23139. EXPECT_EQ(ws::Text, client.read(msg));
  23140. EXPECT_EQ("Hello WebSocket", msg);
  23141. client.close();
  23142. }
  23143. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23144. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23145. "/ws-echo");
  23146. ASSERT_TRUE(client.connect());
  23147. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23148. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23149. std::string msg;
  23150. EXPECT_EQ(ws::Binary, client.read(msg));
  23151. EXPECT_EQ(binary_data, msg);
  23152. client.close();
  23153. }
  23154. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23155. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23156. "/ws-echo");
  23157. ASSERT_TRUE(client.connect());
  23158. for (int i = 0; i < 10; i++) {
  23159. auto text = "message " + std::to_string(i);
  23160. ASSERT_TRUE(client.send(text));
  23161. std::string msg;
  23162. ASSERT_TRUE(client.read(msg));
  23163. EXPECT_EQ(text, msg);
  23164. }
  23165. client.close();
  23166. }
  23167. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23168. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23169. "/ws-close");
  23170. ASSERT_TRUE(client.connect());
  23171. // Send a message to trigger the server to close
  23172. ASSERT_TRUE(client.send("trigger close"));
  23173. // The server will close, so read should return false
  23174. std::string msg;
  23175. EXPECT_FALSE(client.read(msg));
  23176. EXPECT_FALSE(client.is_open());
  23177. }
  23178. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23179. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23180. "/ws-echo");
  23181. ASSERT_TRUE(client.connect());
  23182. // 128KB message
  23183. std::string large_data(128 * 1024, 'X');
  23184. ASSERT_TRUE(client.send(large_data));
  23185. std::string msg;
  23186. ASSERT_TRUE(client.read(msg));
  23187. EXPECT_EQ(large_data, msg);
  23188. client.close();
  23189. }
  23190. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23191. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23192. "/ws-echo");
  23193. ASSERT_TRUE(client.connect());
  23194. const int num_threads = 4;
  23195. std::vector<std::thread> threads;
  23196. std::atomic<int> send_count{0};
  23197. for (int t = 0; t < num_threads; t++) {
  23198. threads.emplace_back([&client, &send_count, t]() {
  23199. for (int i = 0; i < 5; i++) {
  23200. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23201. if (client.send(text)) { send_count++; }
  23202. }
  23203. });
  23204. }
  23205. for (auto &th : threads) {
  23206. th.join();
  23207. }
  23208. int received = 0;
  23209. std::string msg;
  23210. while (received < send_count.load()) {
  23211. if (!client.read(msg)) { break; }
  23212. received++;
  23213. }
  23214. EXPECT_EQ(send_count.load(), received);
  23215. client.close();
  23216. }
  23217. TEST_F(WebSocketIntegrationTest, ReadString) {
  23218. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23219. "/ws-echo-string");
  23220. ASSERT_TRUE(client.connect());
  23221. ASSERT_TRUE(client.send("hello"));
  23222. std::string msg;
  23223. ASSERT_TRUE(client.read(msg));
  23224. EXPECT_EQ("echo: hello", msg);
  23225. ASSERT_TRUE(client.send("world"));
  23226. ASSERT_TRUE(client.read(msg));
  23227. EXPECT_EQ("echo: world", msg);
  23228. client.close();
  23229. }
  23230. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23231. Headers headers = {{"X-Test-Header", "test-value"}};
  23232. ws::WebSocketClient client(
  23233. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23234. ASSERT_TRUE(client.connect());
  23235. std::string msg;
  23236. ASSERT_TRUE(client.read(msg));
  23237. EXPECT_EQ("path:/ws-request-info", msg);
  23238. ASSERT_TRUE(client.read(msg));
  23239. EXPECT_EQ("header:test-value", msg);
  23240. client.close();
  23241. }
  23242. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23243. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23244. "/ws-echo");
  23245. client.set_read_timeout(1, 0); // 1 second
  23246. ASSERT_TRUE(client.connect());
  23247. // Don't send anything — server echo handler waits for a message, so read()
  23248. // should time out. The connection survives it: nothing was consumed.
  23249. std::string msg;
  23250. EXPECT_EQ(client.read(msg), ws::Timeout);
  23251. EXPECT_TRUE(client.is_open());
  23252. // And it is still usable afterwards.
  23253. EXPECT_TRUE(client.send("after timeout"));
  23254. EXPECT_EQ(client.read(msg), ws::Text);
  23255. EXPECT_EQ(msg, "after timeout");
  23256. }
  23257. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23259. "/ws-echo");
  23260. client.set_read_timeout(1, 0);
  23261. ASSERT_TRUE(client.connect());
  23262. ASSERT_TRUE(client.send("first"));
  23263. std::string msg;
  23264. ASSERT_EQ(client.read(msg), ws::Text);
  23265. ASSERT_EQ(msg, "first");
  23266. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23267. // not be used with a read timeout: it would reprocess the previous message.
  23268. EXPECT_EQ(client.read(msg), ws::Timeout);
  23269. EXPECT_EQ(msg, "first");
  23270. }
  23271. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23272. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23273. "/ws-echo");
  23274. ASSERT_TRUE(client.connect());
  23275. // Setting it once the connection is open reaches the live stream, not just
  23276. // the seed for the next connect().
  23277. client.set_read_timeout(1, 0);
  23278. std::string msg;
  23279. EXPECT_EQ(client.read(msg), ws::Timeout);
  23280. EXPECT_TRUE(client.is_open());
  23281. }
  23282. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23283. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23284. "/ws-echo");
  23285. client.set_read_timeout(5, 0);
  23286. ASSERT_TRUE(client.connect());
  23287. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23288. // The server should reject it and close the connection.
  23289. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23290. client.send(oversized);
  23291. // The server's read() should have failed due to payload limit,
  23292. // so our read() should return false (connection closed).
  23293. std::string msg;
  23294. EXPECT_FALSE(client.read(msg));
  23295. }
  23296. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23297. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23298. "/ws-echo");
  23299. client.set_read_timeout(10, 0);
  23300. ASSERT_TRUE(client.connect());
  23301. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23302. // This should succeed.
  23303. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23304. ASSERT_TRUE(client.send(at_limit));
  23305. std::string msg;
  23306. ASSERT_TRUE(client.read(msg));
  23307. EXPECT_EQ(at_limit.size(), msg.size());
  23308. client.close();
  23309. }
  23310. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23311. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23312. "/nonexistent");
  23313. auto res = client.connect();
  23314. EXPECT_FALSE(res);
  23315. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23316. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23317. EXPECT_FALSE(client.is_open());
  23318. }
  23319. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23320. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23321. "/ws-echo");
  23322. ASSERT_TRUE(client.connect());
  23323. ASSERT_TRUE(client.send(""));
  23324. std::string msg;
  23325. EXPECT_EQ(ws::Text, client.read(msg));
  23326. EXPECT_EQ("", msg);
  23327. client.close();
  23328. }
  23329. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23330. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23331. "/ws-echo");
  23332. // First connection
  23333. ASSERT_TRUE(client.connect());
  23334. ASSERT_TRUE(client.send("first"));
  23335. std::string msg;
  23336. ASSERT_TRUE(client.read(msg));
  23337. EXPECT_EQ("first", msg);
  23338. client.close();
  23339. EXPECT_FALSE(client.is_open());
  23340. // Reconnect using the same client object
  23341. ASSERT_TRUE(client.connect());
  23342. ASSERT_TRUE(client.is_open());
  23343. ASSERT_TRUE(client.send("second"));
  23344. ASSERT_TRUE(client.read(msg));
  23345. EXPECT_EQ("second", msg);
  23346. client.close();
  23347. }
  23348. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23349. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23350. "/ws-close-status");
  23351. ASSERT_TRUE(client.connect());
  23352. // Trigger the server to close with GoingAway status
  23353. ASSERT_TRUE(client.send("trigger"));
  23354. // read() should return false after receiving the close frame
  23355. std::string msg;
  23356. EXPECT_FALSE(client.read(msg));
  23357. EXPECT_FALSE(client.is_open());
  23358. }
  23359. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23360. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23361. "/ws-echo");
  23362. ASSERT_TRUE(client.connect());
  23363. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23364. EXPECT_FALSE(client.is_open());
  23365. }
  23366. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23367. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23368. ws::WebSocketClient client(
  23369. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23370. ASSERT_TRUE(client.connect());
  23371. // Server should have selected graphql-ws
  23372. EXPECT_EQ("graphql-ws", client.subprotocol());
  23373. client.close();
  23374. }
  23375. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23376. Headers headers;
  23377. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23378. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23379. ws::WebSocketClient client(
  23380. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23381. ASSERT_TRUE(client.connect());
  23382. // The offer on the second field line counts too, so graphql-ws is selected
  23383. EXPECT_EQ("graphql-ws", client.subprotocol());
  23384. client.close();
  23385. }
  23386. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23387. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23388. ws::WebSocketClient client(
  23389. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23390. ASSERT_TRUE(client.connect());
  23391. // Server should not have selected any subprotocol
  23392. EXPECT_TRUE(client.subprotocol().empty());
  23393. client.close();
  23394. }
  23395. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23396. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23397. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23398. "/ws-subprotocol-unoffered",
  23399. headers);
  23400. ASSERT_TRUE(client.connect());
  23401. EXPECT_TRUE(client.subprotocol().empty());
  23402. client.close();
  23403. }
  23404. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23405. // Connect without requesting any subprotocol
  23406. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23407. "/ws-subprotocol");
  23408. ASSERT_TRUE(client.connect());
  23409. EXPECT_TRUE(client.subprotocol().empty());
  23410. client.close();
  23411. }
  23412. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23413. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23414. "/ws-echo");
  23415. client.set_tcp_nodelay(true);
  23416. client.set_connection_timeout(3, 0);
  23417. bool socket_options_called = false;
  23418. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23419. ASSERT_TRUE(client.connect());
  23420. ASSERT_TRUE(client.is_open());
  23421. EXPECT_TRUE(socket_options_called);
  23422. ASSERT_TRUE(client.send("hello"));
  23423. std::string msg;
  23424. auto result = client.read(msg);
  23425. EXPECT_EQ(result, ws::ReadResult::Text);
  23426. EXPECT_EQ(msg, "hello");
  23427. client.close();
  23428. }
  23429. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23430. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23431. "/ws-echo");
  23432. client.set_connection_timeout(std::chrono::seconds(3));
  23433. client.set_write_timeout(std::chrono::seconds(3));
  23434. // A sub-second remainder exercises the seconds/microseconds split.
  23435. client.set_read_timeout(std::chrono::milliseconds(1500));
  23436. ASSERT_TRUE(client.connect());
  23437. auto start = std::chrono::steady_clock::now();
  23438. std::string msg;
  23439. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23440. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23441. std::chrono::steady_clock::now() - start)
  23442. .count();
  23443. // Above 1s so that dropping the microseconds half of the split fails here.
  23444. // Ignoring the setter altogether would not reach this line at all: a client
  23445. // waits forever by default.
  23446. EXPECT_GE(elapsed, 1400);
  23447. EXPECT_LT(elapsed, 30000);
  23448. }
  23449. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23450. Server svr;
  23451. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23452. if (!req.has_header("Authorization")) {
  23453. res.status = StatusCode::Unauthorized_401;
  23454. res.set_content("Unauthorized", "text/plain");
  23455. return Server::HandlerResponse::Handled;
  23456. }
  23457. return Server::HandlerResponse::Unhandled;
  23458. });
  23459. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23460. std::string msg;
  23461. while (ws.read(msg)) {
  23462. ws.send(msg);
  23463. }
  23464. });
  23465. auto port = svr.bind_to_any_port("localhost");
  23466. std::thread t([&]() { svr.listen_after_bind(); });
  23467. svr.wait_until_ready();
  23468. // Without Authorization header - should be rejected before upgrade
  23469. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23470. EXPECT_FALSE(client1.connect());
  23471. // The rejection is framed like any other HTTP response
  23472. {
  23473. Client cli("localhost", port);
  23474. Headers headers = {{"Upgrade", "websocket"},
  23475. {"Connection", "Upgrade"},
  23476. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23477. {"Sec-WebSocket-Version", "13"}};
  23478. auto res = cli.Get("/ws", headers);
  23479. ASSERT_TRUE(res);
  23480. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23481. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23482. EXPECT_EQ("Unauthorized", res->body);
  23483. }
  23484. // With Authorization header - should succeed
  23485. Headers headers = {{"Authorization", "Bearer token123"}};
  23486. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23487. headers);
  23488. ASSERT_TRUE(client2.connect());
  23489. ASSERT_TRUE(client2.send("hello"));
  23490. std::string msg;
  23491. ASSERT_TRUE(client2.read(msg));
  23492. EXPECT_EQ("hello", msg);
  23493. client2.close();
  23494. svr.stop();
  23495. t.join();
  23496. }
  23497. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23498. Server svr;
  23499. std::atomic<int> pre_routing_calls{0};
  23500. std::atomic<int> pre_request_calls{0};
  23501. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23502. pre_routing_calls++;
  23503. if (req.path == "/handled") {
  23504. res.set_content("handled", "text/plain");
  23505. return Server::HandlerResponse::Handled;
  23506. }
  23507. return Server::HandlerResponse::Unhandled;
  23508. });
  23509. svr.set_pre_request_handler([&](const Request &, Response &) {
  23510. pre_request_calls++;
  23511. return Server::HandlerResponse::Unhandled;
  23512. });
  23513. svr.Get("/http", [](const Request &, Response &res) {
  23514. res.set_content("http", "text/plain");
  23515. });
  23516. svr.WebSocket("/ws",
  23517. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23518. auto port = svr.bind_to_any_port("localhost");
  23519. std::thread t([&]() { svr.listen_after_bind(); });
  23520. auto se = detail::scope_exit([&] {
  23521. svr.stop();
  23522. t.join();
  23523. });
  23524. svr.wait_until_ready();
  23525. Headers upgrade = {{"Upgrade", "websocket"},
  23526. {"Connection", "Upgrade"},
  23527. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23528. {"Sec-WebSocket-Version", "13"}};
  23529. auto get = [&](const char *path) {
  23530. pre_routing_calls = 0;
  23531. return Client("localhost", port).Get(path, upgrade);
  23532. };
  23533. // No WebSocket route, but an HTTP one
  23534. auto res = get("/http");
  23535. ASSERT_TRUE(res);
  23536. EXPECT_EQ(StatusCode::OK_200, res->status);
  23537. EXPECT_EQ("http", res->body);
  23538. EXPECT_EQ(1, pre_routing_calls);
  23539. EXPECT_EQ(1, pre_request_calls);
  23540. // No route at all
  23541. res = get("/none");
  23542. ASSERT_TRUE(res);
  23543. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23544. EXPECT_EQ(1, pre_routing_calls);
  23545. // Answered by the pre-routing handler
  23546. res = get("/handled");
  23547. ASSERT_TRUE(res);
  23548. EXPECT_EQ(StatusCode::OK_200, res->status);
  23549. EXPECT_EQ("handled", res->body);
  23550. EXPECT_EQ(1, pre_routing_calls);
  23551. // A WebSocket route
  23552. pre_routing_calls = 0;
  23553. pre_request_calls = 0;
  23554. {
  23555. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23556. "/ws");
  23557. ASSERT_TRUE(client.connect());
  23558. std::string msg;
  23559. ASSERT_TRUE(client.read(msg));
  23560. EXPECT_EQ("ws", msg);
  23561. client.close();
  23562. }
  23563. EXPECT_EQ(1, pre_routing_calls);
  23564. EXPECT_EQ(1, pre_request_calls);
  23565. }
  23566. // An upgrade request answered by a hook leaves its body unread, so that body
  23567. // must not be served as the next request on the connection.
  23568. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23569. Server svr;
  23570. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23571. if (req.path == "/pre-routing") {
  23572. res.set_content("pre-routing", "text/plain");
  23573. return Server::HandlerResponse::Handled;
  23574. }
  23575. return Server::HandlerResponse::Unhandled;
  23576. });
  23577. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23578. if (req.matched_route == "/pre-request") {
  23579. res.set_content("pre-request", "text/plain");
  23580. return Server::HandlerResponse::Handled;
  23581. }
  23582. return Server::HandlerResponse::Unhandled;
  23583. });
  23584. svr.Get("/smuggled", [](const Request &, Response &res) {
  23585. res.set_content("smuggled", "text/plain");
  23586. });
  23587. svr.WebSocket("/pre-request",
  23588. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23589. auto port = svr.bind_to_any_port(HOST);
  23590. std::thread t([&]() { svr.listen_after_bind(); });
  23591. auto se = detail::scope_exit([&] {
  23592. svr.stop();
  23593. t.join();
  23594. });
  23595. svr.wait_until_ready();
  23596. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23597. for (auto path : {"/pre-routing", "/pre-request"}) {
  23598. std::string req = std::string("GET ") + path +
  23599. " HTTP/1.1\r\n"
  23600. "Host: localhost\r\n"
  23601. "Upgrade: websocket\r\n"
  23602. "Connection: Upgrade\r\n"
  23603. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23604. "Sec-WebSocket-Version: 13\r\n"
  23605. "Content-Length: " +
  23606. std::to_string(body.size()) + "\r\n\r\n" + body;
  23607. std::string res;
  23608. ASSERT_TRUE(send_request(5, req, &res, port));
  23609. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23610. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23611. // Only one response, and the body was not served as a request
  23612. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23613. }
  23614. }
  23615. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23616. Server svr;
  23617. std::atomic<int> pre_request_calls{0};
  23618. std::atomic<bool> route_matched{false};
  23619. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23620. pre_request_calls++;
  23621. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23622. if (req.get_header_value("Authorization") != "Bearer token123") {
  23623. res.status = StatusCode::Unauthorized_401;
  23624. res.set_content("Unauthorized", "text/plain");
  23625. return Server::HandlerResponse::Handled;
  23626. }
  23627. return Server::HandlerResponse::Unhandled;
  23628. });
  23629. std::atomic<bool> handler_called{false};
  23630. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23631. handler_called = true;
  23632. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23633. });
  23634. auto port = svr.bind_to_any_port("localhost");
  23635. std::thread t([&]() { svr.listen_after_bind(); });
  23636. svr.wait_until_ready();
  23637. // Without Authorization header - should be rejected before upgrade
  23638. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23639. "/ws/1");
  23640. EXPECT_FALSE(client1.connect());
  23641. EXPECT_FALSE(handler_called);
  23642. EXPECT_EQ(1, pre_request_calls);
  23643. EXPECT_TRUE(route_matched);
  23644. // The rejection is an ordinary HTTP response, not a protocol switch
  23645. {
  23646. Client cli("localhost", port);
  23647. Headers headers = {{"Upgrade", "websocket"},
  23648. {"Connection", "Upgrade"},
  23649. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23650. {"Sec-WebSocket-Version", "13"}};
  23651. auto res = cli.Get("/ws/1", headers);
  23652. ASSERT_TRUE(res);
  23653. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23654. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23655. EXPECT_EQ("Unauthorized", res->body);
  23656. }
  23657. EXPECT_FALSE(handler_called);
  23658. // With Authorization header - should succeed
  23659. Headers headers = {{"Authorization", "Bearer token123"}};
  23660. ws::WebSocketClient client2(
  23661. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23662. ASSERT_TRUE(client2.connect());
  23663. std::string msg;
  23664. ASSERT_TRUE(client2.read(msg));
  23665. EXPECT_EQ("/ws/:id 2", msg);
  23666. EXPECT_TRUE(handler_called);
  23667. client2.close();
  23668. svr.stop();
  23669. t.join();
  23670. }
  23671. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23672. Server svr;
  23673. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23674. // A read timeout is how a handler gets control back. Without it, a handler
  23675. // parked in read() can never write on the connection it is reading.
  23676. ws.set_read_timeout(std::chrono::milliseconds(100));
  23677. std::string msg;
  23678. while (ws.is_open()) {
  23679. auto r = ws.read(msg);
  23680. if (r == httplib::ws::Timeout) {
  23681. ws.send("tick");
  23682. continue;
  23683. }
  23684. if (r == httplib::ws::Fail) { break; }
  23685. ws.send(msg);
  23686. }
  23687. });
  23688. auto port = svr.bind_to_any_port("localhost");
  23689. std::thread t([&]() { svr.listen_after_bind(); });
  23690. svr.wait_until_ready();
  23691. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23692. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23693. ASSERT_TRUE(client.connect());
  23694. // The client sends nothing, so anything it receives came out of the
  23695. // handler's timeout path.
  23696. std::string msg;
  23697. ASSERT_EQ(client.read(msg), ws::Text);
  23698. EXPECT_EQ("tick", msg);
  23699. client.close();
  23700. svr.stop();
  23701. t.join();
  23702. }
  23703. // Stream::read may return fewer bytes than asked for. This is that contract at
  23704. // its worst -- one byte per call -- which is what a frame header straddling a
  23705. // read buffer's boundary looks like to the frame parser.
  23706. class WsByteAtATimeStream : public Stream {
  23707. public:
  23708. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23709. bool is_readable() const override { return true; }
  23710. bool wait_readable() const override { return true; }
  23711. bool wait_writable() const override { return true; }
  23712. ssize_t read(char *ptr, size_t size) override {
  23713. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23714. *ptr = data_[pos_++];
  23715. return 1;
  23716. }
  23717. ssize_t write(const char *, size_t size) override {
  23718. return static_cast<ssize_t>(size);
  23719. }
  23720. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23721. ip = "127.0.0.1";
  23722. port = 0;
  23723. }
  23724. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23725. ip = "127.0.0.1";
  23726. port = 0;
  23727. }
  23728. socket_t socket() const override { return INVALID_SOCKET; }
  23729. time_t duration() const override { return 0; }
  23730. private:
  23731. std::string data_;
  23732. size_t pos_ = 0;
  23733. };
  23734. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23735. // The payload uses the 16-bit extended length, so the header, the length
  23736. // and the mask key are all multi-byte fields here. Each used to be read
  23737. // with a single read() call, which fails as soon as one is split. The
  23738. // payload is also a little over one read chunk, so it is read in two.
  23739. std::string body;
  23740. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23741. body += static_cast<char>(i % 251);
  23742. }
  23743. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23744. std::string frame;
  23745. frame += static_cast<char>(0x81); // FIN + Text
  23746. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23747. frame += static_cast<char>(body.size() >> 8);
  23748. frame += static_cast<char>(body.size() & 0xff);
  23749. for (size_t i = 0; i < 4; i++) {
  23750. frame += static_cast<char>(mask[i]);
  23751. }
  23752. for (size_t i = 0; i < body.size(); i++) {
  23753. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23754. }
  23755. WsByteAtATimeStream strm(frame);
  23756. ws::Opcode opcode;
  23757. std::string payload;
  23758. bool fin = false;
  23759. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23760. /*expect_masked=*/true, body.size()),
  23761. ws::impl::FrameRead::Ok);
  23762. EXPECT_TRUE(fin);
  23763. EXPECT_EQ(opcode, ws::Opcode::Text);
  23764. EXPECT_EQ(payload, body);
  23765. }
  23766. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23767. std::string body(2000, 'x');
  23768. std::string frame;
  23769. frame += static_cast<char>(0x82); // FIN + Binary
  23770. frame += static_cast<char>(126); // 16-bit length follows
  23771. frame += static_cast<char>(body.size() >> 8);
  23772. frame += static_cast<char>(body.size() & 0xff);
  23773. frame += body;
  23774. detail::BufferStream strm;
  23775. strm.write(frame.data(), frame.size());
  23776. ws::Opcode opcode;
  23777. std::string payload;
  23778. bool fin;
  23779. EXPECT_EQ(
  23780. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23781. ws::impl::FrameRead::Ok);
  23782. EXPECT_EQ(body, payload);
  23783. }
  23784. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23785. // The header announces the largest payload allowed, and only 3 bytes of it
  23786. // ever arrive.
  23787. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23788. std::string frame;
  23789. frame += static_cast<char>(0x82); // FIN + Binary
  23790. frame += static_cast<char>(127); // 64-bit length follows
  23791. for (int shift = 56; shift >= 0; shift -= 8) {
  23792. frame += static_cast<char>((len >> shift) & 0xff);
  23793. }
  23794. frame += "abc";
  23795. detail::BufferStream strm;
  23796. strm.write(frame.data(), frame.size());
  23797. ws::Opcode opcode;
  23798. std::string payload;
  23799. bool fin;
  23800. EXPECT_EQ(
  23801. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23802. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23803. ws::impl::FrameRead::Fail);
  23804. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23805. }
  23806. TEST(WebSocketTest, QueryStringInHandshake) {
  23807. Server svr;
  23808. std::mutex mtx;
  23809. std::string received_target;
  23810. std::string received_token;
  23811. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23812. {
  23813. std::lock_guard<std::mutex> lock(mtx);
  23814. received_target = req.target;
  23815. if (req.has_param("token")) {
  23816. received_token = req.get_param_value("token");
  23817. }
  23818. }
  23819. std::string msg;
  23820. while (ws.read(msg)) {
  23821. ws.send(msg);
  23822. }
  23823. });
  23824. auto port = svr.bind_to_any_port("localhost");
  23825. std::thread t([&]() { svr.listen_after_bind(); });
  23826. svr.wait_until_ready();
  23827. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23828. "/ws?token=ABC&session=123");
  23829. ASSERT_TRUE(client.connect());
  23830. // Round-trip ensures the handler has run and captured the request.
  23831. ASSERT_TRUE(client.send("hello"));
  23832. std::string msg;
  23833. ASSERT_TRUE(client.read(msg));
  23834. EXPECT_EQ("hello", msg);
  23835. client.close();
  23836. {
  23837. std::lock_guard<std::mutex> lock(mtx);
  23838. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23839. EXPECT_EQ("ABC", received_token);
  23840. }
  23841. svr.stop();
  23842. t.join();
  23843. }
  23844. // Run a handshake against a throwaway server and hand the request the server
  23845. // received back to the caller, so tests can assert on the headers the client
  23846. // actually put on the wire.
  23847. static void capture_websocket_handshake_request(
  23848. const Headers &client_headers,
  23849. std::function<void(const Request &, int port)> verify) {
  23850. Server svr;
  23851. std::mutex mtx;
  23852. Request received;
  23853. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23854. {
  23855. std::lock_guard<std::mutex> lock(mtx);
  23856. received = req;
  23857. }
  23858. std::string msg;
  23859. while (ws.read(msg)) {
  23860. ws.send(msg);
  23861. }
  23862. });
  23863. auto port = svr.bind_to_any_port("localhost");
  23864. std::thread t([&]() { svr.listen_after_bind(); });
  23865. auto se = detail::scope_exit([&] {
  23866. svr.stop();
  23867. t.join();
  23868. });
  23869. svr.wait_until_ready();
  23870. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23871. client_headers);
  23872. ASSERT_TRUE(client.connect());
  23873. ASSERT_TRUE(client.send("hello"));
  23874. std::string msg;
  23875. ASSERT_TRUE(client.read(msg));
  23876. client.close();
  23877. {
  23878. std::lock_guard<std::mutex> lock(mtx);
  23879. verify(received, port);
  23880. }
  23881. }
  23882. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23883. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23884. // Non-default port must be present in the Host header. Default ports
  23885. // (80/443) are omitted; that logic is covered by
  23886. // MakeHostAndPortStringTest.
  23887. EXPECT_EQ("localhost:" + std::to_string(port),
  23888. req.get_header_value("Host"));
  23889. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23890. req.get_header_value("User-Agent"));
  23891. EXPECT_FALSE(req.has_header("Accept"));
  23892. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23893. EXPECT_FALSE(req.has_header("Content-Length"));
  23894. });
  23895. }
  23896. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23897. capture_websocket_handshake_request(
  23898. {{"Host", "example.com"},
  23899. {"User-Agent", "custom-agent"},
  23900. {"X-Custom", "value"}},
  23901. [](const Request &req, int) {
  23902. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23903. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23904. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23905. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23906. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23907. });
  23908. }
  23909. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23910. capture_websocket_handshake_request(
  23911. {{"Upgrade", "bogus"},
  23912. {"Connection", "close"},
  23913. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23914. {"Sec-WebSocket-Version", "8"}},
  23915. [](const Request &req, int) {
  23916. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23917. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23918. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23919. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23920. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23921. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23922. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23923. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23924. req.get_header_value("Sec-WebSocket-Key"));
  23925. });
  23926. }
  23927. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23928. // A header the client refuses to send must abort the handshake before any
  23929. // part of it reaches the wire; a lone request line would otherwise sit in
  23930. // the peer's buffer as a truncated request.
  23931. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23932. ASSERT_NE(INVALID_SOCKET, srv);
  23933. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23934. sockaddr_in addr{};
  23935. addr.sin_family = AF_INET;
  23936. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23937. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23938. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23939. ASSERT_EQ(0, ::listen(srv, 1));
  23940. sockaddr_in bound{};
  23941. socklen_t bound_len = sizeof(bound);
  23942. ASSERT_EQ(
  23943. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23944. auto port = ntohs(bound.sin_port);
  23945. ssize_t received = -1;
  23946. std::thread t([&] {
  23947. // Bound every blocking call so a regression fails the test with a bad
  23948. // value instead of hanging the suite.
  23949. fd_set rfds;
  23950. FD_ZERO(&rfds);
  23951. FD_SET(srv, &rfds);
  23952. timeval tv{5, 0};
  23953. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23954. 0) {
  23955. return;
  23956. }
  23957. sockaddr_in cli_addr{};
  23958. socklen_t cli_len = sizeof(cli_addr);
  23959. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23960. if (cli == INVALID_SOCKET) { return; }
  23961. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23962. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23963. char buf[4096];
  23964. received = ::recv(cli, buf, sizeof(buf), 0);
  23965. });
  23966. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23967. // connect() has already shut the socket down by the time it returns false,
  23968. // so the peer sees EOF without waiting for the client to be destroyed.
  23969. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23970. {{"X-Bad", "a\r\nInjected: 1"}});
  23971. EXPECT_FALSE(client.connect());
  23972. t.join();
  23973. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23974. EXPECT_EQ(0, received);
  23975. }
  23976. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23977. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23978. // contains "upgrade" as a substring is a different token and must not
  23979. // start a WebSocket handshake.
  23980. auto make_request = [](const std::vector<std::string> &connection_values) {
  23981. Request req;
  23982. req.method = "GET";
  23983. req.headers.emplace("Upgrade", "websocket");
  23984. for (const auto &value : connection_values) {
  23985. req.headers.emplace("Connection", value);
  23986. }
  23987. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23988. req.headers.emplace("Sec-WebSocket-Version", "13");
  23989. return req;
  23990. };
  23991. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23992. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23993. EXPECT_TRUE(
  23994. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23995. EXPECT_TRUE(
  23996. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23997. EXPECT_TRUE(
  23998. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23999. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24000. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24001. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24002. EXPECT_FALSE(
  24003. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24004. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24005. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24006. }
  24007. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24008. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24009. // asks recipients to match each protocol-name case-insensitively, and RFC
  24010. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24011. // client naming websocket alongside another protocol, or on a second field
  24012. // line, is offering websocket; a value that merely contains "websocket" as a
  24013. // substring is a different protocol name and is not.
  24014. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24015. Request req;
  24016. req.method = "GET";
  24017. for (const auto &value : upgrade_values) {
  24018. req.headers.emplace("Upgrade", value);
  24019. }
  24020. req.headers.emplace("Connection", "Upgrade");
  24021. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24022. req.headers.emplace("Sec-WebSocket-Version", "13");
  24023. return req;
  24024. };
  24025. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24026. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24027. EXPECT_TRUE(
  24028. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24029. EXPECT_TRUE(
  24030. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24031. EXPECT_TRUE(
  24032. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24033. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24034. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24035. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24036. EXPECT_FALSE(
  24037. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24038. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24039. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24040. }
  24041. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24042. Server svr;
  24043. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24044. auto port = svr.bind_to_any_port("localhost");
  24045. std::thread t([&]() { svr.listen_after_bind(); });
  24046. auto se = detail::scope_exit([&] {
  24047. svr.stop();
  24048. t.join();
  24049. });
  24050. svr.wait_until_ready();
  24051. Headers headers = {{"Upgrade", "websocket"},
  24052. {"Connection", "notupgrade"},
  24053. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24054. {"Sec-WebSocket-Version", "13"}};
  24055. Client cli("localhost", port);
  24056. auto res = cli.Get("/ws", headers);
  24057. // The route exists only as a WebSocket route, so a request that fails the
  24058. // handshake check falls through to ordinary routing.
  24059. ASSERT_TRUE(res);
  24060. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24061. }
  24062. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24063. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24064. // Connection value is the only thing left for the client to reject.
  24065. Server svr;
  24066. svr.Get("/ws", [](const Request &req, Response &res) {
  24067. res.status = StatusCode::SwitchingProtocol_101;
  24068. res.set_header("Upgrade", "websocket");
  24069. res.set_header("Connection", "notupgrade");
  24070. res.set_header("Sec-WebSocket-Accept",
  24071. detail::websocket_accept_key(
  24072. req.get_header_value("Sec-WebSocket-Key")));
  24073. });
  24074. auto port = svr.bind_to_any_port("localhost");
  24075. std::thread t([&]() { svr.listen_after_bind(); });
  24076. auto se = detail::scope_exit([&] {
  24077. svr.stop();
  24078. t.join();
  24079. });
  24080. svr.wait_until_ready();
  24081. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24082. auto res = client.connect();
  24083. EXPECT_FALSE(res);
  24084. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24085. EXPECT_FALSE(client.is_open());
  24086. }
  24087. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24088. Server svr;
  24089. svr.Get("/ws", [](const Request &req, Response &res) {
  24090. res.status = StatusCode::SwitchingProtocol_101;
  24091. res.set_header("Upgrade", "websocket");
  24092. res.set_header("Connection", "Upgrade");
  24093. res.set_header("Sec-WebSocket-Accept",
  24094. detail::websocket_accept_key(
  24095. req.get_header_value("Sec-WebSocket-Key")));
  24096. res.set_header("Sec-WebSocket-Protocol", "admin");
  24097. });
  24098. auto port = svr.bind_to_any_port("localhost");
  24099. std::thread t([&]() { svr.listen_after_bind(); });
  24100. auto se = detail::scope_exit([&] {
  24101. svr.stop();
  24102. t.join();
  24103. });
  24104. svr.wait_until_ready();
  24105. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24106. // Server selects a subprotocol the client never offered
  24107. {
  24108. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24109. ws::WebSocketClient client(url, headers);
  24110. auto res = client.connect();
  24111. EXPECT_FALSE(res);
  24112. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24113. EXPECT_FALSE(client.is_open());
  24114. EXPECT_TRUE(client.subprotocol().empty());
  24115. }
  24116. // Client offered none but the server named one anyway
  24117. {
  24118. ws::WebSocketClient client(url);
  24119. auto res = client.connect();
  24120. EXPECT_FALSE(res);
  24121. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24122. EXPECT_FALSE(client.is_open());
  24123. EXPECT_TRUE(client.subprotocol().empty());
  24124. }
  24125. }
  24126. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24127. // The socket path doubles as the URL host, so it must not contain '/'.
  24128. const char *shard = getenv("GTEST_SHARD_INDEX");
  24129. const std::string sock_path =
  24130. shard ? std::string("httplib-ws-") + shard + ".sock"
  24131. : std::string("httplib-ws.sock");
  24132. std::remove(sock_path.c_str());
  24133. Server svr;
  24134. std::mutex mtx;
  24135. std::string received_host;
  24136. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24137. {
  24138. std::lock_guard<std::mutex> lock(mtx);
  24139. received_host = req.get_header_value("Host");
  24140. }
  24141. std::string msg;
  24142. while (ws.read(msg)) {
  24143. ws.send(msg);
  24144. }
  24145. });
  24146. svr.set_address_family(AF_UNIX);
  24147. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24148. auto se = detail::scope_exit([&] {
  24149. svr.stop();
  24150. t.join();
  24151. std::remove(sock_path.c_str());
  24152. });
  24153. svr.wait_until_ready();
  24154. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24155. client.set_address_family(AF_UNIX);
  24156. ASSERT_TRUE(client.connect());
  24157. ASSERT_TRUE(client.send("hello"));
  24158. std::string msg;
  24159. ASSERT_TRUE(client.read(msg));
  24160. client.close();
  24161. {
  24162. std::lock_guard<std::mutex> lock(mtx);
  24163. // There is no host:port for a Unix socket, so the same "localhost"
  24164. // placeholder the HTTP client uses is expected.
  24165. EXPECT_EQ("localhost", received_host);
  24166. }
  24167. }
  24168. // Two threads must never parse WebSocket frames from the same stream.
  24169. // close() used to read the peer's Close reply with its own frame read, so it
  24170. // raced a reader thread that was in the middle of a payload: the payload loop
  24171. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24172. // so bytes taken by close() were replaced with bytes from further along the
  24173. // stream. The message kept its length and silently changed content.
  24174. //
  24175. // The raw peer below sends a frame header plus part of the payload, waits for
  24176. // the handler to call close(), and only then sends the rest. Whichever thread
  24177. // would win the race for those bytes, the message must arrive intact, because
  24178. // close() must not touch the stream while read() owns it.
  24179. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24180. #ifndef _WIN32
  24181. signal(SIGPIPE, SIG_IGN);
  24182. #endif
  24183. const size_t payload_len = 120; // fits the 7-bit length field
  24184. const size_t prefix_len = 8;
  24185. const int attempts = 8;
  24186. std::string expected(payload_len, '\0');
  24187. for (size_t i = 0; i < payload_len; i++) {
  24188. expected[i] = static_cast<char>('a' + i % 26);
  24189. }
  24190. std::atomic<bool> peer_stalled{false};
  24191. std::atomic<bool> handler_done{false};
  24192. std::mutex received_mutex;
  24193. std::vector<std::string> received;
  24194. // Bound every wait, so a regression fails the test instead of hanging the
  24195. // suite.
  24196. auto wait_for = [](const std::atomic<bool> &flag) {
  24197. for (int i = 0; i < 500 && !flag; i++) {
  24198. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24199. }
  24200. };
  24201. Server svr;
  24202. svr.set_websocket_ping_interval(0);
  24203. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24204. std::thread reader([&]() {
  24205. std::string msg;
  24206. while (ws.read(msg)) {
  24207. std::lock_guard<std::mutex> guard(received_mutex);
  24208. received.push_back(msg);
  24209. }
  24210. });
  24211. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24212. // inside read_websocket_frame() when close() runs.
  24213. wait_for(peer_stalled);
  24214. ws.close();
  24215. reader.join();
  24216. handler_done = true;
  24217. });
  24218. auto port = svr.bind_to_any_port("127.0.0.1");
  24219. std::thread t([&]() { svr.listen_after_bind(); });
  24220. auto se = detail::scope_exit([&] {
  24221. svr.stop();
  24222. t.join();
  24223. });
  24224. svr.wait_until_ready();
  24225. auto send_bytes = [](socket_t s, const std::string &data) {
  24226. #ifdef _WIN32
  24227. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24228. #else
  24229. auto n = ::send(s, data.data(), data.size(), 0);
  24230. #endif
  24231. return n == static_cast<decltype(n)>(data.size());
  24232. };
  24233. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24234. // Every length used here fits the 7-bit length field.
  24235. auto masked_header = [](uint8_t first_byte, size_t len) {
  24236. std::string h;
  24237. h += static_cast<char>(first_byte);
  24238. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24239. h.append(4, '\0'); // mask key
  24240. return h;
  24241. };
  24242. for (int attempt = 0; attempt < attempts; attempt++) {
  24243. peer_stalled = false;
  24244. handler_done = false;
  24245. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24246. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24247. auto se_sock = detail::scope_exit([&] {
  24248. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24249. });
  24250. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24251. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24252. sockaddr_in addr{};
  24253. addr.sin_family = AF_INET;
  24254. addr.sin_port = htons(static_cast<uint16_t>(port));
  24255. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24256. ASSERT_EQ(
  24257. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24258. << "attempt " << attempt;
  24259. ASSERT_TRUE(send_bytes(sock,
  24260. "GET /ws HTTP/1.1\r\n"
  24261. "Host: 127.0.0.1\r\n"
  24262. "Upgrade: websocket\r\n"
  24263. "Connection: Upgrade\r\n"
  24264. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24265. "Sec-WebSocket-Version: 13\r\n"
  24266. "\r\n"))
  24267. << "attempt " << attempt;
  24268. std::string response;
  24269. while (response.find("\r\n\r\n") == std::string::npos) {
  24270. char buf[512];
  24271. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24272. if (n <= 0) { break; }
  24273. response.append(buf, static_cast<size_t>(n));
  24274. }
  24275. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24276. << "attempt " << attempt;
  24277. // Send the header of a Binary message but only the first prefix_len bytes
  24278. // of its payload, leaving the reader thread stalled inside the payload.
  24279. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24280. expected.substr(0, prefix_len)))
  24281. << "attempt " << attempt;
  24282. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24283. peer_stalled = true;
  24284. // Let close() send its Close frame and park in its own read before the
  24285. // rest of the payload arrives, so both threads are waiting for it.
  24286. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24287. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24288. close_frame += static_cast<char>(0x03); // status 1000
  24289. close_frame += static_cast<char>(0xE8);
  24290. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24291. << "attempt " << attempt;
  24292. // Closing the peer releases the reader thread even on the buggy path,
  24293. // where it waits for bytes another thread already consumed.
  24294. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24295. detail::close_socket(sock);
  24296. sock = INVALID_SOCKET;
  24297. wait_for(handler_done);
  24298. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24299. }
  24300. std::lock_guard<std::mutex> guard(received_mutex);
  24301. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24302. << "a message in flight when close() ran was dropped";
  24303. for (size_t i = 0; i < received.size(); i++) {
  24304. EXPECT_EQ(expected, received[i]) << "message " << i;
  24305. }
  24306. }
  24307. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24308. // returning the socket, or INVALID_SOCKET.
  24309. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24310. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24311. if (sock == INVALID_SOCKET) { return sock; }
  24312. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24313. sockaddr_in addr{};
  24314. addr.sin_family = AF_INET;
  24315. addr.sin_port = htons(static_cast<uint16_t>(port));
  24316. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24317. std::string req = "GET " + path +
  24318. " HTTP/1.1\r\n"
  24319. "Host: 127.0.0.1\r\n"
  24320. "Upgrade: websocket\r\n"
  24321. "Connection: Upgrade\r\n"
  24322. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24323. "Sec-WebSocket-Version: 13\r\n"
  24324. "\r\n";
  24325. std::string res;
  24326. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24327. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24328. static_cast<ssize_t>(req.size())) {
  24329. char c;
  24330. while (res.find("\r\n\r\n") == std::string::npos &&
  24331. ::recv(sock, &c, 1, 0) == 1) {
  24332. res += c;
  24333. }
  24334. }
  24335. if (res.find(" 101 ") == std::string::npos) {
  24336. detail::close_socket(sock);
  24337. return INVALID_SOCKET;
  24338. }
  24339. return sock;
  24340. }
  24341. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24342. // The payload must fit the 7-bit length field.
  24343. static std::string masked_frame(uint8_t first_byte,
  24344. const std::string &payload) {
  24345. std::string f;
  24346. f += static_cast<char>(first_byte);
  24347. f += static_cast<char>(0x80 | payload.size());
  24348. f.append(4, '\0');
  24349. return f + payload;
  24350. }
  24351. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24352. std::atomic<bool> done{false};
  24353. std::string received;
  24354. Server svr;
  24355. svr.set_websocket_ping_interval(0);
  24356. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24357. std::string msg;
  24358. if (ws.read(msg) == ws::Binary) { received = msg; }
  24359. done = true;
  24360. });
  24361. auto port = svr.bind_to_any_port("127.0.0.1");
  24362. std::thread t([&]() { svr.listen_after_bind(); });
  24363. auto se = detail::scope_exit([&] {
  24364. svr.stop();
  24365. t.join();
  24366. });
  24367. svr.wait_until_ready();
  24368. auto sock = connect_raw_websocket(port, "/ws");
  24369. ASSERT_NE(INVALID_SOCKET, sock);
  24370. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24371. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24372. masked_frame(0x89, "p") + // FIN + Ping
  24373. masked_frame(0x80, "lo"); // FIN + Continuation
  24374. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24375. for (int i = 0; i < 500 && !done; i++) {
  24376. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24377. }
  24378. ASSERT_TRUE(done);
  24379. EXPECT_EQ("Hello", received);
  24380. // The Ping between the fragments is answered with a Pong.
  24381. char pong[3];
  24382. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24383. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24384. }
  24385. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24386. Server svr;
  24387. svr.set_websocket_ping_interval(-1);
  24388. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24389. std::string msg;
  24390. while (ws.read(msg)) {}
  24391. });
  24392. auto port = svr.bind_to_any_port("127.0.0.1");
  24393. std::thread t([&]() { svr.listen_after_bind(); });
  24394. auto se = detail::scope_exit([&] {
  24395. svr.stop();
  24396. t.join();
  24397. });
  24398. svr.wait_until_ready();
  24399. auto sock = connect_raw_websocket(port, "/ws");
  24400. ASSERT_NE(INVALID_SOCKET, sock);
  24401. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24402. // Nothing comes while the client stays quiet.
  24403. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24404. char c;
  24405. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24406. }
  24407. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24408. // and that has to end a read() already waiting on the peer, on every platform.
  24409. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24410. // The peer sends no pings, and its handler never calls read(), which is
  24411. // where pongs are written.
  24412. std::mutex mutex;
  24413. std::condition_variable cv;
  24414. auto release = false;
  24415. svr.set_websocket_ping_interval(0);
  24416. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24417. std::unique_lock<std::mutex> lock(mutex);
  24418. cv.wait(lock, [&] { return release; });
  24419. });
  24420. auto port = svr.bind_to_any_port(HOST);
  24421. std::thread t([&]() { svr.listen_after_bind(); });
  24422. auto se = detail::scope_exit([&] {
  24423. {
  24424. std::lock_guard<std::mutex> lock(mutex);
  24425. release = true;
  24426. }
  24427. cv.notify_all();
  24428. svr.stop();
  24429. t.join();
  24430. });
  24431. svr.wait_until_ready();
  24432. ws::WebSocketClient client(std::string(scheme) +
  24433. "://localhost:" + std::to_string(port) + "/ws");
  24434. #ifdef CPPHTTPLIB_SSL_ENABLED
  24435. client.enable_server_certificate_verification(false);
  24436. #endif
  24437. // A ping a second, given up on after two go unanswered: about 3s
  24438. client.set_websocket_ping_interval(1);
  24439. client.set_websocket_max_missed_pongs(2);
  24440. // Well past that, so that a read the timeout ends instead stands out
  24441. client.set_read_timeout(10);
  24442. ASSERT_TRUE(client.connect());
  24443. auto start = std::chrono::steady_clock::now();
  24444. std::string msg;
  24445. EXPECT_EQ(ws::Fail, client.read(msg));
  24446. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24447. std::chrono::steady_clock::now() - start)
  24448. .count(),
  24449. 6000);
  24450. EXPECT_FALSE(client.is_open());
  24451. }
  24452. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24453. Server svr;
  24454. check_pong_timeout_ends_read(svr, "ws");
  24455. }
  24456. #ifdef CPPHTTPLIB_SSL_ENABLED
  24457. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24458. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24459. ASSERT_TRUE(svr.is_valid());
  24460. check_pong_timeout_ends_read(svr, "wss");
  24461. }
  24462. #endif
  24463. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24464. Server svr;
  24465. svr.set_websocket_ping_interval(0);
  24466. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24467. std::string msg;
  24468. while (ws.read(msg)) {}
  24469. });
  24470. auto port = svr.bind_to_any_port("127.0.0.1");
  24471. std::thread t([&]() { svr.listen_after_bind(); });
  24472. auto se = detail::scope_exit([&] {
  24473. svr.stop();
  24474. t.join();
  24475. });
  24476. svr.wait_until_ready();
  24477. // Each Close payload and the reply it should get: an echo when valid, 1002
  24478. // otherwise.
  24479. std::vector<std::pair<std::string, std::string>> cases = {
  24480. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24481. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24482. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24483. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24484. };
  24485. // Also between the fragments of a message.
  24486. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24487. for (const auto &c : cases) {
  24488. auto sock = connect_raw_websocket(port, "/ws");
  24489. ASSERT_NE(INVALID_SOCKET, sock);
  24490. auto frames = prefix + masked_frame(0x88, c.first);
  24491. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24492. std::string reply;
  24493. char buf[256];
  24494. while (reply.size() < 2 + c.second.size()) {
  24495. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24496. if (n <= 0) { break; }
  24497. reply.append(buf, static_cast<size_t>(n));
  24498. }
  24499. detail::close_socket(sock);
  24500. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24501. c.second,
  24502. reply);
  24503. }
  24504. }
  24505. }
  24506. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24507. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24508. protected:
  24509. void SetUp() override {
  24510. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24511. SERVER_PRIVATE_KEY_FILE);
  24512. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24513. std::string msg;
  24514. ws::ReadResult ret;
  24515. while ((ret = ws.read(msg))) {
  24516. if (ret == ws::Binary) {
  24517. ws.send(msg.data(), msg.size());
  24518. } else {
  24519. ws.send(msg);
  24520. }
  24521. }
  24522. });
  24523. port_ = server_->bind_to_any_port(HOST);
  24524. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24525. server_->wait_until_ready();
  24526. }
  24527. void TearDown() override {
  24528. server_->stop();
  24529. if (server_thread_.joinable()) { server_thread_.join(); }
  24530. }
  24531. std::unique_ptr<SSLServer> server_;
  24532. std::thread server_thread_;
  24533. int port_ = 0;
  24534. };
  24535. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24536. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24537. {
  24538. ws::WebSocketClient client(url);
  24539. client.enable_server_certificate_verification(false);
  24540. auto calls = 0;
  24541. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24542. calls++;
  24543. return false;
  24544. });
  24545. EXPECT_FALSE(client.connect());
  24546. EXPECT_GT(calls, 0);
  24547. }
  24548. {
  24549. ws::WebSocketClient client(url);
  24550. client.enable_server_certificate_verification(false);
  24551. client.set_session_verifier([](tls::session_t) {
  24552. return SSLVerifierResponse::CertificateRejected;
  24553. });
  24554. EXPECT_FALSE(client.connect());
  24555. }
  24556. {
  24557. ws::WebSocketClient client(url);
  24558. client.enable_server_certificate_verification(false);
  24559. client.set_session_verifier([](tls::session_t) {
  24560. return SSLVerifierResponse::CertificateAccepted;
  24561. });
  24562. EXPECT_TRUE(client.connect());
  24563. }
  24564. }
  24565. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24566. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24567. "/ws-echo");
  24568. client.enable_server_certificate_verification(false);
  24569. ASSERT_TRUE(client.connect());
  24570. ASSERT_TRUE(client.is_open());
  24571. ASSERT_TRUE(client.send("Hello WSS"));
  24572. std::string msg;
  24573. EXPECT_EQ(ws::Text, client.read(msg));
  24574. EXPECT_EQ("Hello WSS", msg);
  24575. client.close();
  24576. }
  24577. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24578. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24579. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24580. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24581. // client (without calling close() first) is the only path that runs
  24582. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24583. // bug exactly.
  24584. //
  24585. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24586. // when linked against an instrumented libssl; run under Valgrind to catch it
  24587. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24588. // suite (the freed session otherwise stalls on the close handshake) — this test
  24589. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24590. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24591. {
  24592. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24593. "/ws-echo");
  24594. client.enable_server_certificate_verification(false);
  24595. client.set_read_timeout(2, 0);
  24596. client.set_write_timeout(2, 0);
  24597. ASSERT_TRUE(client.connect());
  24598. ASSERT_TRUE(client.is_open());
  24599. ASSERT_TRUE(client.send("still open"));
  24600. // Intentionally do NOT call client.close(): leaving scope runs
  24601. // shutdown_and_close() with the WebSocket still open, which must send the
  24602. // close frame while the TLS session is still alive.
  24603. }
  24604. }
  24605. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24606. // shutdown_and_close() at the start of connect(), reproducing the same
  24607. // use-after-free within the test body rather than at scope exit. The second
  24608. // connect must succeed and echo, proving the close handshake ran over a live
  24609. // session. See the note above about memory-tool requirements.
  24610. TEST_F(WebSocketSSLIntegrationTest,
  24611. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24612. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24613. "/ws-echo");
  24614. client.enable_server_certificate_verification(false);
  24615. client.set_read_timeout(2, 0);
  24616. client.set_write_timeout(2, 0);
  24617. ASSERT_TRUE(client.connect());
  24618. ASSERT_TRUE(client.is_open());
  24619. ASSERT_TRUE(client.send("still open"));
  24620. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24621. // the still-open connection, which must not touch a freed TLS session.
  24622. ASSERT_TRUE(client.connect());
  24623. ASSERT_TRUE(client.is_open());
  24624. ASSERT_TRUE(client.send("after reconnect"));
  24625. std::string msg;
  24626. EXPECT_EQ(ws::Text, client.read(msg));
  24627. EXPECT_EQ("after reconnect", msg);
  24628. client.close();
  24629. }
  24630. #endif
  24631. #ifdef CPPHTTPLIB_SSL_ENABLED
  24632. class WebSocketSSLCATest : public ::testing::Test {
  24633. protected:
  24634. void SetUp() override {
  24635. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24636. SERVER_PRIVATE_KEY_FILE);
  24637. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24638. std::string msg;
  24639. while (ws.read(msg)) {
  24640. ws.send(msg);
  24641. }
  24642. });
  24643. port_ = server_->bind_to_any_port("127.0.0.1");
  24644. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24645. server_->wait_until_ready();
  24646. }
  24647. void TearDown() override {
  24648. server_->stop();
  24649. if (server_thread_.joinable()) { server_thread_.join(); }
  24650. }
  24651. std::string url() const {
  24652. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24653. }
  24654. std::unique_ptr<SSLServer> server_;
  24655. std::thread server_thread_;
  24656. int port_ = 0;
  24657. };
  24658. // A custom CA loaded as PEM verifies the server with full certificate
  24659. // verification enabled
  24660. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24661. ws::WebSocketClient client(url());
  24662. std::string cert;
  24663. read_file(SERVER_CERT2_FILE, cert);
  24664. client.load_ca_cert_store(cert.c_str(), cert.size());
  24665. ASSERT_TRUE(client.connect());
  24666. ASSERT_TRUE(client.send("hello"));
  24667. std::string msg;
  24668. EXPECT_EQ(ws::Text, client.read(msg));
  24669. EXPECT_EQ("hello", msg);
  24670. client.close();
  24671. }
  24672. // A custom CA that does not cover the server must fail verification (the
  24673. // custom CA is exclusive; system certs are not loaded alongside it)
  24674. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24675. ws::WebSocketClient client(url());
  24676. std::string cert;
  24677. read_file(CLIENT_CA_CERT_FILE, cert);
  24678. client.load_ca_cert_store(cert.c_str(), cert.size());
  24679. auto res = client.connect();
  24680. ASSERT_FALSE(res);
  24681. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24682. EXPECT_EQ(-1, res.status());
  24683. EXPECT_NE(0u, res.ssl_backend_error());
  24684. }
  24685. // The same CA as a file path rather than PEM in memory
  24686. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24687. ws::WebSocketClient client(url());
  24688. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24689. ASSERT_TRUE(client.connect());
  24690. ASSERT_TRUE(client.send("hello"));
  24691. std::string msg;
  24692. EXPECT_EQ(ws::Text, client.read(msg));
  24693. EXPECT_EQ("hello", msg);
  24694. client.close();
  24695. }
  24696. // ...and a CA file that does not cover the server still fails, so it is the
  24697. // path above that decides the outcome
  24698. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24699. ws::WebSocketClient client(url());
  24700. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24701. ASSERT_FALSE(client.connect());
  24702. }
  24703. // Regression test: reconnecting with a native custom CA store used to reuse
  24704. // a store handle the previous TLS context had already freed (use-after-free
  24705. // under the OpenSSL backend). The context now lives as long as the client.
  24706. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24707. ws::WebSocketClient client(url());
  24708. std::string cert;
  24709. read_file(SERVER_CERT2_FILE, cert);
  24710. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24711. ASSERT_TRUE(client.connect());
  24712. client.close();
  24713. ASSERT_TRUE(client.connect());
  24714. ASSERT_TRUE(client.send("again"));
  24715. std::string msg;
  24716. EXPECT_EQ(ws::Text, client.read(msg));
  24717. EXPECT_EQ("again", msg);
  24718. client.close();
  24719. }
  24720. // Regression test: a certificate with a trusted chain but no identity match
  24721. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24722. // verification entirely for IP hosts, so this connection succeeded there.
  24723. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24724. // chain verification while the identity check must still fail.
  24725. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24726. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24727. ASSERT_TRUE(svr.is_valid());
  24728. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24729. std::string msg;
  24730. while (ws.read(msg)) {
  24731. ws.send(msg);
  24732. }
  24733. });
  24734. auto port = svr.bind_to_any_port("127.0.0.1");
  24735. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24736. auto se = detail::scope_exit([&] {
  24737. svr.stop();
  24738. t.join();
  24739. });
  24740. svr.wait_until_ready();
  24741. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24742. "/echo");
  24743. std::string cert;
  24744. read_file(SERVER_CERT_FILE, cert);
  24745. client.load_ca_cert_store(cert.c_str(), cert.size());
  24746. ASSERT_FALSE(client.connect());
  24747. }
  24748. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24749. // SNI, so nothing binds the host name to the TLS session. These bind the
  24750. // server to "localhost" instead, the only shape that exercises the SNI and
  24751. // hostname-verification path with certificate verification left enabled.
  24752. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24753. protected:
  24754. void Start(const char *cert_file) {
  24755. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24756. SERVER_PRIVATE_KEY_FILE);
  24757. ASSERT_TRUE(server_->is_valid());
  24758. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24759. std::string msg;
  24760. while (ws.read(msg)) {
  24761. ws.send(msg);
  24762. }
  24763. });
  24764. port_ = server_->bind_to_any_port("localhost");
  24765. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24766. server_->wait_until_ready();
  24767. }
  24768. void TearDown() override {
  24769. if (server_) { server_->stop(); }
  24770. if (server_thread_.joinable()) { server_thread_.join(); }
  24771. }
  24772. std::string url() const {
  24773. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24774. }
  24775. std::unique_ptr<SSLServer> server_;
  24776. std::thread server_thread_;
  24777. int port_ = 0;
  24778. };
  24779. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24780. // out and the connection is usable
  24781. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24782. Start(SERVER_CERT2_FILE);
  24783. ws::WebSocketClient client(url());
  24784. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24785. ASSERT_TRUE(client.connect());
  24786. ASSERT_TRUE(client.send("hello"));
  24787. std::string msg;
  24788. EXPECT_EQ(ws::Text, client.read(msg));
  24789. EXPECT_EQ("hello", msg);
  24790. client.close();
  24791. }
  24792. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24793. // while the identity check must still reject "localhost"
  24794. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24795. Start(SERVER_CERT_FILE);
  24796. ws::WebSocketClient client(url());
  24797. client.set_ca_cert_path(SERVER_CERT_FILE);
  24798. auto res = client.connect();
  24799. ASSERT_FALSE(res);
  24800. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24801. EXPECT_EQ(-1, res.status());
  24802. }
  24803. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24804. // disabled: the chain is still checked, only the identity check is skipped
  24805. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24806. Start(SERVER_CERT_FILE);
  24807. ws::WebSocketClient client(url());
  24808. client.set_ca_cert_path(SERVER_CERT_FILE);
  24809. client.enable_server_hostname_verification(false);
  24810. ASSERT_TRUE(client.connect());
  24811. ASSERT_TRUE(client.send("hello"));
  24812. std::string msg;
  24813. EXPECT_EQ(ws::Text, client.read(msg));
  24814. EXPECT_EQ("hello", msg);
  24815. client.close();
  24816. }
  24817. // A CA that did not sign the server certificate fails the chain, even though
  24818. // the name would match
  24819. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24820. Start(SERVER_CERT2_FILE);
  24821. ws::WebSocketClient client(url());
  24822. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24823. ASSERT_FALSE(client.connect());
  24824. }
  24825. // With verification disabled, neither the chain nor the name is checked
  24826. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24827. Start(SERVER_CERT_FILE);
  24828. ws::WebSocketClient client(url());
  24829. client.enable_server_certificate_verification(false);
  24830. ASSERT_TRUE(client.connect());
  24831. ASSERT_TRUE(client.send("hello"));
  24832. std::string msg;
  24833. EXPECT_EQ(ws::Text, client.read(msg));
  24834. EXPECT_EQ("hello", msg);
  24835. client.close();
  24836. }
  24837. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24838. protected:
  24839. void SetUp() override {
  24840. server_ = httplib::detail::make_unique<SSLServer>(
  24841. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24842. ASSERT_TRUE(server_->is_valid());
  24843. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24844. std::string msg;
  24845. while (ws.read(msg)) {
  24846. ws.send(msg);
  24847. }
  24848. });
  24849. port_ = server_->bind_to_any_port("localhost");
  24850. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24851. server_->wait_until_ready();
  24852. }
  24853. void TearDown() override {
  24854. server_->stop();
  24855. if (server_thread_.joinable()) { server_thread_.join(); }
  24856. }
  24857. std::string url() const {
  24858. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24859. }
  24860. void ConnectWithClientCert(const std::string &client_cert_file,
  24861. const std::string &client_private_key_file,
  24862. const char *private_key_password) {
  24863. std::string cert_pem, key_pem;
  24864. read_file(client_cert_file, cert_pem);
  24865. read_file(client_private_key_file, key_pem);
  24866. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24867. key_pem.c_str(), key_pem.size(),
  24868. private_key_password};
  24869. ConnectWithPem(pem);
  24870. }
  24871. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24872. ws::WebSocketClient client(url(), pem);
  24873. ASSERT_TRUE(client.is_valid());
  24874. client.enable_server_certificate_verification(false);
  24875. ASSERT_TRUE(client.connect());
  24876. ASSERT_TRUE(client.send("hello"));
  24877. std::string msg;
  24878. EXPECT_EQ(ws::Text, client.read(msg));
  24879. EXPECT_EQ("hello", msg);
  24880. client.close();
  24881. }
  24882. std::unique_ptr<SSLServer> server_;
  24883. std::thread server_thread_;
  24884. int port_ = 0;
  24885. };
  24886. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24887. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24888. }
  24889. // Control for the tests above: the fixture's server really does require a
  24890. // client certificate, so it is the PEM the constructor installed that decides
  24891. // the outcome.
  24892. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24893. ws::WebSocketClient client(url());
  24894. ASSERT_TRUE(client.is_valid());
  24895. client.enable_server_certificate_verification(false);
  24896. EXPECT_FALSE(client.connect());
  24897. }
  24898. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24899. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24900. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24901. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24902. }
  24903. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24904. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24905. std::string cert_pem, key_pem;
  24906. read_file(CLIENT_CERT_FILE, cert_pem);
  24907. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24908. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24909. std::vector<char> key(key_pem.begin(), key_pem.end());
  24910. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24911. key.size(), nullptr};
  24912. ConnectWithPem(pem);
  24913. }
  24914. #endif
  24915. #if !defined(_WIN32)
  24916. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24917. auto secret_dir = std::string("./symlink_test_secret");
  24918. auto served_dir = std::string("./symlink_test_served");
  24919. auto secret_file = secret_dir + "/secret.txt";
  24920. auto symlink_path = served_dir + "/escape";
  24921. // Setup: create directories and files
  24922. mkdir(secret_dir.c_str(), 0755);
  24923. mkdir(served_dir.c_str(), 0755);
  24924. {
  24925. std::ofstream ofs(secret_file);
  24926. ofs << "SECRET_DATA";
  24927. }
  24928. // Create symlink using absolute path so it resolves correctly
  24929. #ifdef PATH_MAX
  24930. char abs_secret[PATH_MAX];
  24931. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24932. #else
  24933. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24934. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24935. ASSERT_NE(nullptr, abs_secret);
  24936. #endif
  24937. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24938. auto se = detail::scope_exit([&] {
  24939. unlink(symlink_path.c_str());
  24940. unlink(secret_file.c_str());
  24941. rmdir(served_dir.c_str());
  24942. rmdir(secret_dir.c_str());
  24943. });
  24944. Server svr;
  24945. svr.set_mount_point("/", served_dir);
  24946. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24947. auto se2 = detail::scope_exit([&] {
  24948. svr.stop();
  24949. listen_thread.join();
  24950. });
  24951. svr.wait_until_ready();
  24952. Client cli("localhost", PORT);
  24953. // Symlink pointing outside base dir should be blocked
  24954. auto res = cli.Get("/escape/secret.txt");
  24955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24956. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24957. }
  24958. #endif
  24959. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24960. // "GET /smuggled" request), reads the first response, and only then sends the
  24961. // embedded request as the body. Returns how many times /smuggled ran.
  24962. //
  24963. // The body is sent AFTER receiving the first response (as in the original
  24964. // PoC) so that the stream_line_reader cannot buffer it together with the
  24965. // headers of the first request.
  24966. static int count_smuggled_requests(const std::string &outer_head,
  24967. std::string &first_response) {
  24968. Server svr;
  24969. svr.set_mount_point("/", "./www");
  24970. std::atomic<int> smuggled_count(0);
  24971. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24972. smuggled_count++;
  24973. res.set_content("oops", "text/plain");
  24974. });
  24975. svr.Post("/post", [&](const Request &req, Response &res) {
  24976. res.set_content(req.body, "text/plain");
  24977. });
  24978. auto port = svr.bind_to_any_port("localhost");
  24979. thread t = thread([&] { svr.listen_after_bind(); });
  24980. auto se = detail::scope_exit([&] {
  24981. svr.stop();
  24982. t.join();
  24983. });
  24984. svr.wait_until_ready();
  24985. auto error = Error::Success;
  24986. auto sock = detail::create_client_socket(
  24987. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24988. /*connection_timeout_sec=*/2, 0,
  24989. /*read_timeout_sec=*/2, 0,
  24990. /*write_timeout_sec=*/2, 0, std::string(), error);
  24991. EXPECT_NE(INVALID_SOCKET, sock);
  24992. if (sock == INVALID_SOCKET) { return -1; }
  24993. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24994. // The "smuggled" request will be sent as the body of the outer request
  24995. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24996. "Host: localhost\r\n"
  24997. "Connection: close\r\n"
  24998. "\r\n";
  24999. auto head = outer_head;
  25000. auto len = std::to_string(smuggled.size());
  25001. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25002. pos = head.find("{len}", pos + len.size())) {
  25003. head.replace(pos, 5, len);
  25004. }
  25005. // Step 1: Send only the outer request headers (no body yet)
  25006. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25007. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25008. // Step 2: Read the first response
  25009. char buf[4096];
  25010. for (;;) {
  25011. auto n = recv(sock, buf, sizeof(buf), 0);
  25012. if (n <= 0) break;
  25013. first_response.append(buf, static_cast<size_t>(n));
  25014. // Stop once we have a complete response (headers + body)
  25015. auto hdr_end = first_response.find("\r\n\r\n");
  25016. if (hdr_end != std::string::npos) {
  25017. // Check for Content-Length to know when the body is complete
  25018. auto cl_pos = first_response.find("Content-Length:");
  25019. if (cl_pos != std::string::npos) {
  25020. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25021. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25022. auto cl = std::stoul(
  25023. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25024. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25025. } else {
  25026. break; // No Content-Length, assume headers-only response
  25027. }
  25028. }
  25029. }
  25030. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25031. // vulnerable server the keep-alive loop reads this as a second request. The
  25032. // server may already have closed the connection, so the result is ignored.
  25033. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25034. // Half-close so that a server which drained the body sees EOF and closes,
  25035. // instead of the read below waiting for the read timeout.
  25036. #ifdef _WIN32
  25037. ::shutdown(sock, SD_SEND);
  25038. #else
  25039. ::shutdown(sock, SHUT_WR);
  25040. #endif
  25041. // Step 4: Read until the server closes the connection
  25042. for (;;) {
  25043. auto n = recv(sock, buf, sizeof(buf), 0);
  25044. if (n <= 0) break;
  25045. }
  25046. return smuggled_count.load();
  25047. }
  25048. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25049. // A GET request with Content-Length to a static file handler must have its
  25050. // body drained before the keep-alive connection is reused. Otherwise the
  25051. // unread body bytes are interpreted as the next HTTP request.
  25052. std::string first_response;
  25053. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25054. "Host: localhost\r\n"
  25055. "Content-Length: {len}\r\n"
  25056. "\r\n",
  25057. first_response));
  25058. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25059. }
  25060. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25061. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25062. // be answered with 400 and the connection closed. Treating it as "no body"
  25063. // leaves the body to be parsed as the next request.
  25064. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25065. const char *targets[] = {
  25066. "GET /file", // handler that never reads the body
  25067. "GET /not-found", // no handler matches (404)
  25068. "POST /post", // handler that reads the body
  25069. };
  25070. for (auto target : targets) {
  25071. for (auto value : values) {
  25072. std::string first_response;
  25073. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25074. " HTTP/1.1\r\n"
  25075. "Host: localhost\r\n"
  25076. "Content-Length: " +
  25077. value + "\r\n\r\n",
  25078. first_response))
  25079. << target << " with Content-Length: " << value;
  25080. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25081. << target << " with Content-Length: " << value;
  25082. }
  25083. }
  25084. }
  25085. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25086. // A 400 for an unparseable request line leaves the rest of the message
  25087. // unread, so the connection must be closed rather than reused.
  25088. std::string first_response;
  25089. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25090. "Host: localhost\r\n"
  25091. "Content-Length: {len}\r\n"
  25092. "\r\n",
  25093. first_response));
  25094. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25095. }
  25096. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25097. // Same as above for a header block that fails to parse.
  25098. std::string first_response;
  25099. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25100. "Host: localhost\r\n"
  25101. "Bad Header\r\n"
  25102. "Content-Length: {len}\r\n"
  25103. "\r\n",
  25104. first_response));
  25105. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25106. }
  25107. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25108. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25109. // server must not read another request on that connection, even when the
  25110. // request had no body to drain.
  25111. std::string first_response;
  25112. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25113. "Host: localhost\r\n"
  25114. "\r\n",
  25115. first_response));
  25116. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25117. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25118. }
  25119. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25120. // A content reader that stops early leaves the stream inside the body.
  25121. // Draining the whole Content-Length from there, or reading the body again,
  25122. // reads into the next request, and whatever follows is parsed as a request
  25123. // of its own.
  25124. Server svr;
  25125. std::atomic<int> smuggled_count(0);
  25126. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25127. svr.Post("/upload", [](const Request &req, Response &res,
  25128. const ContentReader &content_reader) {
  25129. // Stop at the last chunk, so the whole body has been read however it
  25130. // arrives.
  25131. auto length = req.get_header_value_u64("Content-Length");
  25132. size_t total = 0;
  25133. auto consumed = content_reader([&](const char *, size_t n) {
  25134. total += n;
  25135. return total < length;
  25136. });
  25137. EXPECT_FALSE(consumed);
  25138. if (req.has_param("retry")) {
  25139. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25140. }
  25141. // Replace the 400 the aborted read set, which would close the connection.
  25142. res.set_redirect("/done");
  25143. });
  25144. auto port = svr.bind_to_any_port(HOST);
  25145. thread t = thread([&] { svr.listen_after_bind(); });
  25146. auto se = detail::scope_exit([&] {
  25147. svr.stop();
  25148. t.join();
  25149. });
  25150. svr.wait_until_ready();
  25151. // A front end sees the second request as a POST whose body is the GET. The
  25152. // first body is as long as the POST's headers, so draining it again reads
  25153. // exactly those and leaves the GET to be parsed next.
  25154. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25155. "Host: localhost\r\n"
  25156. "\r\n";
  25157. std::string second_head = "POST /post HTTP/1.1\r\n"
  25158. "Host: localhost\r\n"
  25159. "Content-Length: " +
  25160. std::to_string(inner.size()) +
  25161. "\r\n"
  25162. "\r\n";
  25163. for (auto target : {"/upload", "/upload?retry"}) {
  25164. smuggled_count = 0;
  25165. std::string request = "POST " + std::string(target) +
  25166. " HTTP/1.1\r\n"
  25167. "Host: localhost\r\n"
  25168. "Content-Length: " +
  25169. std::to_string(second_head.size()) +
  25170. "\r\n"
  25171. "\r\n" +
  25172. std::string(second_head.size(), 'A') + second_head +
  25173. inner;
  25174. std::string response;
  25175. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25176. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25177. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25178. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25179. EXPECT_EQ(0, smuggled_count.load()) << target;
  25180. }
  25181. }
  25182. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25183. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25184. // must be rejected with 400 Bad Request.
  25185. Server svr;
  25186. svr.Post("/test", [&](const Request &, Response &res) {
  25187. res.set_content("ok", "text/plain");
  25188. });
  25189. thread t = thread([&] { svr.listen(HOST, PORT); });
  25190. auto se = detail::scope_exit([&] {
  25191. svr.stop();
  25192. t.join();
  25193. ASSERT_FALSE(svr.is_running());
  25194. });
  25195. svr.wait_until_ready();
  25196. // Exact "chunked"
  25197. {
  25198. auto req = "POST /test HTTP/1.1\r\n"
  25199. "Host: localhost\r\n"
  25200. "Content-Length: 5\r\n"
  25201. "Transfer-Encoding: chunked\r\n"
  25202. "Connection: close\r\n"
  25203. "\r\n"
  25204. "hello";
  25205. std::string response;
  25206. ASSERT_TRUE(send_request(1, req, &response));
  25207. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25208. response.substr(0, response.find("\r\n")));
  25209. }
  25210. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25211. {
  25212. auto req = "POST /test HTTP/1.1\r\n"
  25213. "Host: localhost\r\n"
  25214. "Content-Length: 5\r\n"
  25215. "Transfer-Encoding: gzip, chunked\r\n"
  25216. "Connection: close\r\n"
  25217. "\r\n"
  25218. "hello";
  25219. std::string response;
  25220. ASSERT_TRUE(send_request(1, req, &response));
  25221. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25222. response.substr(0, response.find("\r\n")));
  25223. }
  25224. }
  25225. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25226. Server svr;
  25227. svr.Post("/test", [&](const Request &, Response &res) {
  25228. res.set_content("ok", "text/plain");
  25229. });
  25230. thread t = thread([&] { svr.listen(HOST, PORT); });
  25231. auto se = detail::scope_exit([&] {
  25232. svr.stop();
  25233. t.join();
  25234. ASSERT_FALSE(svr.is_running());
  25235. });
  25236. svr.wait_until_ready();
  25237. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25238. // length cannot be determined, so the server must answer 400 and close
  25239. // rather than treat the request as bodyless and leave the body in the
  25240. // socket for the next request to pick up.
  25241. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25242. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25243. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25244. std::string response;
  25245. ASSERT_TRUE(send_request(1, req, &response));
  25246. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25247. response.substr(0, response.find("\r\n")))
  25248. << transfer_encoding;
  25249. }
  25250. // RFC 9110 5.3: the codings may also be split across several
  25251. // Transfer-Encoding lines, which combine in the order they were received.
  25252. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25253. // just like the single-line "chunked, gzip" above.
  25254. {
  25255. auto req = "POST /test HTTP/1.1\r\n"
  25256. "Host: localhost\r\n"
  25257. "Transfer-Encoding: chunked\r\n"
  25258. "Transfer-Encoding: gzip\r\n"
  25259. "\r\n"
  25260. "0\r\n\r\n";
  25261. std::string response;
  25262. ASSERT_TRUE(send_request(1, req, &response));
  25263. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25264. response.substr(0, response.find("\r\n")));
  25265. }
  25266. }
  25267. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25268. Server svr;
  25269. svr.Post("/test", [&](const Request &, Response &res) {
  25270. res.set_content("ok", "text/plain");
  25271. });
  25272. auto port = svr.bind_to_any_port(HOST);
  25273. ASSERT_GT(port, 0);
  25274. thread t = thread([&] { svr.listen_after_bind(); });
  25275. auto se = detail::scope_exit([&] {
  25276. svr.stop();
  25277. t.join();
  25278. ASSERT_FALSE(svr.is_running());
  25279. });
  25280. svr.wait_until_ready();
  25281. for (auto transfer_encoding :
  25282. {"Transfer-Encoding: gzip, chunked\r\n",
  25283. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25284. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25285. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25286. transfer_encoding + "\r\n0\r\n\r\n";
  25287. std::string response;
  25288. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25289. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25290. response.substr(0, response.find("\r\n")))
  25291. << transfer_encoding;
  25292. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25293. << transfer_encoding;
  25294. }
  25295. }
  25296. // Regression for issue #2450: a DELETE without Content-Length on a
  25297. // keep-alive connection must not let the post-response drain consume the
  25298. // next request's bytes.
  25299. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25300. Server svr;
  25301. std::atomic<int> delete_count(0);
  25302. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25303. delete_count++;
  25304. res.status = StatusCode::NoContent_204;
  25305. });
  25306. auto port = svr.bind_to_any_port(HOST);
  25307. thread t = thread([&] { svr.listen_after_bind(); });
  25308. auto se = detail::scope_exit([&] {
  25309. svr.stop();
  25310. t.join();
  25311. });
  25312. svr.wait_until_ready();
  25313. auto error = Error::Success;
  25314. auto sock = detail::create_client_socket(
  25315. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25316. /*connection_timeout_sec=*/2, 0,
  25317. /*read_timeout_sec=*/2, 0,
  25318. /*write_timeout_sec=*/2, 0, std::string(), error);
  25319. ASSERT_NE(INVALID_SOCKET, sock);
  25320. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25321. auto send_request_and_read_response = [&](const std::string &req,
  25322. std::string &out) -> bool {
  25323. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25324. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25325. char buf[4096];
  25326. for (;;) {
  25327. auto n = recv(sock, buf, sizeof(buf), 0);
  25328. if (n <= 0) { return !out.empty(); }
  25329. out.append(buf, static_cast<size_t>(n));
  25330. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25331. }
  25332. };
  25333. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25334. "Host: localhost\r\n"
  25335. "\r\n";
  25336. std::string resp1;
  25337. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25338. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25339. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25340. "Host: localhost\r\n"
  25341. "Connection: close\r\n"
  25342. "\r\n";
  25343. std::string resp2;
  25344. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25345. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25346. EXPECT_EQ(2, delete_count.load());
  25347. }
  25348. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25349. Server svr;
  25350. svr.Post("/ingest", [&](const Request &, Response &res,
  25351. const ContentReader &content_reader) {
  25352. auto consumed = content_reader([](const char *, size_t) { return false; });
  25353. EXPECT_FALSE(consumed);
  25354. res.status = StatusCode::Conflict_409;
  25355. res.set_header("Connection", "close");
  25356. });
  25357. auto port = svr.bind_to_any_port(HOST);
  25358. thread t = thread([&] { svr.listen_after_bind(); });
  25359. auto se = detail::scope_exit([&] {
  25360. svr.stop();
  25361. t.join();
  25362. });
  25363. svr.wait_until_ready();
  25364. auto error = Error::Success;
  25365. auto sock = detail::create_client_socket(
  25366. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25367. /*connection_timeout_sec=*/2, 0,
  25368. /*read_timeout_sec=*/1, 0,
  25369. /*write_timeout_sec=*/2, 0, std::string(), error);
  25370. ASSERT_NE(INVALID_SOCKET, sock);
  25371. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25372. std::string request = "POST /ingest HTTP/1.1\r\n"
  25373. "Host: localhost\r\n"
  25374. "Transfer-Encoding: chunked\r\n"
  25375. "\r\n"
  25376. "4\r\n"
  25377. "data\r\n";
  25378. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25379. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25380. std::string response;
  25381. ssize_t received = 0;
  25382. do {
  25383. char buf[4096];
  25384. received = recv(sock, buf, sizeof(buf), 0);
  25385. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25386. } while (received > 0);
  25387. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25388. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25389. EXPECT_EQ(0, received);
  25390. }
  25391. namespace no_proxy_test {
  25392. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25393. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25394. // calling listen().
  25395. class ScopedServer {
  25396. public:
  25397. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25398. ~ScopedServer() {
  25399. svr_.stop();
  25400. if (th_.joinable()) { th_.join(); }
  25401. }
  25402. Server &svr() { return svr_; }
  25403. int port() const { return port_; }
  25404. void listen() {
  25405. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25406. svr_.wait_until_ready();
  25407. }
  25408. private:
  25409. Server svr_;
  25410. std::thread th_;
  25411. int port_ = 0;
  25412. };
  25413. class ProxyAndTargetServers {
  25414. public:
  25415. ProxyAndTargetServers() {
  25416. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25417. proxy_hits_++;
  25418. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25419. res.set_content("via-proxy", "text/plain");
  25420. });
  25421. target_.Get(".*", [this](const Request &req, Response &res) {
  25422. target_hits_++;
  25423. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25424. res.set_content("direct", "text/plain");
  25425. });
  25426. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25427. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25428. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25429. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25430. proxy_mock_.wait_until_ready();
  25431. target_.wait_until_ready();
  25432. }
  25433. ~ProxyAndTargetServers() {
  25434. proxy_mock_.stop();
  25435. target_.stop();
  25436. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25437. if (target_thread_.joinable()) { target_thread_.join(); }
  25438. }
  25439. Server &proxy_mock() { return proxy_mock_; }
  25440. Server &target() { return target_; }
  25441. int proxy_port() const { return proxy_port_; }
  25442. int target_port() const { return target_port_; }
  25443. int proxy_hits() const { return proxy_hits_.load(); }
  25444. int target_hits() const { return target_hits_.load(); }
  25445. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25446. void reset_counters() {
  25447. proxy_hits_ = 0;
  25448. target_hits_ = 0;
  25449. last_had_proxy_authz_ = false;
  25450. }
  25451. private:
  25452. Server proxy_mock_;
  25453. Server target_;
  25454. std::thread proxy_thread_;
  25455. std::thread target_thread_;
  25456. int proxy_port_ = 0;
  25457. int target_port_ = 0;
  25458. std::atomic<int> proxy_hits_{0};
  25459. std::atomic<int> target_hits_{0};
  25460. std::atomic<bool> last_had_proxy_authz_{false};
  25461. };
  25462. inline std::unique_ptr<Client> make_client(const std::string &host,
  25463. ProxyAndTargetServers &s) {
  25464. auto cli = detail::make_unique<Client>(host, s.target_port());
  25465. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25466. cli->set_proxy("127.0.0.1", s.proxy_port());
  25467. return cli;
  25468. }
  25469. } // namespace no_proxy_test
  25470. using no_proxy_test::make_client;
  25471. using no_proxy_test::ProxyAndTargetServers;
  25472. // A stream request carries the credentials a buffered request does
  25473. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25474. no_proxy_test::ScopedServer origin;
  25475. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25476. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25477. });
  25478. origin.listen();
  25479. Client cli("127.0.0.1", origin.port());
  25480. cli.set_basic_auth("user", "pass");
  25481. auto handle = cli.open_stream("GET", "/x");
  25482. ASSERT_TRUE(handle.is_valid());
  25483. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25484. Client bearer("127.0.0.1", origin.port());
  25485. bearer.set_bearer_token_auth("tok");
  25486. auto handle2 = bearer.open_stream("GET", "/x");
  25487. ASSERT_TRUE(handle2.is_valid());
  25488. EXPECT_EQ("Bearer tok", read_all(handle2));
  25489. }
  25490. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25491. // takes its own credentials, as for a buffered request
  25492. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25493. std::string target, authz, proxy_authz;
  25494. no_proxy_test::ScopedServer proxy;
  25495. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25496. target = req.target;
  25497. authz = req.get_header_value("Authorization");
  25498. proxy_authz = req.get_header_value("Proxy-Authorization");
  25499. res.set_content("ok", "text/plain");
  25500. });
  25501. proxy.listen();
  25502. Client cli("origin.example", 8080);
  25503. cli.set_proxy("127.0.0.1", proxy.port());
  25504. cli.set_proxy_basic_auth("puser", "ppass");
  25505. cli.set_basic_auth("user", "pass");
  25506. auto handle = cli.open_stream("GET", "/x");
  25507. ASSERT_TRUE(handle.is_valid());
  25508. EXPECT_EQ("ok", read_all(handle));
  25509. EXPECT_EQ("http://origin.example:8080/x", target);
  25510. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25511. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25512. }
  25513. TEST(NoProxyTest, ExactHostnameBypasses) {
  25514. ProxyAndTargetServers s;
  25515. auto cli = make_client("example.com", s);
  25516. cli->set_no_proxy({"example.com"});
  25517. auto res = cli->Get("/");
  25518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25519. EXPECT_EQ(0, s.proxy_hits());
  25520. EXPECT_EQ(1, s.target_hits());
  25521. }
  25522. TEST(NoProxyTest, SubdomainBypasses) {
  25523. ProxyAndTargetServers s;
  25524. auto cli = make_client("foo.example.com", s);
  25525. cli->set_no_proxy({"example.com"});
  25526. auto res = cli->Get("/");
  25527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25528. EXPECT_EQ(0, s.proxy_hits());
  25529. EXPECT_EQ(1, s.target_hits());
  25530. }
  25531. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25532. // Regression guard: "evilexample.com" must not be considered a subdomain
  25533. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25534. // check would let traffic bypass the proxy and leak credentials direct
  25535. // to the attacker host.
  25536. ProxyAndTargetServers s;
  25537. auto cli = make_client("evilexample.com", s);
  25538. cli->set_no_proxy({"example.com"});
  25539. auto res = cli->Get("/");
  25540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25541. EXPECT_GE(s.proxy_hits(), 1);
  25542. EXPECT_EQ(0, s.target_hits());
  25543. }
  25544. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25545. ProxyAndTargetServers s;
  25546. auto cli = make_client("example.com.evil.com", s);
  25547. cli->set_no_proxy({"example.com"});
  25548. auto res = cli->Get("/");
  25549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25550. EXPECT_GE(s.proxy_hits(), 1);
  25551. EXPECT_EQ(0, s.target_hits());
  25552. }
  25553. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25554. ProxyAndTargetServers s;
  25555. auto cli = make_client("example.com", s);
  25556. cli->set_no_proxy({".example.com"});
  25557. auto res = cli->Get("/");
  25558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25559. EXPECT_EQ(0, s.proxy_hits());
  25560. EXPECT_EQ(1, s.target_hits());
  25561. }
  25562. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25563. ProxyAndTargetServers s;
  25564. auto cli = make_client("Example.COM", s);
  25565. cli->set_no_proxy({"EXAMPLE.com"});
  25566. auto res = cli->Get("/");
  25567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25568. EXPECT_EQ(0, s.proxy_hits());
  25569. EXPECT_EQ(1, s.target_hits());
  25570. }
  25571. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25572. ProxyAndTargetServers s;
  25573. auto cli = make_client("example.com.", s);
  25574. cli->set_no_proxy({"example.com"});
  25575. auto res = cli->Get("/");
  25576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25577. EXPECT_EQ(0, s.proxy_hits());
  25578. EXPECT_EQ(1, s.target_hits());
  25579. }
  25580. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25581. // Trailing dots must be normalized on BOTH sides — host and entry.
  25582. // An implementation that only strips the host-side trailing dot would
  25583. // fail to match host "example.com" against entry "example.com." because
  25584. // a literal substring search would compare 11 chars against 12.
  25585. ProxyAndTargetServers s;
  25586. auto cli = make_client("example.com", s);
  25587. cli->set_no_proxy({"example.com."});
  25588. auto res = cli->Get("/");
  25589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25590. EXPECT_EQ(0, s.proxy_hits());
  25591. EXPECT_EQ(1, s.target_hits());
  25592. }
  25593. TEST(NoProxyTest, WildcardBypassesEverything) {
  25594. ProxyAndTargetServers s;
  25595. auto cli = make_client("anything.invalid.test", s);
  25596. cli->set_no_proxy({"*"});
  25597. auto res = cli->Get("/");
  25598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25599. EXPECT_EQ(0, s.proxy_hits());
  25600. EXPECT_EQ(1, s.target_hits());
  25601. }
  25602. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  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({"127.0.0.1"});
  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, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25613. ProxyAndTargetServers s;
  25614. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25615. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25616. cli.set_proxy("127.0.0.1", s.proxy_port());
  25617. cli.set_no_proxy({"::1"});
  25618. auto res = cli.Get("/");
  25619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25620. EXPECT_EQ(0, s.proxy_hits());
  25621. EXPECT_EQ(1, s.target_hits());
  25622. }
  25623. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25624. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25625. // must still be recognized as IPv6 for CIDR matching. Implementations
  25626. // that detect IPv6 only when the host begins with '[' would parse the
  25627. // host as a hostname and miss the match.
  25628. ProxyAndTargetServers s;
  25629. Client cli("fe80::1", s.target_port());
  25630. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25631. cli.set_proxy("127.0.0.1", s.proxy_port());
  25632. cli.set_no_proxy({"fe80::/10"});
  25633. auto res = cli.Get("/");
  25634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25635. EXPECT_EQ(0, s.proxy_hits());
  25636. EXPECT_EQ(1, s.target_hits());
  25637. }
  25638. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25639. ProxyAndTargetServers s;
  25640. Client cli("::1", s.target_port());
  25641. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25642. cli.set_proxy("127.0.0.1", s.proxy_port());
  25643. cli.set_no_proxy({"[::1]"});
  25644. auto res = cli.Get("/");
  25645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25646. EXPECT_EQ(0, s.proxy_hits());
  25647. EXPECT_EQ(1, s.target_hits());
  25648. }
  25649. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25650. ProxyAndTargetServers s;
  25651. Client cli("fe80::1", s.target_port());
  25652. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25653. cli.set_proxy("127.0.0.1", s.proxy_port());
  25654. cli.set_no_proxy({"[fe80::]/10"});
  25655. auto res = cli.Get("/");
  25656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25657. EXPECT_EQ(0, s.proxy_hits());
  25658. EXPECT_EQ(1, s.target_hits());
  25659. }
  25660. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25661. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25662. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25663. // tricks via address-family conversion.
  25664. ProxyAndTargetServers s;
  25665. Client cli("::ffff:127.0.0.1", s.target_port());
  25666. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25667. cli.set_proxy("127.0.0.1", s.proxy_port());
  25668. cli.set_no_proxy({"127.0.0.1"});
  25669. auto res = cli.Get("/");
  25670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25671. EXPECT_GE(s.proxy_hits(), 1);
  25672. EXPECT_EQ(0, s.target_hits());
  25673. }
  25674. TEST(NoProxyTest, IPv4CidrMatch) {
  25675. ProxyAndTargetServers s;
  25676. Client cli("127.0.0.1", s.target_port());
  25677. cli.set_proxy("127.0.0.1", s.proxy_port());
  25678. cli.set_no_proxy({"127.0.0.0/8"});
  25679. auto res = cli.Get("/");
  25680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25681. EXPECT_EQ(0, s.proxy_hits());
  25682. EXPECT_EQ(1, s.target_hits());
  25683. }
  25684. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25685. ProxyAndTargetServers s;
  25686. Client cli("127.0.0.1", s.target_port());
  25687. cli.set_proxy("127.0.0.1", s.proxy_port());
  25688. cli.set_no_proxy({"10.0.0.0/8"});
  25689. auto res = cli.Get("/");
  25690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25691. EXPECT_GE(s.proxy_hits(), 1);
  25692. EXPECT_EQ(0, s.target_hits());
  25693. }
  25694. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25695. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25696. // IPv4 target matches.
  25697. ProxyAndTargetServers s;
  25698. Client cli("127.0.0.1", s.target_port());
  25699. cli.set_proxy("127.0.0.1", s.proxy_port());
  25700. cli.set_no_proxy({"0.0.0.0/0"});
  25701. auto res = cli.Get("/");
  25702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25703. EXPECT_EQ(0, s.proxy_hits());
  25704. EXPECT_EQ(1, s.target_hits());
  25705. }
  25706. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25707. ProxyAndTargetServers s;
  25708. Client cli("127.0.0.1", s.target_port());
  25709. cli.set_proxy("127.0.0.1", s.proxy_port());
  25710. cli.set_no_proxy({"127.0.0.1"});
  25711. auto res = cli.Get("/");
  25712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25713. EXPECT_EQ(0, s.proxy_hits());
  25714. EXPECT_EQ(1, s.target_hits());
  25715. }
  25716. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25717. ProxyAndTargetServers s;
  25718. Client cli("127.0.0.1", s.target_port());
  25719. cli.set_proxy("127.0.0.1", s.proxy_port());
  25720. cli.set_no_proxy({"127.0.0.0/33"});
  25721. auto res = cli.Get("/");
  25722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25723. EXPECT_GE(s.proxy_hits(), 1);
  25724. EXPECT_EQ(0, s.target_hits());
  25725. }
  25726. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25727. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25728. ProxyAndTargetServers s;
  25729. Client cli("127.0.0.1", s.target_port());
  25730. cli.set_proxy("127.0.0.1", s.proxy_port());
  25731. cli.set_no_proxy({"127.0.0.1/"});
  25732. auto res = cli.Get("/");
  25733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25734. EXPECT_GE(s.proxy_hits(), 1);
  25735. EXPECT_EQ(0, s.target_hits());
  25736. }
  25737. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25738. ProxyAndTargetServers s;
  25739. auto cli = make_client("internal.corp", s);
  25740. cli->set_proxy_basic_auth("u", "p");
  25741. cli->set_no_proxy({"internal.corp"});
  25742. auto res = cli->Get("/");
  25743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25744. EXPECT_EQ(1, s.target_hits());
  25745. EXPECT_EQ(0, s.proxy_hits());
  25746. EXPECT_FALSE(s.last_had_proxy_authz())
  25747. << "Proxy-Authorization must not be sent direct to the target";
  25748. }
  25749. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25750. ProxyAndTargetServers s;
  25751. auto cli = make_client("public.example", s);
  25752. cli->set_proxy_basic_auth("u", "p");
  25753. cli->set_no_proxy({"internal.corp"}); // does not match
  25754. auto res = cli->Get("/");
  25755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25756. EXPECT_GE(s.proxy_hits(), 1);
  25757. EXPECT_TRUE(s.last_had_proxy_authz());
  25758. }
  25759. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25760. std::atomic<int> hits{0};
  25761. std::atomic<int> hits_with_authz{0};
  25762. no_proxy_test::ScopedServer proxy_mock;
  25763. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25764. hits++;
  25765. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25766. if (req.target.find("/redir") != std::string::npos) {
  25767. res.set_redirect("http://other.example/landed");
  25768. } else {
  25769. res.set_content("via-proxy", "text/plain");
  25770. }
  25771. });
  25772. proxy_mock.listen();
  25773. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25774. hits = 0;
  25775. hits_with_authz = 0;
  25776. Client cli("public.example", 80);
  25777. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25778. cli.set_proxy_basic_auth(c.first, c.second);
  25779. cli.set_follow_location(true);
  25780. // The redirect to another host goes through the proxy as well
  25781. auto res = cli.Get("/redir");
  25782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25783. EXPECT_EQ(2, hits.load());
  25784. EXPECT_EQ(2, hits_with_authz.load());
  25785. }
  25786. }
  25787. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25788. ProxyAndTargetServers s;
  25789. auto cli = make_client("anything.test", s);
  25790. auto res = cli->Get("/");
  25791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25792. EXPECT_GE(s.proxy_hits(), 1);
  25793. EXPECT_EQ(0, s.target_hits());
  25794. }
  25795. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25796. ProxyAndTargetServers s;
  25797. auto cli = make_client("example.com", s);
  25798. cli->set_no_proxy({"example.com:8080"});
  25799. auto res = cli->Get("/");
  25800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25801. EXPECT_GE(s.proxy_hits(), 1);
  25802. EXPECT_EQ(0, s.target_hits());
  25803. }
  25804. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25805. ProxyAndTargetServers s;
  25806. auto cli = make_client("anything.test", s);
  25807. cli->set_no_proxy({"", " ", "\t"});
  25808. auto res = cli->Get("/");
  25809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25810. EXPECT_GE(s.proxy_hits(), 1);
  25811. EXPECT_EQ(0, s.target_hits());
  25812. }
  25813. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25814. // An entry with leading/trailing whitespace must still match — env-style
  25815. // values are commonly pasted with stray spaces and an implementation
  25816. // that feeds the raw token directly to inet_pton would fail to match
  25817. // valid CIDRs because of the spaces.
  25818. ProxyAndTargetServers s;
  25819. Client cli("127.0.0.1", s.target_port());
  25820. cli.set_proxy("127.0.0.1", s.proxy_port());
  25821. cli.set_no_proxy({" 127.0.0.0/8 "});
  25822. auto res = cli.Get("/");
  25823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25824. EXPECT_EQ(0, s.proxy_hits());
  25825. EXPECT_EQ(1, s.target_hits());
  25826. }
  25827. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25828. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25829. // go direct and must NOT carry Proxy-Authorization.
  25830. std::atomic<int> proxy_hits{0};
  25831. std::atomic<int> target_hits{0};
  25832. std::atomic<bool> target_saw_authz{false};
  25833. no_proxy_test::ScopedServer proxy_mock, target;
  25834. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25835. proxy_hits++;
  25836. res.status = 302;
  25837. res.set_header("Location", "http://127.0.0.1:" +
  25838. std::to_string(target.port()) + "/landed");
  25839. });
  25840. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25841. target_hits++;
  25842. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25843. res.set_content("direct", "text/plain");
  25844. });
  25845. proxy_mock.listen();
  25846. target.listen();
  25847. Client cli("public.example", target.port());
  25848. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25849. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25850. cli.set_proxy_basic_auth("u", "p");
  25851. cli.set_no_proxy({"127.0.0.1"});
  25852. cli.set_follow_location(true);
  25853. auto res = cli.Get("/redir");
  25854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25855. EXPECT_GE(proxy_hits.load(), 1);
  25856. EXPECT_GE(target_hits.load(), 1);
  25857. EXPECT_FALSE(target_saw_authz.load());
  25858. }
  25859. #ifdef CPPHTTPLIB_SSL_ENABLED
  25860. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25861. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25862. // proxy creds would be sent to the (possibly hostile) origin.
  25863. std::atomic<int> target_hits{0};
  25864. std::atomic<bool> target_saw_proxy_authz{false};
  25865. no_proxy_test::ScopedServer target;
  25866. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25867. target_hits++;
  25868. if (req.has_header("Proxy-Authorization")) {
  25869. target_saw_proxy_authz = true;
  25870. }
  25871. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25872. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25873. "nonce=\"abc\", algorithm=MD5");
  25874. });
  25875. target.listen();
  25876. // The proxy address is set to the target's port: the bypass MUST kick in;
  25877. // if it doesn't, the test still routes "via proxy" to the same server and
  25878. // the Proxy-Authorization assertion below catches the leak.
  25879. Client cli("evil.example", target.port());
  25880. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25881. cli.set_proxy("127.0.0.1", target.port());
  25882. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25883. cli.set_no_proxy({"evil.example"});
  25884. auto res = cli.Get("/x");
  25885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25886. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25887. EXPECT_EQ(1, target_hits.load());
  25888. EXPECT_FALSE(target_saw_proxy_authz.load());
  25889. }
  25890. #endif
  25891. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25892. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25893. std::atomic<int> proxy_hits{0};
  25894. std::atomic<int> bypass_hits{0};
  25895. std::atomic<bool> proxy_saw_c_url{false};
  25896. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25897. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25898. proxy_hits++;
  25899. if (req.path.find("/start") != std::string::npos) {
  25900. res.status = 302;
  25901. res.set_header("Location", "http://127.0.0.1:" +
  25902. std::to_string(bypass_server.port()) +
  25903. "/middle");
  25904. return;
  25905. }
  25906. if (req.path.find("/end") != std::string::npos) {
  25907. proxy_saw_c_url = true;
  25908. res.set_content("c-via-proxy", "text/plain");
  25909. return;
  25910. }
  25911. res.set_content("unexpected", "text/plain");
  25912. });
  25913. // public.example's "advertised" port is arbitrary (the request never lands
  25914. // there — it goes through the proxy), but use a dynamic value to stay
  25915. // friendly with sharded parallel runs.
  25916. int public_port = bypass_server.port();
  25917. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25918. bypass_hits++;
  25919. res.status = 302;
  25920. res.set_header("Location", "http://public.example:" +
  25921. std::to_string(public_port) + "/end");
  25922. });
  25923. proxy_mock.listen();
  25924. bypass_server.listen();
  25925. Client cli("public.example", public_port);
  25926. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25927. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25928. cli.set_no_proxy({"127.0.0.1"});
  25929. cli.set_follow_location(true);
  25930. auto res = cli.Get("/start");
  25931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25932. EXPECT_EQ(StatusCode::OK_200, res->status);
  25933. EXPECT_EQ("c-via-proxy", res->body);
  25934. EXPECT_GE(proxy_hits.load(), 2);
  25935. EXPECT_GE(bypass_hits.load(), 1);
  25936. EXPECT_TRUE(proxy_saw_c_url.load());
  25937. }
  25938. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25939. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25940. // request reconnects to the correct endpoint.
  25941. std::atomic<int> proxy_hits{0};
  25942. std::atomic<int> target_hits{0};
  25943. no_proxy_test::ScopedServer proxy_mock, target;
  25944. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25945. proxy_hits++;
  25946. res.set_content("via-proxy", "text/plain");
  25947. });
  25948. target.svr().Get(".*", [&](const Request &, Response &res) {
  25949. target_hits++;
  25950. res.set_content("direct", "text/plain");
  25951. });
  25952. proxy_mock.listen();
  25953. target.listen();
  25954. Client cli("public.example", target.port());
  25955. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25956. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25957. cli.set_keep_alive(true);
  25958. auto res1 = cli.Get("/a");
  25959. ASSERT_TRUE(res1);
  25960. EXPECT_EQ("via-proxy", res1->body);
  25961. EXPECT_EQ(1, proxy_hits.load());
  25962. EXPECT_EQ(0, target_hits.load());
  25963. cli.set_no_proxy({"public.example"});
  25964. auto res2 = cli.Get("/b");
  25965. ASSERT_TRUE(res2);
  25966. EXPECT_EQ("direct", res2->body);
  25967. EXPECT_EQ(1, proxy_hits.load());
  25968. EXPECT_EQ(1, target_hits.load());
  25969. }
  25970. // Forward declarations (see the base64_encode note).
  25971. namespace httplib {
  25972. namespace detail {
  25973. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  25974. int shutdown_socket(socket_t sock) noexcept;
  25975. } // namespace detail
  25976. } // namespace httplib
  25977. namespace proxy_tunnel_test {
  25978. const char *const kTunnelEstablished =
  25979. "HTTP/1.1 200 Connection established\r\n\r\n";
  25980. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  25981. using ConnectReply = std::function<std::string(const std::string &head)>;
  25982. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  25983. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  25984. class ScopedConnectProxy {
  25985. public:
  25986. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  25987. : forward_port_(forward_port), reply_(std::move(reply)) {
  25988. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25989. if (listen_sock_ == INVALID_SOCKET) { return; }
  25990. auto a = loopback(0);
  25991. auto addr = reinterpret_cast<sockaddr *>(&a);
  25992. socklen_t alen = sizeof(a);
  25993. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  25994. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  25995. ::listen(listen_sock_, 4) != 0) {
  25996. return;
  25997. }
  25998. port_ = ntohs(a.sin_port);
  25999. th_ = std::thread([this] { run(); });
  26000. }
  26001. ~ScopedConnectProxy() {
  26002. if (th_.joinable()) {
  26003. stop_ = true;
  26004. auto wake = connect_to(port_);
  26005. th_.join();
  26006. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26007. }
  26008. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26009. }
  26010. int port() const { return port_; }
  26011. int connect_hits() const { return connect_hits_.load(); }
  26012. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26013. std::string connect_request() const {
  26014. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26015. return connect_request_;
  26016. }
  26017. private:
  26018. static sockaddr_in loopback(int port) {
  26019. sockaddr_in a{};
  26020. a.sin_family = AF_INET;
  26021. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26022. a.sin_port = htons(static_cast<unsigned short>(port));
  26023. return a;
  26024. }
  26025. static socket_t connect_to(int port) {
  26026. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26027. if (sock == INVALID_SOCKET) { return sock; }
  26028. auto a = loopback(port);
  26029. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26030. detail::close_socket(sock);
  26031. return INVALID_SOCKET;
  26032. }
  26033. return sock;
  26034. }
  26035. static bool send_all(socket_t sock, const char *data, size_t size) {
  26036. while (size > 0) {
  26037. auto n = detail::send_socket(sock, data, size, 0);
  26038. if (n <= 0) { return false; }
  26039. data += n;
  26040. size -= static_cast<size_t>(n);
  26041. }
  26042. return true;
  26043. }
  26044. void run() {
  26045. for (;;) {
  26046. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26047. if (stop_) {
  26048. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26049. return;
  26050. }
  26051. if (client == INVALID_SOCKET) { continue; }
  26052. serve(client);
  26053. detail::close_socket(client);
  26054. }
  26055. }
  26056. void serve(socket_t client) {
  26057. std::string head;
  26058. char buf[2048];
  26059. while (head.find("\r\n\r\n") == std::string::npos) {
  26060. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26061. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26062. if (n <= 0) { return; }
  26063. head.append(buf, static_cast<size_t>(n));
  26064. }
  26065. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26066. connect_hits_++;
  26067. {
  26068. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26069. connect_request_ = head;
  26070. }
  26071. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26072. if (!send_all(client, res.data(), res.size()) ||
  26073. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26074. return;
  26075. }
  26076. auto origin = connect_to(forward_port_);
  26077. if (origin == INVALID_SOCKET) { return; }
  26078. // When either side stops, shut both down so the other pump returns too.
  26079. auto pump = [&](socket_t from, socket_t to) {
  26080. char b[8192];
  26081. for (;;) {
  26082. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26083. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26084. }
  26085. detail::shutdown_socket(client);
  26086. detail::shutdown_socket(origin);
  26087. };
  26088. std::thread up([&] { pump(client, origin); });
  26089. pump(origin, client);
  26090. up.join();
  26091. detail::close_socket(origin);
  26092. }
  26093. int forward_port_;
  26094. ConnectReply reply_;
  26095. socket_t listen_sock_ = INVALID_SOCKET;
  26096. int port_ = 0;
  26097. std::thread th_;
  26098. std::atomic<bool> stop_{false};
  26099. std::atomic<int> connect_hits_{0};
  26100. mutable std::mutex connect_request_mutex_;
  26101. std::string connect_request_;
  26102. };
  26103. } // namespace proxy_tunnel_test
  26104. #ifdef CPPHTTPLIB_SSL_ENABLED
  26105. namespace proxy_tunnel_test {
  26106. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26107. class ScopedSSLServer {
  26108. public:
  26109. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26110. port_ = svr_.bind_to_any_port("127.0.0.1");
  26111. }
  26112. ~ScopedSSLServer() {
  26113. svr_.stop();
  26114. if (th_.joinable()) { th_.join(); }
  26115. }
  26116. SSLServer &svr() { return svr_; }
  26117. int port() const { return port_; }
  26118. void listen() {
  26119. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26120. svr_.wait_until_ready();
  26121. }
  26122. private:
  26123. SSLServer svr_;
  26124. std::thread th_;
  26125. int port_ = 0;
  26126. };
  26127. // Sends one request through the CONNECT proxy to the TLS origin with a
  26128. // credential configured for each hop, and checks that each credential reaches
  26129. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26130. // origin's (every header in origin_headers) on the tunnelled request.
  26131. void CredentialsStayWithTheirHop(
  26132. const std::function<void(SSLClient &)> &set_credentials,
  26133. const std::string &scheme,
  26134. const std::vector<std::string> &origin_headers = {"Authorization"},
  26135. bool stream = false) {
  26136. std::atomic<int> origin_hits{0};
  26137. std::atomic<bool> origin_saw_proxy_authz{false};
  26138. std::atomic<bool> origin_saw_headers{false};
  26139. ScopedSSLServer origin;
  26140. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26141. origin_hits++;
  26142. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26143. origin_saw_headers =
  26144. std::all_of(origin_headers.begin(), origin_headers.end(),
  26145. [&](const std::string &h) { return req.has_header(h); });
  26146. res.set_content("ok", "text/plain");
  26147. });
  26148. origin.listen();
  26149. ScopedConnectProxy proxy(origin.port());
  26150. ASSERT_NE(0, proxy.port());
  26151. // Pinned to 127.0.0.1 for the same reason as the test below.
  26152. SSLClient cli("127.0.0.1", origin.port());
  26153. cli.enable_server_certificate_verification(false);
  26154. cli.set_proxy("127.0.0.1", proxy.port());
  26155. set_credentials(cli);
  26156. if (stream) {
  26157. auto handle = cli.open_stream("GET", "/x");
  26158. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26159. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26160. } else {
  26161. auto res = cli.Get("/x");
  26162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26163. EXPECT_EQ(StatusCode::OK_200, res->status);
  26164. }
  26165. EXPECT_EQ(1, origin_hits.load());
  26166. EXPECT_EQ(1, proxy.connect_hits());
  26167. EXPECT_TRUE(origin_saw_headers.load());
  26168. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26169. << "Proxy-Authorization must not be sent inside the tunnel";
  26170. auto connect_req = proxy.connect_request();
  26171. EXPECT_NE(std::string::npos,
  26172. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26173. for (const auto &h : origin_headers) {
  26174. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26175. << h << " must not be sent to the proxy on CONNECT";
  26176. }
  26177. }
  26178. } // namespace proxy_tunnel_test
  26179. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26180. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26181. [](SSLClient &cli) {
  26182. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26183. cli.set_basic_auth("origin-user", "origin-pass");
  26184. },
  26185. "Basic");
  26186. }
  26187. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26188. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26189. [](SSLClient &cli) {
  26190. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26191. cli.set_basic_auth("origin-user", "origin-pass");
  26192. },
  26193. "Basic", {"Authorization"}, true);
  26194. }
  26195. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26196. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26197. [](SSLClient &cli) {
  26198. cli.set_proxy_bearer_token_auth("proxy-token");
  26199. cli.set_bearer_token_auth("origin-token");
  26200. },
  26201. "Bearer");
  26202. }
  26203. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26204. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26205. [](SSLClient &cli) {
  26206. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26207. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26208. {"Cookie", "sid=origin-session"},
  26209. {"X-Api-Key", "origin-key"}});
  26210. },
  26211. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26212. }
  26213. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26214. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26215. // retry; otherwise proxy creds would be sent to the origin.
  26216. std::atomic<int> origin_hits{0};
  26217. std::atomic<bool> origin_saw_proxy_authz{false};
  26218. proxy_tunnel_test::ScopedSSLServer origin;
  26219. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26220. origin_hits++;
  26221. if (req.has_header("Proxy-Authorization")) {
  26222. origin_saw_proxy_authz = true;
  26223. }
  26224. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26225. res.set_header("Proxy-Authenticate",
  26226. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26227. "algorithm=MD5");
  26228. });
  26229. origin.listen();
  26230. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26231. ASSERT_NE(0, proxy.port());
  26232. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26233. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26234. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26235. // and answer with its own status, making this test flaky.
  26236. SSLClient cli("127.0.0.1", origin.port());
  26237. cli.enable_server_certificate_verification(false);
  26238. cli.set_proxy("127.0.0.1", proxy.port());
  26239. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26240. auto res = cli.Get("/x");
  26241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26242. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26243. EXPECT_EQ(1, origin_hits.load());
  26244. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26245. EXPECT_EQ(1, proxy.connect_hits());
  26246. }
  26247. #endif
  26248. namespace proxy_tunnel_test {
  26249. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26250. // anything else gets a 407 with `challenge`.
  26251. ConnectReply require_proxy_auth(const std::string &expected,
  26252. const std::string &challenge) {
  26253. return [=](const std::string &head) -> std::string {
  26254. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26255. std::string::npos) {
  26256. return kTunnelEstablished;
  26257. }
  26258. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26259. "Proxy-Authenticate: " +
  26260. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26261. };
  26262. }
  26263. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26264. // request, then echoes.
  26265. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26266. ws.send(
  26267. "authorization:" + req.get_header_value("Authorization") +
  26268. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26269. std::string msg;
  26270. while (ws.read(msg)) {
  26271. ws.send(msg);
  26272. }
  26273. }
  26274. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26275. class ScopedWebSocketOrigin {
  26276. public:
  26277. ScopedWebSocketOrigin() {
  26278. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26279. server_.listen();
  26280. }
  26281. int port() const { return server_.port(); }
  26282. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26283. std::string url() const {
  26284. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26285. }
  26286. private:
  26287. no_proxy_test::ScopedServer server_;
  26288. };
  26289. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26290. // passed as a constructor header, and checks that each reaches only its hop.
  26291. void WebSocketCredentialsStayWithTheirHop(
  26292. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26293. const std::string &proxy_authz, const std::string &origin_authz) {
  26294. ScopedWebSocketOrigin origin;
  26295. ScopedConnectProxy proxy(
  26296. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26297. ASSERT_NE(0, proxy.port());
  26298. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26299. client.set_proxy("127.0.0.1", proxy.port());
  26300. set_proxy_credentials(client);
  26301. auto res = client.connect();
  26302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26303. std::string msg;
  26304. ASSERT_TRUE(client.read(msg));
  26305. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26306. client.close();
  26307. EXPECT_EQ(1, proxy.connect_hits());
  26308. EXPECT_EQ(std::string::npos,
  26309. proxy.connect_request().find("\r\nAuthorization: "))
  26310. << "origin credentials must not be sent to the proxy";
  26311. }
  26312. } // namespace proxy_tunnel_test
  26313. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26314. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26315. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26316. ASSERT_NE(0, proxy.port());
  26317. ws::WebSocketClient client(origin.url());
  26318. client.set_proxy("127.0.0.1", proxy.port());
  26319. auto res = client.connect();
  26320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26321. std::string msg;
  26322. ASSERT_TRUE(client.read(msg));
  26323. ASSERT_TRUE(client.send("hello"));
  26324. ASSERT_TRUE(client.read(msg));
  26325. EXPECT_EQ("hello", msg);
  26326. client.close();
  26327. EXPECT_EQ(1, proxy.connect_hits());
  26328. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26329. auto connect_req = proxy.connect_request();
  26330. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26331. EXPECT_NE(std::string::npos,
  26332. connect_req.find("\r\nHost: " + target + "\r\n"));
  26333. }
  26334. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26335. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26336. [](ws::WebSocketClient &cli) {
  26337. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26338. },
  26339. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26340. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26341. }
  26342. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26343. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26344. [](ws::WebSocketClient &cli) {
  26345. cli.set_proxy_bearer_token_auth("proxy-token");
  26346. },
  26347. "Bearer proxy-token", "Bearer origin-token");
  26348. }
  26349. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26350. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26351. proxy_tunnel_test::ScopedConnectProxy proxy(
  26352. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26353. "Basic " + detail::base64_encode("proxy-user:"),
  26354. "Basic realm=\"proxy\""));
  26355. ASSERT_NE(0, proxy.port());
  26356. ws::WebSocketClient client(origin.url());
  26357. client.set_proxy("127.0.0.1", proxy.port());
  26358. client.set_proxy_basic_auth("proxy-user", "");
  26359. auto res = client.connect();
  26360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26361. client.close();
  26362. EXPECT_EQ(1, proxy.connect_hits());
  26363. }
  26364. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26365. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26366. proxy_tunnel_test::ScopedConnectProxy proxy(
  26367. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26368. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26369. ASSERT_NE(0, proxy.port());
  26370. ws::WebSocketClient client(origin.url());
  26371. client.set_proxy("127.0.0.1", proxy.port());
  26372. auto res = client.connect();
  26373. EXPECT_FALSE(res);
  26374. EXPECT_EQ(Error::ProxyConnection, res.error());
  26375. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26376. EXPECT_EQ("Basic realm=\"proxy\"",
  26377. res.get_header_value("Proxy-Authenticate"));
  26378. EXPECT_FALSE(client.is_open());
  26379. }
  26380. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26381. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26382. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26383. ASSERT_NE(0, proxy.port());
  26384. ws::WebSocketClient client(origin.url());
  26385. client.set_proxy("127.0.0.1", proxy.port());
  26386. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26387. client.set_no_proxy({"127.0.0.1"});
  26388. auto res = client.connect();
  26389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26390. std::string msg;
  26391. ASSERT_TRUE(client.read(msg));
  26392. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26393. << "proxy credentials must not reach a bypassed origin";
  26394. client.close();
  26395. EXPECT_EQ(0, proxy.connect_hits());
  26396. }
  26397. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26398. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26399. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26400. ASSERT_NE(0, proxy.port());
  26401. ws::WebSocketClient client(origin.url());
  26402. client.set_proxy("127.0.0.1", proxy.port());
  26403. ASSERT_TRUE(client.connect());
  26404. ASSERT_TRUE(client.connect());
  26405. client.close();
  26406. EXPECT_EQ(2, proxy.connect_hits());
  26407. }
  26408. #ifdef CPPHTTPLIB_SSL_ENABLED
  26409. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26410. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26411. proxy_tunnel_test::ScopedConnectProxy proxy(
  26412. origin.port(), [](const std::string &head) -> std::string {
  26413. if (head.find(
  26414. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26415. std::string::npos) {
  26416. return proxy_tunnel_test::kTunnelEstablished;
  26417. }
  26418. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26419. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26420. "nonce=\"abc\", algorithm=MD5\r\n"
  26421. "Content-Length: 0\r\n\r\n";
  26422. });
  26423. ASSERT_NE(0, proxy.port());
  26424. ws::WebSocketClient client(origin.url());
  26425. client.set_proxy("127.0.0.1", proxy.port());
  26426. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26427. auto res = client.connect();
  26428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26429. std::string msg;
  26430. ASSERT_TRUE(client.read(msg));
  26431. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26432. client.close();
  26433. EXPECT_EQ(2, proxy.connect_hits());
  26434. }
  26435. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26436. proxy_tunnel_test::ScopedSSLServer origin;
  26437. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26438. origin.listen();
  26439. proxy_tunnel_test::ScopedConnectProxy proxy(
  26440. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26441. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26442. ASSERT_NE(0, proxy.port());
  26443. ws::WebSocketClient client(
  26444. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26445. client.enable_server_certificate_verification(false);
  26446. client.set_proxy("127.0.0.1", proxy.port());
  26447. client.set_proxy_bearer_token_auth("proxy-token");
  26448. auto res = client.connect();
  26449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26450. std::string msg;
  26451. ASSERT_TRUE(client.read(msg));
  26452. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26453. << "Proxy-Authorization must not be sent inside the tunnel";
  26454. client.close();
  26455. EXPECT_EQ(1, proxy.connect_hits());
  26456. }
  26457. #endif