test.cc 1020 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. std::vector<std::string> get_ca_names(ctx_t ctx);
  69. } // namespace tls
  70. } // namespace httplib
  71. #endif
  72. using namespace std;
  73. using namespace httplib;
  74. const char *HOST = "localhost";
  75. static int get_base_port() {
  76. const char *shard = getenv("GTEST_SHARD_INDEX");
  77. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  78. }
  79. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  80. // New standalone tests MUST use svr.bind_to_any_port() instead.
  81. const int PORT = get_base_port();
  82. const string LONG_QUERY_VALUE = string(25000, '@');
  83. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  84. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  85. const string TOO_LONG_QUERY_URL =
  86. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  87. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  88. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  89. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  90. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  91. return file.name == key;
  92. });
  93. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  94. return *it;
  95. #else
  96. if (it != items.end()) { return *it; }
  97. throw std::runtime_error("invalid multipart form data name error");
  98. #endif
  99. }
  100. static void read_file(const std::string &path, std::string &out) {
  101. std::ifstream fs(path, std::ios_base::binary);
  102. if (!fs) {
  103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  104. return;
  105. #else
  106. throw std::runtime_error("File not found: " + path);
  107. #endif
  108. }
  109. fs.seekg(0, std::ios_base::end);
  110. auto size = fs.tellg();
  111. fs.seekg(0);
  112. out.resize(static_cast<size_t>(size));
  113. fs.read(&out[0], static_cast<std::streamsize>(size));
  114. }
  115. class UnixSocketTest : public ::testing::Test {
  116. protected:
  117. void TearDown() override { std::remove(pathname_.c_str()); }
  118. void client_GET(const std::string &addr) {
  119. httplib::Client cli{addr};
  120. cli.set_address_family(AF_UNIX);
  121. ASSERT_TRUE(cli.is_valid());
  122. const auto &result = cli.Get(pattern_);
  123. ASSERT_TRUE(result) << "error: " << result.error();
  124. const auto &resp = result.value();
  125. EXPECT_EQ(resp.status, StatusCode::OK_200);
  126. EXPECT_EQ(resp.body, content_);
  127. }
  128. static std::string make_sock_path() {
  129. const char *shard = getenv("GTEST_SHARD_INDEX");
  130. return shard ? std::string("./httplib-server-") + shard + ".sock"
  131. : "./httplib-server.sock";
  132. }
  133. const std::string pathname_{make_sock_path()};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. // ".//x.sock", which is not taken for a URL
  154. client_GET("./" + pathname_.substr(1));
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_TRUE(s0.is_peer_alive());
  247. EXPECT_EQ(0, close(fds[1]));
  248. EXPECT_FALSE(s0.is_peer_alive());
  249. return true;
  250. });
  251. EXPECT_EQ(0, close(fds[0]));
  252. }
  253. TEST(SocketStream, wait_writable_INET) {
  254. sockaddr_in addr;
  255. memset(&addr, 0, sizeof(addr));
  256. addr.sin_family = AF_INET;
  257. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  258. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  259. int disconnected_svr_sock = -1;
  260. std::thread svr{[&] {
  261. const int s = socket(AF_INET, SOCK_STREAM, 0);
  262. ASSERT_LE(0, s);
  263. // PORT + 1 is shared with the SSL redirect tests and with
  264. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  265. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  266. // because that happens on a worker thread the ASSERT does not stop the
  267. // test: it runs on and fails at the disconnected_svr_sock check instead.
  268. default_socket_options(s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. // wait_writable() returns true because select_write() only checks if the
  292. // send buffer has space. Peer disconnection is detected later by send().
  293. EXPECT_TRUE(ss.wait_writable());
  294. return true;
  295. });
  296. ASSERT_EQ(0, close(disconnected_svr_sock));
  297. }
  298. #endif // #ifndef _WIN32
  299. TEST(SetSocketOptTest, TcpNoDelay) {
  300. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  301. ASSERT_NE(sock, INVALID_SOCKET);
  302. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  303. int val = 0;
  304. socklen_t len = sizeof(val);
  305. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  306. reinterpret_cast<char *>(&val), &len));
  307. EXPECT_NE(val, 0);
  308. detail::close_socket(sock);
  309. }
  310. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  311. // accept() reports failures through WSAGetLastError() on Windows and through
  312. // errno everywhere else. Asking the wrong one is what made the accept loop
  313. // treat every recoverable failure as fatal on Windows.
  314. struct Classification {
  315. bool resource;
  316. bool transient;
  317. };
  318. auto classify = [](int err) {
  319. #ifdef _WIN32
  320. WSASetLastError(err);
  321. #else
  322. errno = err;
  323. #endif
  324. // Read both before asserting: an assertion may clobber the error slot.
  325. Classification c;
  326. c.resource = detail::is_accept_resource_error();
  327. c.transient = detail::is_accept_transient_error();
  328. return c;
  329. };
  330. #ifdef _WIN32
  331. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  332. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  333. WSAECONNRESET, WSAECONNABORTED};
  334. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  335. #else
  336. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  337. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  338. ECONNABORTED};
  339. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  340. #endif
  341. for (auto err : resource_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.resource) << "error " << err;
  344. EXPECT_FALSE(c.transient) << "error " << err;
  345. }
  346. for (auto err : transient_errors) {
  347. const auto c = classify(err);
  348. EXPECT_TRUE(c.transient) << "error " << err;
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. }
  351. for (auto err : fatal_errors) {
  352. const auto c = classify(err);
  353. EXPECT_FALSE(c.resource) << "error " << err;
  354. EXPECT_FALSE(c.transient) << "error " << err;
  355. }
  356. #ifdef _WIN32
  357. WSASetLastError(0);
  358. #else
  359. errno = 0;
  360. #endif
  361. }
  362. TEST(ClientTest, MoveConstructible) {
  363. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  365. }
  366. TEST(ClientTest, MoveAssignable) {
  367. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  368. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  369. }
  370. #ifdef _WIN32
  371. TEST(StartupTest, WSAStartup) {
  372. WSADATA wsaData;
  373. int ret = WSAStartup(0x0002, &wsaData);
  374. ASSERT_EQ(0, ret);
  375. }
  376. #endif
  377. TEST(DecodePathTest, PercentCharacter) {
  378. EXPECT_EQ(
  379. decode_path_component(
  380. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  381. U8("descrip=Gastos áéíóúñÑ 6"));
  382. }
  383. TEST(DecodePathTest, PercentCharacterNUL) {
  384. string expected;
  385. expected.push_back('x');
  386. expected.push_back('\0');
  387. expected.push_back('x');
  388. EXPECT_EQ(decode_path_component("x%00x"), expected);
  389. }
  390. TEST(DecodePathTest, UnicodeEncoding) {
  391. // %u0041 = 'A' (1-byte UTF-8)
  392. EXPECT_EQ("A", decode_path_component("%u0041"));
  393. // %u00E9 = 'é' (2-byte UTF-8)
  394. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  395. // %u3042 = 'あ' (3-byte UTF-8)
  396. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  397. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  398. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  399. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  400. // neighbours)
  401. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  402. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  403. }
  404. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  405. // A sign or whitespace inside the two-character escape window must not be
  406. // accepted as a valid percent-encoding; the sequence is passed through
  407. // literally, matching decode_uri_component / decode_path_component.
  408. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  409. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  410. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  411. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  412. // Well-formed escapes still decode.
  413. EXPECT_EQ("-", decode_query_component("%2D", false));
  414. EXPECT_EQ("A", decode_query_component("%41", false));
  415. }
  416. TEST(SanitizeFilenameTest, VariousPatterns) {
  417. // Path traversal
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  420. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  421. // Normal and edge cases
  422. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  423. EXPECT_EQ("filename.txt",
  424. httplib::sanitize_filename("/path/to/filename.txt"));
  425. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  426. EXPECT_EQ("", httplib::sanitize_filename(".."));
  427. EXPECT_EQ("", httplib::sanitize_filename(""));
  428. // Null bytes stripped
  429. EXPECT_EQ("safe.txt",
  430. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  431. // Whitespace-only rejected
  432. EXPECT_EQ("", httplib::sanitize_filename(" "));
  433. }
  434. // Forward declaration (see the base64_encode note below): split builds move the
  435. // definition into httplib.cc, so re-declaring it here lets the test link.
  436. namespace httplib {
  437. namespace detail {
  438. bool is_chunked_transfer_encoding(const Headers &headers);
  439. } // namespace detail
  440. } // namespace httplib
  441. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  442. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  443. auto make = [](std::initializer_list<const char *> lines) {
  444. Headers h;
  445. for (auto te : lines) {
  446. if (te) { h.emplace("Transfer-Encoding", te); }
  447. }
  448. return h;
  449. };
  450. // Sole coding, matched case-insensitively.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  454. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  458. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  463. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  464. // were received, into one list. Headers preserves that order, so the answer
  465. // is decided by the last coding of the last line and the order the lines
  466. // arrived in is significant.
  467. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  470. // The split can fall anywhere in the list.
  471. EXPECT_TRUE(
  472. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  473. EXPECT_FALSE(
  474. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  475. // A trailing line naming no coding leaves the list ending in nothing, so it
  476. // must not inherit the chunked from the line before it.
  477. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  478. }
  479. // Forward declarations (see the base64_encode note below).
  480. namespace httplib {
  481. namespace detail {
  482. bool parse_status_line(const char *line, std::string &version, int &status,
  483. std::string &reason);
  484. std::string file_extension(const std::string &path);
  485. std::string
  486. find_content_type(const std::string &path,
  487. const std::map<std::string, std::string> &user_data,
  488. const std::string &default_content_type);
  489. bool can_compress_content_type(const std::string &content_type);
  490. bool is_prohibited_header_name(const std::string &name);
  491. #ifdef CPPHTTPLIB_SSL_ENABLED
  492. bool match_hostname(const std::string &pattern, const std::string &hostname);
  493. #endif
  494. } // namespace detail
  495. } // namespace httplib
  496. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  497. struct {
  498. const char *line;
  499. const char *version;
  500. int status;
  501. const char *reason;
  502. } cases[] = {
  503. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  504. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  505. // The reason phrase may be empty, or left out along with its space.
  506. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  507. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  508. };
  509. for (const auto &c : cases) {
  510. std::string version;
  511. int status = 0;
  512. std::string reason = "unset";
  513. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  514. << c.line;
  515. EXPECT_EQ(c.version, version);
  516. EXPECT_EQ(c.status, status);
  517. EXPECT_EQ(c.reason, reason);
  518. }
  519. }
  520. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  521. const char *lines[] = {
  522. "HTTP/2 200 OK\r\n",
  523. "HTTP/1.2 200 OK\r\n",
  524. "HTTP/1.1 20 OK\r\n",
  525. "HTTP/1.1 2000 OK\r\n",
  526. "HTTP/1.1 2x0 OK\r\n",
  527. "HTTP/1.1 200 OK\r\n",
  528. "HTTP/1.1 200OK\r\n",
  529. "HTTP/1.1 200 O\rK\r\n",
  530. "HTTP/1.1 200 OK",
  531. "HTTP/1.1 200 OK\r\nX",
  532. "",
  533. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  534. "HTTP/1.1 200 OK\n",
  535. #endif
  536. };
  537. for (auto line : lines) {
  538. std::string version;
  539. int status = 0;
  540. std::string reason;
  541. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  542. << line;
  543. }
  544. }
  545. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  546. // Long enough to overflow the stack when matched with std::regex.
  547. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  548. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  549. std::string version;
  550. int status = 0;
  551. std::string reason;
  552. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  553. EXPECT_EQ(200, status);
  554. EXPECT_EQ(long_reason, reason);
  555. }
  556. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  557. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  558. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  559. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  560. EXPECT_EQ("", detail::file_extension("noext"));
  561. EXPECT_EQ("", detail::file_extension("a."));
  562. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  563. EXPECT_EQ("", detail::file_extension("a.b-c"));
  564. // Long enough to overflow the stack when matched with std::regex.
  565. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  566. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  567. }
  568. #ifdef CPPHTTPLIB_SSL_ENABLED
  569. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  570. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  573. // A wildcard needs two labels after it, in the leftmost label only
  574. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  575. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  576. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  577. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  578. EXPECT_FALSE(
  579. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  580. // No name may have an empty label
  581. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  582. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  583. }
  584. #endif
  585. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  586. detail::case_ignore::hash hash;
  587. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  588. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  589. // Long enough to overflow the stack if hashed one call per character.
  590. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  591. }
  592. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  593. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  594. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  595. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  596. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  597. // Same 26-bit hash as html, svg and js.
  598. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  601. }
  602. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  603. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  604. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  605. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  606. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  607. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  608. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  609. // Same 26-bit hash as application/json.
  610. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  611. }
  612. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  613. Request req;
  614. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  615. EXPECT_TRUE(req.is_multipart_form_data());
  616. std::string boundary;
  617. EXPECT_TRUE(detail::parse_multipart_boundary(
  618. req.get_header_value("Content-Type"), boundary));
  619. EXPECT_EQ("x", boundary);
  620. }
  621. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  622. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  623. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  624. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  625. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  626. // Same 26-bit hash as REMOTE_ADDR.
  627. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  628. }
  629. // Forward declaration: in split builds split.py strips `inline` and moves the
  630. // definition into httplib.cc, so detail::base64_encode is not visible from the
  631. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  632. // in both header-only and split builds.
  633. namespace httplib {
  634. namespace detail {
  635. std::string base64_encode(const std::string &in);
  636. } // namespace detail
  637. } // namespace httplib
  638. TEST(Base64EncodeTest, KnownAnswers) {
  639. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  640. // where the accumulator's top bit is already set before the next shift.
  641. EXPECT_EQ("", detail::base64_encode(""));
  642. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  643. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  644. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  645. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  646. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  647. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  648. // High bytes keep the top bit set across several rounds.
  649. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  650. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  651. }
  652. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  653. string unescapedCharacters = "-_.!~*'()";
  654. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  655. }
  656. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  657. string reservedCharacters = ";,/?:@&=+$";
  658. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  659. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  660. }
  661. TEST(ClientQueryOrder, PreserveOrder) {
  662. // This test reproduces Issue #2259: client may reorder query parameters
  663. // when sending a GET request. The expected behavior is that the client
  664. // preserves the original query string order when the caller supplied it
  665. // as part of the path.
  666. Server svr;
  667. svr.Get("/", [&](const Request &req, Response &res) {
  668. // Echo back the raw target so the test can assert ordering
  669. res.set_content(req.target, "text/plain");
  670. });
  671. std::thread t{[&] { svr.listen(HOST, PORT); }};
  672. auto se = detail::scope_exit([&] {
  673. svr.stop();
  674. t.join();
  675. ASSERT_FALSE(svr.is_running());
  676. });
  677. svr.wait_until_ready();
  678. Client cli(HOST, PORT);
  679. ASSERT_TRUE(cli.is_valid());
  680. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  681. auto res = cli.Get(original);
  682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  683. // Expect the echoed target to exactly match the original path (order
  684. // preserved)
  685. EXPECT_EQ(res->body, original);
  686. }
  687. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  688. string chineseCharacters = U8("中国語");
  689. string russianCharacters = U8("дом");
  690. string brazilianCharacters = U8("óculos");
  691. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  692. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  693. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  694. "%D0%B4%D0%BE%D0%BC");
  695. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  696. }
  697. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  698. string unescapedCharacters = "-_.!~*'()";
  699. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  700. }
  701. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  702. string reservedCharacters = ";,/?:@&=+$";
  703. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  704. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  705. }
  706. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  707. string chineseCharacters = U8("中国語");
  708. string russianCharacters = U8("дом");
  709. string brazilianCharacters = U8("óculos");
  710. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  711. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  712. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  713. "%D0%B4%D0%BE%D0%BC");
  714. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  715. }
  716. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  717. // Issue #2082 use case: encoding path component with ampersand
  718. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  719. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  720. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  721. }
  722. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  723. string unescapedCharacters = "-_.!~*'()";
  724. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  725. }
  726. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  727. string reservedCharacters = ";,/?:@&=+$#";
  728. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  729. }
  730. TEST(EncodeUriTest, TestUTF8Characters) {
  731. string chineseCharacters = U8("中国語");
  732. string russianCharacters = U8("дом");
  733. string brazilianCharacters = U8("óculos");
  734. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  735. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  736. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  737. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  738. }
  739. TEST(EncodeUriTest, TestCompleteUri) {
  740. string uri =
  741. "https://example.com/path/to/resource?query=value&param=test#fragment";
  742. EXPECT_EQ(
  743. httplib::encode_uri(uri),
  744. "https://example.com/path/to/resource?query=value&param=test#fragment");
  745. }
  746. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  747. string uri =
  748. "https://example.com/path with spaces/file name.html?q=hello world";
  749. EXPECT_EQ(httplib::encode_uri(uri),
  750. "https://example.com/path%20with%20spaces/"
  751. "file%20name.html?q=hello%20world");
  752. }
  753. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  754. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  755. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  756. }
  757. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  758. string unescapedCharacters = "-_.!~*'()";
  759. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  760. }
  761. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  762. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  763. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  764. string encodedBrazilian = "%C3%B3culos";
  765. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  767. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  768. }
  769. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  770. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  772. "Piri Tommy Villiers - on & on");
  773. }
  774. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  775. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  776. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  777. }
  778. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  779. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  780. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  781. }
  782. TEST(DecodeUriTest, TestUTF8Characters) {
  783. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  784. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  785. string encodedBrazilian = "%C3%B3culos";
  786. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  787. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  788. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  789. }
  790. TEST(DecodeUriTest, TestCompleteUri) {
  791. string encodedUri = "https://example.com/path%20with%20spaces/"
  792. "file%20name.html?q=hello%20world";
  793. EXPECT_EQ(
  794. httplib::decode_uri(encodedUri),
  795. "https://example.com/path with spaces/file name.html?q=hello world");
  796. }
  797. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  798. string original =
  799. "https://example.com/path with spaces/file name.html?q=hello world";
  800. string encoded = httplib::encode_uri(original);
  801. string decoded = httplib::decode_uri(encoded);
  802. EXPECT_EQ(decoded, original);
  803. }
  804. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  805. // decode_uri is the inverse of encode_uri: an escaped reserved character
  806. // stays encoded so it is not promoted into a real delimiter, while
  807. // non-reserved escapes still decode (like JS decodeURI).
  808. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  809. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  810. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  811. "%3F%3A%40%26%3D%2B%24%2C%3B");
  812. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  813. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  814. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  815. "http://example.com/a%2Fb");
  816. // decode_uri_component still decodes the reserved character.
  817. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  818. }
  819. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  820. string original = "Piri Tommy Villiers - on & on";
  821. string encoded = httplib::encode_uri_component(original);
  822. string decoded = httplib::decode_uri_component(encoded);
  823. EXPECT_EQ(decoded, original);
  824. }
  825. TEST(TrimTests, TrimStringTests) {
  826. EXPECT_EQ("abc", detail::trim_copy("abc"));
  827. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  828. EXPECT_TRUE(detail::trim_copy("").empty());
  829. }
  830. TEST(AsciiTest, LocaleIndependentClassification) {
  831. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  832. // which consult the global C locale: std::isalnum(0xC5) can return true
  833. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  834. // helpers must classify every byte by the ASCII grammar alone.
  835. for (int i = 0; i < 256; i++) {
  836. auto c = static_cast<char>(i);
  837. auto is_digit = i >= '0' && i <= '9';
  838. auto is_upper = i >= 'A' && i <= 'Z';
  839. auto is_lower = i >= 'a' && i <= 'z';
  840. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  841. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  842. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  843. << "byte " << i;
  844. }
  845. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  846. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  847. // Non-ASCII bytes must be percent-encoded, never passed through as
  848. // alphanumeric.
  849. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  850. }
  851. TEST(FromCharsTest, Double) {
  852. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  853. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  854. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  855. auto parse = [](const std::string &s, double &v) {
  856. return detail::from_chars(s.data(), s.data() + s.size(), v);
  857. };
  858. double v = -1.0;
  859. // Representative quality values.
  860. EXPECT_EQ(parse("0", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.0);
  862. EXPECT_EQ(parse("1", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 1.0);
  864. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 0.8);
  866. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.001);
  868. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. // A missing integer or fractional part is tolerated.
  871. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  872. EXPECT_DOUBLE_EQ(v, 0.5);
  873. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 5.0);
  875. // Values outside [0, 1] still parse; the caller range-checks them.
  876. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  877. EXPECT_DOUBLE_EQ(v, 123.456);
  878. // Stops at the first byte that is not part of the number and reports where.
  879. std::string trailing = "0.9, text/html";
  880. auto r = parse(trailing, v);
  881. EXPECT_EQ(r.ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 0.9);
  883. EXPECT_EQ(*r.ptr, ',');
  884. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  885. // outright, and an 'e'/'E' simply ends the number.
  886. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  888. std::string exp_input = "1.5e3";
  889. r = parse(exp_input, v);
  890. EXPECT_EQ(r.ec, std::errc{});
  891. EXPECT_DOUBLE_EQ(v, 1.5);
  892. EXPECT_EQ(*r.ptr, 'e');
  893. // Invalid inputs.
  894. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  898. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  899. // Pathological but well-formed inputs must stay bounded (no overflow, no
  900. // out-of-bounds table access) and stay within [0, 1] for the caller.
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  902. std::errc{});
  903. EXPECT_DOUBLE_EQ(v, 0.0);
  904. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  905. std::errc{});
  906. EXPECT_GE(v, 0.0);
  907. EXPECT_LE(v, 1.0);
  908. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  909. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  910. }
  911. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  912. // Simple case without quality values
  913. std::vector<std::string> result1;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html,application/json,text/plain", result1));
  916. EXPECT_EQ(result1.size(), 3U);
  917. EXPECT_EQ(result1[0], "text/html");
  918. EXPECT_EQ(result1[1], "application/json");
  919. EXPECT_EQ(result1[2], "text/plain");
  920. // With quality values
  921. std::vector<std::string> result2;
  922. EXPECT_TRUE(detail::parse_accept_header(
  923. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  924. EXPECT_EQ(result2.size(), 3U);
  925. EXPECT_EQ(result2[0], "application/json"); // highest q value
  926. EXPECT_EQ(result2[1], "text/html");
  927. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  928. }
  929. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  930. // Mixed with and without quality values
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(
  933. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  934. EXPECT_EQ(result.size(), 3U);
  935. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  936. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  937. EXPECT_EQ(result[2], "application/json"); // q=0.5
  938. }
  939. TEST(ParseAcceptHeaderTest, EdgeCases) {
  940. // Empty header
  941. std::vector<std::string> empty_result;
  942. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  943. EXPECT_TRUE(empty_result.empty());
  944. // Single type
  945. std::vector<std::string> single_result;
  946. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  947. EXPECT_EQ(single_result.size(), 1U);
  948. EXPECT_EQ(single_result[0], "application/json");
  949. // Wildcard types
  950. std::vector<std::string> wildcard_result;
  951. EXPECT_TRUE(detail::parse_accept_header(
  952. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  953. EXPECT_EQ(wildcard_result.size(), 3U);
  954. EXPECT_EQ(wildcard_result[0], "application/json");
  955. EXPECT_EQ(wildcard_result[1], "text/*");
  956. EXPECT_EQ(wildcard_result[2], "*/*");
  957. }
  958. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  959. // Common browser Accept header
  960. std::vector<std::string> browser_result;
  961. EXPECT_TRUE(
  962. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  963. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  964. browser_result));
  965. EXPECT_EQ(browser_result.size(), 6U);
  966. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  970. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  971. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  972. // API client header
  973. std::vector<std::string> api_result;
  974. EXPECT_TRUE(detail::parse_accept_header(
  975. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  976. api_result));
  977. EXPECT_EQ(api_result.size(), 3U);
  978. EXPECT_EQ(api_result[0], "application/json");
  979. EXPECT_EQ(api_result[1], "application/xml");
  980. EXPECT_EQ(api_result[2], "text/plain");
  981. }
  982. TEST(ParseAcceptHeaderTest, SpecialCases) {
  983. // Quality value with 3 decimal places
  984. std::vector<std::string> decimal_result;
  985. EXPECT_TRUE(detail::parse_accept_header(
  986. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  987. EXPECT_EQ(decimal_result.size(), 2U);
  988. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  989. EXPECT_EQ(decimal_result[1], "text/html");
  990. // Zero quality (should still be included but with lowest priority)
  991. std::vector<std::string> zero_q_result;
  992. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  993. zero_q_result));
  994. EXPECT_EQ(zero_q_result.size(), 2U);
  995. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  996. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  997. // No spaces around commas
  998. std::vector<std::string> no_space_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1001. no_space_result));
  1002. EXPECT_EQ(no_space_result.size(), 3U);
  1003. EXPECT_EQ(no_space_result[0], "text/html");
  1004. EXPECT_EQ(no_space_result[1], "application/json");
  1005. EXPECT_EQ(no_space_result[2], "text/plain");
  1006. }
  1007. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1008. // Quality values always use '.' as the decimal separator, so parsing must
  1009. // not depend on the process locale. An embedding application may have
  1010. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1011. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1012. std::string saved = cur ? cur : "C";
  1013. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1014. "fr_FR.UTF-8"};
  1015. bool switched = false;
  1016. for (const auto loc : comma_locales) {
  1017. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1018. std::localeconv()->decimal_point[0] == ',') {
  1019. switched = true;
  1020. break;
  1021. }
  1022. }
  1023. if (!switched) {
  1024. std::setlocale(LC_NUMERIC, saved.c_str());
  1025. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1026. }
  1027. // The higher-weighted type appears later in the list, so a correct parse
  1028. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1029. // sensitive parse reads both weights as 0 and leaves the original order.
  1030. std::vector<std::string> result;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "application/json;q=0.1,text/html;q=0.9", result));
  1033. ASSERT_EQ(result.size(), 2U);
  1034. EXPECT_EQ(result[0], "text/html");
  1035. EXPECT_EQ(result[1], "application/json");
  1036. std::setlocale(LC_NUMERIC, saved.c_str());
  1037. }
  1038. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1039. std::vector<std::string> result;
  1040. // Invalid quality value (> 1.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1043. // Invalid quality value (< 0.0)
  1044. EXPECT_FALSE(
  1045. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1046. // Invalid quality value (not a number)
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=invalid,application/json", result));
  1049. // A valid numeric prefix does not make the entire quality value valid.
  1050. EXPECT_FALSE(detail::parse_accept_header(
  1051. "text/html;q=0.5junk,application/json", result));
  1052. // Empty quality value
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("text/html;q=,application/json", result));
  1055. // Invalid media type format (no slash and not wildcard)
  1056. EXPECT_FALSE(
  1057. detail::parse_accept_header("invalidtype,application/json", result));
  1058. // Valid cases should still work
  1059. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*/*");
  1062. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "*");
  1065. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "text/*");
  1068. }
  1069. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1070. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1071. // and must not be answered with 400 Bad Request.
  1072. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1073. struct {
  1074. const char *value;
  1075. std::vector<std::string> expected;
  1076. } cases[] = {
  1077. {",application/json", {"application/json"}},
  1078. {"text/html,", {"text/html"}},
  1079. {"text/html,,*/*", {"text/html", "*/*"}},
  1080. // An empty element may be spelled with whitespace in it
  1081. {"text/html, , application/json", {"text/html", "application/json"}},
  1082. // Nothing but empty elements is an empty list, which means the same
  1083. // thing as no Accept header at all
  1084. {",,,", {}},
  1085. // Quality values still apply across ignored empty elements
  1086. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1087. };
  1088. for (const auto &c : cases) {
  1089. std::vector<std::string> result;
  1090. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1091. << "value: " << c.value;
  1092. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1093. }
  1094. // An invalid entry is still rejected when empty elements surround it
  1095. std::vector<std::string> result;
  1096. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1097. }
  1098. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1099. // or ';' inside one does not end the list element or the parameter. Section
  1100. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1101. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1102. struct {
  1103. const char *value;
  1104. std::vector<std::string> expected;
  1105. } cases[] = {
  1106. {"text/html;profile=\"a,b\",application/json",
  1107. {"text/html", "application/json"}},
  1108. // A "q=" inside a quoted value is not the weight
  1109. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1110. {"text/html", "application/json"}},
  1111. // The weight after a quoted value still applies
  1112. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1113. {"application/json", "text/html"}},
  1114. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1115. {"application/json", "text/html"}},
  1116. {"text/html;profile=\"a\\\"b\",application/json",
  1117. {"text/html", "application/json"}},
  1118. // An escaped backslash does not escape the '"' after it
  1119. {"text/html;profile=\"a\\\\\",application/json",
  1120. {"text/html", "application/json"}},
  1121. };
  1122. for (const auto &c : cases) {
  1123. std::vector<std::string> result;
  1124. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1125. << "value: " << c.value;
  1126. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1127. }
  1128. }
  1129. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1130. Server svr;
  1131. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1132. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1133. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1134. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1135. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1136. res.set_content("ok", "text/plain");
  1137. });
  1138. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1139. EXPECT_TRUE(false);
  1140. res.set_content("bad request", "text/plain");
  1141. });
  1142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1143. auto se = detail::scope_exit([&] {
  1144. svr.stop();
  1145. listen_thread.join();
  1146. ASSERT_FALSE(svr.is_running());
  1147. });
  1148. svr.wait_until_ready();
  1149. Client cli("localhost", PORT);
  1150. {
  1151. auto res = cli.Get(
  1152. "/accept_ok",
  1153. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. auto res = cli.Get("/accept_bad_request",
  1159. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1162. }
  1163. }
  1164. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1165. Server svr;
  1166. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1167. res.set_content("ok", "text/plain");
  1168. });
  1169. std::atomic<int> start_count{0};
  1170. std::atomic<bool> running_when_called{false};
  1171. svr.set_start_handler([&]() {
  1172. running_when_called = svr.is_running();
  1173. start_count++;
  1174. });
  1175. auto port = svr.bind_to_any_port(HOST);
  1176. std::thread t([&]() { svr.listen_after_bind(); });
  1177. auto se = detail::scope_exit([&] {
  1178. svr.stop();
  1179. t.join();
  1180. ASSERT_FALSE(svr.is_running());
  1181. });
  1182. svr.wait_until_ready();
  1183. // A successful request proves the accept loop is running, which the start
  1184. // handler precedes; so by now the handler must have run exactly once.
  1185. Client cli(HOST, port);
  1186. cli.set_connection_timeout(std::chrono::seconds(5));
  1187. auto res = cli.Get("/");
  1188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1189. EXPECT_EQ(StatusCode::OK_200, res->status);
  1190. EXPECT_EQ(1, start_count.load());
  1191. EXPECT_TRUE(running_when_called.load());
  1192. }
  1193. TEST(DivideTest, DivideStringTests) {
  1194. auto divide = [](const std::string &str, char d) {
  1195. std::string lhs;
  1196. std::string rhs;
  1197. detail::divide(str, d,
  1198. [&](const char *lhs_data, std::size_t lhs_size,
  1199. const char *rhs_data, std::size_t rhs_size) {
  1200. lhs.assign(lhs_data, lhs_size);
  1201. rhs.assign(rhs_data, rhs_size);
  1202. });
  1203. return std::make_pair(std::move(lhs), std::move(rhs));
  1204. };
  1205. {
  1206. const auto res = divide("", '=');
  1207. EXPECT_EQ(res.first, "");
  1208. EXPECT_EQ(res.second, "");
  1209. }
  1210. {
  1211. const auto res = divide("=", '=');
  1212. EXPECT_EQ(res.first, "");
  1213. EXPECT_EQ(res.second, "");
  1214. }
  1215. {
  1216. const auto res = divide(" ", '=');
  1217. EXPECT_EQ(res.first, " ");
  1218. EXPECT_EQ(res.second, "");
  1219. }
  1220. {
  1221. const auto res = divide("a", '=');
  1222. EXPECT_EQ(res.first, "a");
  1223. EXPECT_EQ(res.second, "");
  1224. }
  1225. {
  1226. const auto res = divide("a=", '=');
  1227. EXPECT_EQ(res.first, "a");
  1228. EXPECT_EQ(res.second, "");
  1229. }
  1230. {
  1231. const auto res = divide("=b", '=');
  1232. EXPECT_EQ(res.first, "");
  1233. EXPECT_EQ(res.second, "b");
  1234. }
  1235. {
  1236. const auto res = divide("a=b", '=');
  1237. EXPECT_EQ(res.first, "a");
  1238. EXPECT_EQ(res.second, "b");
  1239. }
  1240. {
  1241. const auto res = divide("a=b=", '=');
  1242. EXPECT_EQ(res.first, "a");
  1243. EXPECT_EQ(res.second, "b=");
  1244. }
  1245. {
  1246. const auto res = divide("a=b=c", '=');
  1247. EXPECT_EQ(res.first, "a");
  1248. EXPECT_EQ(res.second, "b=c");
  1249. }
  1250. }
  1251. TEST(SplitTest, ParseQueryString) {
  1252. string s = "key1=val1&key2=val2&key3=val3";
  1253. Params dic;
  1254. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1255. [&](const char *b, const char *e) {
  1256. string key, val;
  1257. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1258. if (key.empty()) {
  1259. key.assign(b2, e2);
  1260. } else {
  1261. val.assign(b2, e2);
  1262. }
  1263. });
  1264. dic.emplace(key, val);
  1265. });
  1266. EXPECT_EQ("val1", dic.find("key1")->second);
  1267. EXPECT_EQ("val2", dic.find("key2")->second);
  1268. EXPECT_EQ("val3", dic.find("key3")->second);
  1269. }
  1270. TEST(SplitTest, ParseInvalidQueryTests) {
  1271. {
  1272. string s = " ";
  1273. Params dict;
  1274. detail::parse_query_text(s, dict);
  1275. EXPECT_TRUE(dict.empty());
  1276. }
  1277. {
  1278. string s = " = =";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. }
  1284. TEST(ParseQueryTest, ParseQueryString) {
  1285. {
  1286. std::string s = "key1=val1&key2=val2&key3=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("val1", dic.find("key1")->second);
  1290. EXPECT_EQ("val2", dic.find("key2")->second);
  1291. EXPECT_EQ("val3", dic.find("key3")->second);
  1292. }
  1293. {
  1294. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1295. Params dic;
  1296. detail::parse_query_text(s, dic);
  1297. EXPECT_EQ("", dic.find("key1")->second);
  1298. EXPECT_EQ("val1", dic.find("key2")->second);
  1299. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1300. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1301. }
  1302. }
  1303. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1304. Params dic;
  1305. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1306. dic.emplace("key1", "val1");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1308. dic.emplace("key2", "val2");
  1309. dic.emplace("key3", "val3");
  1310. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1311. }
  1312. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1313. Params params;
  1314. params.emplace("a", "1");
  1315. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1316. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1317. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1318. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1319. // Long enough to overflow the stack when matched with std::regex.
  1320. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1321. EXPECT_EQ("/p?" + long_query + "&a=1",
  1322. append_query_params("/p?" + long_query, params));
  1323. }
  1324. // Joins every entry of a Headers or Params into "key=value " so a whole
  1325. // traversal can be compared in one assertion. Both are instantiations of the
  1326. // same insertion-ordered container, so one helper serves both.
  1327. template <typename Map> static std::string entries_to_string(const Map &m) {
  1328. std::string s;
  1329. for (const auto &entry : m) {
  1330. s += entry.first + "=" + entry.second + " ";
  1331. }
  1332. return s;
  1333. }
  1334. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1335. // Params used to be a std::multimap, which sorted by name and handed the
  1336. // caller's query back alphabetised. A client signing its query string could
  1337. // not reproduce the order it asked for.
  1338. Params dic;
  1339. dic.emplace("zulu", "1");
  1340. dic.emplace("alpha", "2");
  1341. dic.emplace("mike", "3");
  1342. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1343. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1344. }
  1345. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1346. Params dic;
  1347. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1349. }
  1350. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1351. Request req;
  1352. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1353. req.params);
  1354. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag"));
  1356. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1357. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1358. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1359. EXPECT_EQ("", req.get_param_value("tag", 3));
  1360. }
  1361. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1362. // Params shares its container with Headers, which matches field names
  1363. // case-insensitively. Parameter names must not pick that up.
  1364. Params dic;
  1365. dic.emplace("Key", "upper");
  1366. dic.emplace("key", "lower");
  1367. EXPECT_EQ(2U, dic.size());
  1368. EXPECT_EQ(1U, dic.count("Key"));
  1369. EXPECT_EQ(1U, dic.count("key"));
  1370. EXPECT_EQ("upper", dic.find("Key")->second);
  1371. EXPECT_EQ("lower", dic.find("key")->second);
  1372. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1373. }
  1374. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1375. Server svr;
  1376. std::string order;
  1377. svr.Get("/order", [&](const Request &req, Response &res) {
  1378. order = entries_to_string(req.params);
  1379. res.set_content("ok", "text/plain");
  1380. });
  1381. auto port = svr.bind_to_any_port(HOST);
  1382. thread t = thread([&] { svr.listen_after_bind(); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. t.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, port);
  1390. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1391. ASSERT_TRUE(res);
  1392. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1393. }
  1394. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1395. Server svr;
  1396. std::string field_order, file_order;
  1397. svr.Post("/order", [&](const Request &req, Response &res) {
  1398. for (const auto &field : req.form.fields) {
  1399. field_order += field.first + "=" + field.second.content + " ";
  1400. }
  1401. for (const auto &file : req.form.files) {
  1402. file_order += file.first + "=" + file.second.filename + " ";
  1403. }
  1404. res.set_content("ok", "text/plain");
  1405. });
  1406. auto port = svr.bind_to_any_port(HOST);
  1407. thread t = thread([&] { svr.listen_after_bind(); });
  1408. auto se = detail::scope_exit([&] {
  1409. svr.stop();
  1410. t.join();
  1411. ASSERT_FALSE(svr.is_running());
  1412. });
  1413. svr.wait_until_ready();
  1414. UploadFormDataItems items = {
  1415. {"zulu", "1", "", ""},
  1416. {"alpha", "2", "", ""},
  1417. {"mike", "3", "", ""},
  1418. {"zebra", "z", "z.txt", "text/plain"},
  1419. {"apple", "a", "a.txt", "text/plain"},
  1420. };
  1421. Client cli(HOST, port);
  1422. auto res = cli.Post("/order", items);
  1423. ASSERT_TRUE(res);
  1424. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1425. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1426. }
  1427. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1428. Server svr;
  1429. std::vector<std::string> values;
  1430. std::string first, second, out_of_range, order;
  1431. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1432. values = req.form.get_fields("tag");
  1433. first = req.form.get_field("tag", 0);
  1434. second = req.form.get_field("tag", 1);
  1435. out_of_range = req.form.get_field("tag", 2);
  1436. for (const auto &field : req.form.fields) {
  1437. order += field.first + "=" + field.second.content + " ";
  1438. }
  1439. res.set_content("ok", "text/plain");
  1440. });
  1441. auto port = svr.bind_to_any_port(HOST);
  1442. thread t = thread([&] { svr.listen_after_bind(); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. t.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1450. // not adjacent in the container.
  1451. UploadFormDataItems items = {
  1452. {"tag", "first", "", ""},
  1453. {"other", "x", "", ""},
  1454. {"tag", "second", "", ""},
  1455. };
  1456. Client cli(HOST, port);
  1457. auto res = cli.Post("/repeated", items);
  1458. ASSERT_TRUE(res);
  1459. ASSERT_EQ(2U, values.size());
  1460. EXPECT_EQ("first", values[0]);
  1461. EXPECT_EQ("second", values[1]);
  1462. EXPECT_EQ("first", first);
  1463. EXPECT_EQ("second", second);
  1464. // std::multimap already kept entries sharing a name in insertion order, so
  1465. // everything above passes without this change too. The whole traversal is
  1466. // what tells the two apart: sorting by name would hoist "other" to the front
  1467. // and the two "tag" parts would end up adjacent.
  1468. EXPECT_EQ("tag=first other=x tag=second ", order);
  1469. // Advancing past the last entry of a name used to run off the container;
  1470. // the container's saturating increment makes it return the default instead.
  1471. EXPECT_EQ("", out_of_range);
  1472. }
  1473. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1474. Server svr;
  1475. std::string file_names;
  1476. svr.Post("/upload", [&](const Request &req, Response &res) {
  1477. for (const auto &file : req.form.files) {
  1478. file_names += file.first + "|" + file.second.filename + " ";
  1479. }
  1480. res.set_content("ok", "text/plain");
  1481. });
  1482. auto port = svr.bind_to_any_port(HOST);
  1483. thread t = thread([&] { svr.listen_after_bind(); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. t.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. // A trailing backslash would otherwise escape the closing quote.
  1491. UploadFormDataItems items = {
  1492. {"dir\\", "x", "a.txt", "text/plain"},
  1493. {"b", "y", "a\\\\b.txt", "text/plain"},
  1494. };
  1495. Client cli(HOST, port);
  1496. auto res = cli.Post("/upload", items);
  1497. ASSERT_TRUE(res);
  1498. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1499. }
  1500. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1501. // Server::read_content() keeps a FormFields::iterator alive across the
  1502. // content callbacks that fill the part it points at. The container is
  1503. // vector-backed, so a later emplace can reallocate and invalidate an older
  1504. // iterator; 64 parts grow the vector through seven reallocations, which
  1505. // checks that every part's content still lands in its own entry.
  1506. const size_t part_count = 64;
  1507. // One formula for both the parts sent and the values expected back, so the
  1508. // two cannot drift apart.
  1509. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1510. auto content_of = [](size_t i) {
  1511. return std::string(64, static_cast<char>('a' + (i % 26)));
  1512. };
  1513. Server svr;
  1514. std::vector<std::pair<std::string, std::string>> received;
  1515. svr.Post("/many", [&](const Request &req, Response &res) {
  1516. for (const auto &field : req.form.fields) {
  1517. received.emplace_back(field.first, field.second.content);
  1518. }
  1519. res.set_content("ok", "text/plain");
  1520. });
  1521. auto port = svr.bind_to_any_port(HOST);
  1522. thread t = thread([&] { svr.listen_after_bind(); });
  1523. auto se = detail::scope_exit([&] {
  1524. svr.stop();
  1525. t.join();
  1526. ASSERT_FALSE(svr.is_running());
  1527. });
  1528. svr.wait_until_ready();
  1529. UploadFormDataItems items;
  1530. for (size_t i = 0; i < part_count; i++) {
  1531. items.push_back({name_of(i), content_of(i), "", ""});
  1532. }
  1533. Client cli(HOST, port);
  1534. auto res = cli.Post("/many", items);
  1535. ASSERT_TRUE(res);
  1536. ASSERT_EQ(part_count, received.size());
  1537. for (size_t i = 0; i < part_count; i++) {
  1538. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1539. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1540. }
  1541. }
  1542. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1543. string content_type = "multipart/form-data; boundary=something";
  1544. string boundary;
  1545. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(boundary, "something");
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1550. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1551. string boundary;
  1552. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1553. EXPECT_TRUE(ret);
  1554. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1557. string content_type =
  1558. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1559. string boundary;
  1560. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1561. EXPECT_TRUE(ret);
  1562. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1565. string content_type =
  1566. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1567. string boundary;
  1568. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1569. EXPECT_TRUE(ret);
  1570. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1571. }
  1572. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1573. const string boundary(70, 'a');
  1574. string content_type = "multipart/form-data; boundary=" + boundary;
  1575. string parsed;
  1576. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1577. EXPECT_TRUE(ret);
  1578. EXPECT_EQ(parsed, boundary);
  1579. }
  1580. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1581. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1582. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1583. string parsed;
  1584. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1585. EXPECT_FALSE(ret);
  1586. }
  1587. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1588. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1589. // is 72 characters on the wire and still valid.
  1590. const string boundary(70, 'a');
  1591. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1592. string parsed;
  1593. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1594. EXPECT_EQ(parsed, boundary);
  1595. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1596. parsed.clear();
  1597. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1598. }
  1599. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1600. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1601. // The parameter parser must not treat that '=' as the key/value separator.
  1602. string content_type =
  1603. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1604. "charset=UTF-8";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1608. }
  1609. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1610. // A ';' inside the quoted-string is part of the value, not a parameter
  1611. // separator, so it must not truncate the boundary.
  1612. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1613. string parsed;
  1614. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1615. EXPECT_EQ(parsed, "a;b");
  1616. }
  1617. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1621. EXPECT_EQ("a\\b", parsed);
  1622. EXPECT_TRUE(detail::parse_multipart_boundary(
  1623. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1624. EXPECT_EQ("a\"b", parsed);
  1625. }
  1626. TEST(ParseDispositionParamsTest, QuotedValues) {
  1627. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1628. // ';' and '=' are ordinary characters inside one.
  1629. struct {
  1630. const char *value;
  1631. std::vector<std::pair<const char *, const char *>> expected;
  1632. } cases[] = {
  1633. {"name=\"file1\"; filename=\"a.txt\"",
  1634. {{"name", "file1"}, {"filename", "a.txt"}}},
  1635. // Whitespace around '=' and ';' is still trimmed
  1636. {"name=\"file2\" ;filename = \"a.html\"",
  1637. {{"name", "file2"}, {"filename", "a.html"}}},
  1638. // '=' inside the value used to leave only the text after the last one
  1639. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1640. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1641. {"name=\"x=y\"", {{"name", "x=y"}}},
  1642. // ';' inside the value used to truncate the pair and leave a bogus one
  1643. {"name=\"file3\"; filename=\"a;b.txt\"",
  1644. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1645. // An unquoted value keeps working, and so does filename*
  1646. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1647. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1648. // A parameter with no key is dropped rather than turned into one whose
  1649. // key is the value
  1650. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1651. // An escaped quote does not end the value
  1652. {"name=\"a\\\"; filename=evil.php\"",
  1653. {{"name", "a\"; filename=evil.php"}}},
  1654. // Other backslashes, as in a Windows path, are kept
  1655. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1656. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1657. };
  1658. for (const auto &c : cases) {
  1659. Params params;
  1660. detail::parse_disposition_params(c.value, params);
  1661. for (const auto &kv : c.expected) {
  1662. auto it = params.find(kv.first);
  1663. ASSERT_NE(it, params.end())
  1664. << "value: " << c.value << ", key: " << kv.first;
  1665. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1666. }
  1667. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1668. }
  1669. }
  1670. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1671. Server svr;
  1672. std::string filename;
  1673. std::string content;
  1674. svr.Post("/upload", [&](const Request &req, Response &) {
  1675. const auto &file = req.form.get_file("file");
  1676. filename = file.filename;
  1677. content = file.content;
  1678. });
  1679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1680. auto se = detail::scope_exit([&] {
  1681. svr.stop();
  1682. thread.join();
  1683. ASSERT_FALSE(svr.is_running());
  1684. });
  1685. svr.wait_until_ready();
  1686. std::string body = "--B\r\n"
  1687. "Content-Disposition: form-data; name=\"file\"; "
  1688. "filename=\"a.txt\"\r\n"
  1689. "Content-Type: text/plain\r\n"
  1690. "\r\n"
  1691. "hello\r\n"
  1692. "--B--\r\n";
  1693. Client cli(HOST, PORT);
  1694. auto res = cli.Post(
  1695. "/upload",
  1696. [&](size_t offset, DataSink &sink) {
  1697. if (offset < body.size()) {
  1698. sink.write(&body[offset], 1);
  1699. } else {
  1700. sink.done();
  1701. }
  1702. return true;
  1703. },
  1704. "multipart/form-data; boundary=B");
  1705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1706. EXPECT_EQ(StatusCode::OK_200, res->status);
  1707. EXPECT_EQ("a.txt", filename);
  1708. EXPECT_EQ("hello", content);
  1709. }
  1710. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1711. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1712. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1713. Server svr;
  1714. std::string field_value, file_name, file_filename;
  1715. bool has_field = false, has_file = false;
  1716. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1717. has_field = req.form.has_field("x=y");
  1718. field_value = req.form.get_field("x=y");
  1719. has_file = req.form.has_file("file1");
  1720. const auto &file = req.form.get_file("file1");
  1721. file_name = file.name;
  1722. file_filename = file.filename;
  1723. res.set_content("ok", "text/plain");
  1724. });
  1725. auto port = svr.bind_to_any_port(HOST);
  1726. thread t = thread([&] { svr.listen_after_bind(); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. t.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. UploadFormDataItems items = {
  1734. {"x=y", "field-value", "", ""},
  1735. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1736. };
  1737. Client cli(HOST, port);
  1738. auto res = cli.Post("/quoted", items);
  1739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1740. ASSERT_EQ(StatusCode::OK_200, res->status);
  1741. EXPECT_TRUE(has_field);
  1742. EXPECT_EQ("field-value", field_value);
  1743. EXPECT_TRUE(has_file);
  1744. EXPECT_EQ("file1", file_name);
  1745. EXPECT_EQ("a;b=report.pdf", file_filename);
  1746. }
  1747. TEST(GetHeaderValueTest, DefaultValue) {
  1748. Headers headers = {{"Dummy", "Dummy"}};
  1749. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1750. EXPECT_STREQ("text/plain", val);
  1751. }
  1752. TEST(GetHeaderValueTest, DefaultValueInt) {
  1753. Headers headers = {{"Dummy", "Dummy"}};
  1754. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1755. EXPECT_EQ(100ull, val);
  1756. }
  1757. TEST(GetHeaderValueTest, RegularValue) {
  1758. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1759. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1760. EXPECT_STREQ("text/html", val);
  1761. }
  1762. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1763. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1764. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1765. EXPECT_STREQ("text/html", val);
  1766. }
  1767. TEST(GetHeaderValueTest, SetContent) {
  1768. Response res;
  1769. res.set_content("html", "text/html");
  1770. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1771. res.set_content("text", "text/plain");
  1772. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1773. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueInt) {
  1776. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1778. EXPECT_EQ(100ull, val);
  1779. }
  1780. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1781. Headers headers = {{"Content-Length", "x"}};
  1782. auto is_invalid_value = false;
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1784. is_invalid_value);
  1785. EXPECT_EQ(0ull, val);
  1786. EXPECT_TRUE(is_invalid_value);
  1787. }
  1788. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1789. // An all-digit value that overflows size_t must be reported as invalid, not
  1790. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1791. // a large length to a small one on 32-bit builds, leaving the framing length
  1792. // wrong while is_invalid_value stayed false.
  1793. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1794. auto is_invalid_value = false;
  1795. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1796. is_invalid_value);
  1797. EXPECT_TRUE(is_invalid_value);
  1798. // A well-formed length is unaffected.
  1799. Headers ok = {{"Content-Length", "1234"}};
  1800. is_invalid_value = false;
  1801. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_EQ(1234ull, val);
  1804. EXPECT_FALSE(is_invalid_value);
  1805. }
  1806. TEST(GetHeaderValueTest, Range) {
  1807. {
  1808. Headers headers = {make_range_header({{1, -1}})};
  1809. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1810. EXPECT_STREQ("bytes=1-", val);
  1811. }
  1812. {
  1813. Headers headers = {make_range_header({{-1, 1}})};
  1814. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1815. EXPECT_STREQ("bytes=-1", val);
  1816. }
  1817. {
  1818. Headers headers = {make_range_header({{1, 10}})};
  1819. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1820. EXPECT_STREQ("bytes=1-10", val);
  1821. }
  1822. {
  1823. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1824. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1825. EXPECT_STREQ("bytes=1-10, 100-", val);
  1826. }
  1827. {
  1828. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1829. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1830. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1831. }
  1832. {
  1833. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1834. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1835. EXPECT_STREQ("bytes=0-0, -1", val);
  1836. }
  1837. }
  1838. TEST(BearerTokenAuthTest, SchemeValidation) {
  1839. // A value shorter than "Bearer " must not throw from the fixed-length
  1840. // substr, and a non-Bearer scheme must not be reported as a token.
  1841. struct {
  1842. const char *value;
  1843. const char *expected;
  1844. } cases[] = {
  1845. {"x", ""},
  1846. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1847. {"Bearer abc123", "abc123"},
  1848. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1849. };
  1850. for (const auto &c : cases) {
  1851. Request req;
  1852. req.set_header("Authorization", c.value);
  1853. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1854. }
  1855. }
  1856. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1857. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1858. // to depend on the standard library (libstdc++ handed back duplicates in
  1859. // reverse insertion order, libc++ in insertion order).
  1860. Request req;
  1861. req.set_header("Accept-Encoding", "gzip");
  1862. req.set_header("Accept-Encoding", "deflate");
  1863. req.set_header("Accept-Encoding", "br");
  1864. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1866. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1867. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1868. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1869. }
  1870. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1871. Request req;
  1872. req.set_header("X-Test", "only");
  1873. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1875. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1876. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1877. }
  1878. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1879. Request req;
  1880. req.set_header("X-First", "1");
  1881. req.set_header("X-Test", "2");
  1882. req.params.emplace("first", "1");
  1883. req.params.emplace("test", "2");
  1884. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1885. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1886. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1887. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1888. // The second one is negative when read as a signed value
  1889. const auto max_id = (std::numeric_limits<size_t>::max)();
  1890. for (auto id : {max_id / 2, max_id}) {
  1891. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1892. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1893. EXPECT_EQ("", req.get_param_value("test", id));
  1894. EXPECT_EQ("", req.form.get_field("test", id));
  1895. EXPECT_EQ("", req.form.get_file("test", id).content);
  1896. }
  1897. }
  1898. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1899. Headers headers;
  1900. headers.emplace("Host", "example.com");
  1901. headers.emplace("Accept-Encoding", "gzip");
  1902. headers.emplace("User-Agent", "test");
  1903. headers.emplace("Accept-Encoding", "deflate");
  1904. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1905. "Accept-Encoding=deflate ",
  1906. entries_to_string(headers));
  1907. }
  1908. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1909. Headers headers = {{"Content-Type", "text/html"},
  1910. {"CONTENT-TYPE", "text/xml"}};
  1911. EXPECT_EQ(2U, headers.count("content-type"));
  1912. auto it = headers.find("content-type");
  1913. ASSERT_TRUE(it != headers.end());
  1914. EXPECT_EQ("text/html", it->second);
  1915. }
  1916. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1917. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1918. // drop only those fields and leave everything positioned between them.
  1919. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1920. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1921. auto rng = headers.equal_range("a");
  1922. headers.erase(rng.first, rng.second);
  1923. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1924. }
  1925. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1926. Headers headers = {
  1927. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1928. EXPECT_EQ(3U, headers.erase("A"));
  1929. EXPECT_EQ(0U, headers.count("A"));
  1930. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1933. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1934. headers.emplace_front("Host", "example.com");
  1935. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1936. entries_to_string(headers));
  1937. }
  1938. TEST(ParseHeaderValueTest, Range) {
  1939. {
  1940. Ranges ranges;
  1941. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1944. }
  1945. {
  1946. Ranges ranges;
  1947. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1948. EXPECT_TRUE(ret);
  1949. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1960. EXPECT_FALSE(ret);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1965. EXPECT_TRUE(ret);
  1966. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret =
  1971. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1990. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1991. EXPECT_FALSE(
  1992. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1993. EXPECT_TRUE(ranges.empty());
  1994. }
  1995. {
  1996. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1997. // remainder of the representation, so it stays accepted.
  1998. Ranges ranges;
  1999. auto ret =
  2000. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2001. EXPECT_TRUE(ret);
  2002. ASSERT_EQ(1u, ranges.size());
  2003. EXPECT_EQ(0, ranges[0].first);
  2004. EXPECT_EQ(-1, ranges[0].second);
  2005. }
  2006. // RFC 9110 14.1: range unit names are case-insensitive.
  2007. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2008. Ranges ranges;
  2009. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2010. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2011. }
  2012. }
  2013. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding", "gzip");
  2016. Response res;
  2017. res.set_header("Content-Type", "text/plain");
  2018. auto ret = detail::encoding_type(req, res);
  2019. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2020. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2021. #else
  2022. EXPECT_TRUE(ret == detail::EncodingType::None);
  2023. #endif
  2024. }
  2025. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2033. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2034. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2035. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2036. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2037. #else
  2038. EXPECT_TRUE(ret == detail::EncodingType::None);
  2039. #endif
  2040. }
  2041. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2042. Request req;
  2043. req.set_header("Accept-Encoding",
  2044. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2045. Response res;
  2046. res.set_header("Content-Type", "text/plain");
  2047. auto ret = detail::encoding_type(req, res);
  2048. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2050. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2052. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2053. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2054. #else
  2055. EXPECT_TRUE(ret == detail::EncodingType::None);
  2056. #endif
  2057. }
  2058. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2059. // All supported encodings rejected with q=0 should return None
  2060. Request req;
  2061. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2062. Response res;
  2063. res.set_header("Content-Type", "text/plain");
  2064. auto ret = detail::encoding_type(req, res);
  2065. EXPECT_TRUE(ret == detail::EncodingType::None);
  2066. }
  2067. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2068. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2069. Request req;
  2070. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2071. Response res;
  2072. res.set_header("Content-Type", "text/plain");
  2073. auto ret = detail::encoding_type(req, res);
  2074. EXPECT_TRUE(ret == detail::EncodingType::None);
  2075. }
  2076. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2077. Request req;
  2078. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2079. Response res;
  2080. res.set_header("Content-Type", "text/plain");
  2081. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2082. }
  2083. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2084. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2085. Request req;
  2086. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2087. Response res;
  2088. res.set_header("Content-Type", "text/plain");
  2089. auto ret = detail::encoding_type(req, res);
  2090. EXPECT_TRUE(ret == detail::EncodingType::None);
  2091. }
  2092. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2093. // RFC 7231: Accept-Encoding values are case-insensitive
  2094. Request req;
  2095. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2096. Response res;
  2097. res.set_header("Content-Type", "text/plain");
  2098. auto ret = detail::encoding_type(req, res);
  2099. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2100. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2101. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2102. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2103. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2104. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2105. #else
  2106. EXPECT_TRUE(ret == detail::EncodingType::None);
  2107. #endif
  2108. }
  2109. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2110. // q value should determine priority, not hardcoded order
  2111. Request req;
  2112. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2113. Response res;
  2114. res.set_header("Content-Type", "text/plain");
  2115. auto ret = detail::encoding_type(req, res);
  2116. // gzip has highest q=1.0, so it should be selected even though
  2117. // br and zstd are also supported
  2118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2120. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2121. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2122. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2123. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2124. #else
  2125. EXPECT_TRUE(ret == detail::EncodingType::None);
  2126. #endif
  2127. }
  2128. TEST(BufferStreamTest, read) {
  2129. detail::BufferStream strm1;
  2130. Stream &strm = strm1;
  2131. EXPECT_EQ(5, strm.write("hello"));
  2132. char buf[512];
  2133. EXPECT_EQ(2, strm.read(buf, 2));
  2134. EXPECT_EQ('h', buf[0]);
  2135. EXPECT_EQ('e', buf[1]);
  2136. EXPECT_EQ(2, strm.read(buf, 2));
  2137. EXPECT_EQ('l', buf[0]);
  2138. EXPECT_EQ('l', buf[1]);
  2139. EXPECT_EQ(1, strm.read(buf, 1));
  2140. EXPECT_EQ('o', buf[0]);
  2141. EXPECT_EQ(0, strm.read(buf, 1));
  2142. }
  2143. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2144. auto host = "www.httpwatch.com";
  2145. auto ip = hosted_at(host);
  2146. EXPECT_EQ("23.96.13.243", ip);
  2147. std::vector<std::string> addrs;
  2148. hosted_at(host, addrs);
  2149. EXPECT_EQ(1u, addrs.size());
  2150. }
  2151. #if 0 // It depends on each test environment...
  2152. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2153. auto host = "www.youtube.com";
  2154. std::vector<std::string> addrs;
  2155. hosted_at(host, addrs);
  2156. EXPECT_EQ(20u, addrs.size());
  2157. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2158. EXPECT_TRUE(it != addrs.end());
  2159. }
  2160. #endif
  2161. class ChunkedEncodingTest : public ::testing::Test {
  2162. protected:
  2163. ChunkedEncodingTest()
  2164. : cli_(HOST, PORT)
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. ,
  2167. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2168. #endif
  2169. {
  2170. cli_.set_connection_timeout(2);
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. cli_.enable_server_certificate_verification(false);
  2173. #endif
  2174. }
  2175. virtual void SetUp() {
  2176. read_file("./image.jpg", image_data_);
  2177. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2178. res.set_content("Hello World!", "text/plain");
  2179. });
  2180. svr_.Get(
  2181. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2182. res.set_chunked_content_provider(
  2183. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2184. size_t remaining = image_data_.size() - offset;
  2185. if (remaining == 0) {
  2186. sink.done();
  2187. } else {
  2188. constexpr size_t CHUNK_SIZE = 1024;
  2189. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2190. sink.write(&image_data_[offset], send_size);
  2191. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2192. }
  2193. return true;
  2194. });
  2195. });
  2196. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2197. svr_.wait_until_ready();
  2198. }
  2199. virtual void TearDown() {
  2200. svr_.stop();
  2201. if (!request_threads_.empty()) {
  2202. std::this_thread::sleep_for(std::chrono::seconds(1));
  2203. for (auto &t : request_threads_) {
  2204. t.join();
  2205. }
  2206. }
  2207. t_.join();
  2208. }
  2209. #ifdef CPPHTTPLIB_SSL_ENABLED
  2210. SSLClient cli_;
  2211. SSLServer svr_;
  2212. #else
  2213. Client cli_;
  2214. Server svr_;
  2215. #endif
  2216. thread t_;
  2217. std::vector<thread> request_threads_;
  2218. std::string image_data_;
  2219. };
  2220. TEST_F(ChunkedEncodingTest, NormalGet) {
  2221. auto res = cli_.Get("/chunked");
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. std::string out;
  2224. read_file("./image.jpg", out);
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(out, res->body);
  2227. }
  2228. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2229. std::string body;
  2230. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2231. body.append(data, data_length);
  2232. return true;
  2233. });
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get(
  2243. "/chunked",
  2244. [&](const Response &response) {
  2245. EXPECT_EQ(StatusCode::OK_200, response.status);
  2246. return true;
  2247. },
  2248. [&](const char *data, size_t data_length) {
  2249. body.append(data, data_length);
  2250. return true;
  2251. });
  2252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2253. std::string out;
  2254. read_file("./image.jpg", out);
  2255. EXPECT_EQ(StatusCode::OK_200, res->status);
  2256. EXPECT_EQ(out, body);
  2257. }
  2258. TEST(RangeTest, FromHTTPBin_Online) {
  2259. auto host = "httpbingo.org";
  2260. auto path = std::string{"/range/32"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(5);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. }
  2275. {
  2276. Headers headers = {make_range_header({{1, -1}})};
  2277. auto res = cli.Get(path, headers);
  2278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2279. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2281. }
  2282. {
  2283. Headers headers = {make_range_header({{1, 10}})};
  2284. auto res = cli.Get(path, headers);
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("bcdefghijk", res->body);
  2287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2288. }
  2289. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2290. // entire resource, while the original httpbin returned 200. Both are
  2291. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2292. {
  2293. Headers headers = {make_range_header({{0, 31}})};
  2294. auto res = cli.Get(path, headers);
  2295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2296. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2297. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2298. res->status == StatusCode::PartialContent_206);
  2299. }
  2300. {
  2301. Headers headers = {make_range_header({{0, -1}})};
  2302. auto res = cli.Get(path, headers);
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2305. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2306. res->status == StatusCode::PartialContent_206);
  2307. }
  2308. // go-httpbin returns 206 with clamped range for over-range requests,
  2309. // while the original httpbin returned 416. Both behaviors are observed
  2310. // in real servers, so we only verify the request succeeds.
  2311. {
  2312. Headers headers = {make_range_header({{0, 32}})};
  2313. auto res = cli.Get(path, headers);
  2314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2315. }
  2316. }
  2317. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2318. auto host = "unresolvableaddress.local";
  2319. auto path = std::string{"/"};
  2320. #ifdef CPPHTTPLIB_SSL_ENABLED
  2321. auto port = 443;
  2322. SSLClient cli(host, port);
  2323. #else
  2324. auto port = 80;
  2325. Client cli(host, port);
  2326. #endif
  2327. cli.set_connection_timeout(1);
  2328. {
  2329. auto res = cli.Get(path);
  2330. ASSERT_FALSE(res);
  2331. }
  2332. std::this_thread::sleep_for(std::chrono::seconds(8));
  2333. }
  2334. #if defined(__linux__) && defined(__GLIBC__) && \
  2335. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2336. // Forward declaration: in split builds split.py strips `inline` and moves the
  2337. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2338. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2339. // against the symbol in both header-only and split builds.
  2340. namespace httplib {
  2341. namespace detail {
  2342. int getaddrinfo_with_timeout(const char *node, const char *service,
  2343. const struct addrinfo *hints,
  2344. struct addrinfo **res, time_t timeout_sec);
  2345. } // namespace detail
  2346. } // namespace httplib
  2347. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2348. //
  2349. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2350. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2351. // gai_suspend() call hits the connection timeout the function calls
  2352. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2353. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2354. // still alive and still references the now-destroyed stack frame.
  2355. //
  2356. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2357. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2358. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2359. // and runs them in a container.
  2360. namespace {
  2361. bool should_run_issue_2431_tests() {
  2362. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2363. return v && *v && std::string(v) != "0";
  2364. }
  2365. std::string unique_unresolvable_host(int n) {
  2366. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2367. // glibc still asks the configured nameserver — which is exactly the path
  2368. // we want to exercise. A unique label per call avoids the resolver cache.
  2369. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2370. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2371. std::to_string(n) + ".invalid";
  2372. }
  2373. } // namespace
  2374. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2375. if (!should_run_issue_2431_tests()) {
  2376. GTEST_SKIP()
  2377. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2378. }
  2379. for (int i = 0; i < 8; ++i) {
  2380. struct addrinfo hints;
  2381. memset(&hints, 0, sizeof(hints));
  2382. hints.ai_family = AF_UNSPEC;
  2383. hints.ai_socktype = SOCK_STREAM;
  2384. auto host = unique_unresolvable_host(i);
  2385. struct addrinfo *result = nullptr;
  2386. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2387. &result, /*timeout_sec=*/1);
  2388. if (rc == 0 && result) { freeaddrinfo(result); }
  2389. }
  2390. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2391. // stack region they still believe holds their gaicb.
  2392. std::this_thread::sleep_for(std::chrono::seconds(3));
  2393. }
  2394. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2395. if (!should_run_issue_2431_tests()) {
  2396. GTEST_SKIP()
  2397. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2398. }
  2399. std::atomic<bool> stop{false};
  2400. std::vector<std::thread> threads;
  2401. for (int t = 0; t < 8; ++t) {
  2402. threads.emplace_back([t, &stop] {
  2403. int i = 0;
  2404. while (!stop.load(std::memory_order_relaxed)) {
  2405. struct addrinfo hints;
  2406. memset(&hints, 0, sizeof(hints));
  2407. hints.ai_family = AF_UNSPEC;
  2408. hints.ai_socktype = SOCK_STREAM;
  2409. auto host = unique_unresolvable_host(t * 100000 + i++);
  2410. struct addrinfo *result = nullptr;
  2411. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2412. &result, /*timeout_sec=*/1);
  2413. if (rc == 0 && result) { freeaddrinfo(result); }
  2414. }
  2415. });
  2416. }
  2417. std::this_thread::sleep_for(std::chrono::seconds(8));
  2418. stop.store(true, std::memory_order_relaxed);
  2419. for (auto &th : threads) {
  2420. th.join();
  2421. }
  2422. std::this_thread::sleep_for(std::chrono::seconds(3));
  2423. }
  2424. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2425. if (!should_run_issue_2431_tests()) {
  2426. GTEST_SKIP()
  2427. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2428. }
  2429. std::atomic<bool> stop{false};
  2430. std::vector<std::thread> threads;
  2431. for (int t = 0; t < 8; ++t) {
  2432. threads.emplace_back([t, &stop] {
  2433. int i = 0;
  2434. while (!stop.load(std::memory_order_relaxed)) {
  2435. auto host = unique_unresolvable_host(t * 100000 + i++);
  2436. Client cli(host, 80);
  2437. cli.set_connection_timeout(1, 0);
  2438. cli.set_read_timeout(1, 0);
  2439. cli.set_write_timeout(1, 0);
  2440. (void)cli.Get("/");
  2441. }
  2442. });
  2443. }
  2444. std::this_thread::sleep_for(std::chrono::seconds(8));
  2445. stop.store(true, std::memory_order_relaxed);
  2446. for (auto &th : threads) {
  2447. th.join();
  2448. }
  2449. std::this_thread::sleep_for(std::chrono::seconds(3));
  2450. }
  2451. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2452. TEST(ConnectionErrorTest, InvalidHost) {
  2453. auto host = "-abcde.com";
  2454. #ifdef CPPHTTPLIB_SSL_ENABLED
  2455. auto port = 443;
  2456. SSLClient cli(host, port);
  2457. #else
  2458. auto port = 80;
  2459. Client cli(host, port);
  2460. #endif
  2461. cli.set_connection_timeout(std::chrono::seconds(2));
  2462. auto res = cli.Get("/");
  2463. ASSERT_TRUE(!res);
  2464. EXPECT_EQ(Error::Connection, res.error());
  2465. }
  2466. TEST(ConnectionErrorTest, InvalidHost2) {
  2467. auto host = "httpcan.org/";
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. SSLClient cli(host);
  2470. #else
  2471. Client cli(host);
  2472. #endif
  2473. cli.set_connection_timeout(std::chrono::seconds(2));
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(!res);
  2476. EXPECT_EQ(Error::Connection, res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2479. auto host = "httpcan.org/";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. SSLClient cli(host);
  2482. #else
  2483. Client cli(host);
  2484. #endif
  2485. cli.set_connection_timeout(std::chrono::seconds(2));
  2486. auto res = cli.Get("/");
  2487. ASSERT_TRUE(!res);
  2488. stringstream s;
  2489. s << "error code: " << res.error();
  2490. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2491. }
  2492. TEST(ConnectionErrorTest, InvalidPort) {
  2493. auto host = "localhost";
  2494. auto port = 44380;
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host, port);
  2497. #else
  2498. Client cli(host, port);
  2499. #endif
  2500. cli.set_connection_timeout(std::chrono::seconds(2));
  2501. auto res = cli.Get("/");
  2502. ASSERT_TRUE(!res);
  2503. EXPECT_TRUE(Error::Connection == res.error() ||
  2504. Error::ConnectionTimeout == res.error());
  2505. }
  2506. TEST(ConnectionErrorTest, Timeout_Online) {
  2507. auto host = "google.com";
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. auto port = 44380;
  2510. SSLClient cli(host, port);
  2511. #else
  2512. auto port = 8080;
  2513. Client cli(host, port);
  2514. #endif
  2515. cli.set_connection_timeout(std::chrono::seconds(2));
  2516. // only probe one address type so that the error reason
  2517. // correlates to the timed-out IPv4, not the unsupported
  2518. // IPv6 connection attempt
  2519. cli.set_address_family(AF_INET);
  2520. auto res = cli.Get("/");
  2521. ASSERT_TRUE(!res);
  2522. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2523. }
  2524. TEST(CancelTest, NoCancel_Online) {
  2525. auto host = "httpbingo.org";
  2526. auto path = std::string{"/range/32"};
  2527. #ifdef CPPHTTPLIB_SSL_ENABLED
  2528. auto port = 443;
  2529. SSLClient cli(host, port);
  2530. #else
  2531. auto port = 80;
  2532. Client cli(host, port);
  2533. #endif
  2534. cli.set_connection_timeout(std::chrono::seconds(5));
  2535. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2537. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2538. EXPECT_EQ(StatusCode::OK_200, res->status);
  2539. }
  2540. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2541. // Use /bytes with a large payload so that the DownloadProgress callback
  2542. // (which only fires for Content-Length responses) is invoked before the
  2543. // entire body is received, giving cancellation a chance to fire.
  2544. auto host = "httpbingo.org";
  2545. auto path = std::string{"/bytes/524288"};
  2546. #ifdef CPPHTTPLIB_SSL_ENABLED
  2547. auto port = 443;
  2548. SSLClient cli(host, port);
  2549. #else
  2550. auto port = 80;
  2551. Client cli(host, port);
  2552. #endif
  2553. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2554. cli.set_connection_timeout(std::chrono::seconds(5));
  2555. ASSERT_TRUE(!res);
  2556. EXPECT_EQ(Error::Canceled, res.error());
  2557. }
  2558. TEST(CancelTest, WithCancelLargePayload_Online) {
  2559. auto host = "httpbingo.org";
  2560. auto path = std::string{"/bytes/524288"};
  2561. #ifdef CPPHTTPLIB_SSL_ENABLED
  2562. auto port = 443;
  2563. SSLClient cli(host, port);
  2564. #else
  2565. auto port = 80;
  2566. Client cli(host, port);
  2567. #endif
  2568. cli.set_connection_timeout(std::chrono::seconds(5));
  2569. uint32_t count = 0;
  2570. auto res =
  2571. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2572. ASSERT_TRUE(!res);
  2573. EXPECT_EQ(Error::Canceled, res.error());
  2574. }
  2575. TEST(CancelTest, NoCancelPost) {
  2576. Server svr;
  2577. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2578. res.set_content("Hello World!", "text/plain");
  2579. });
  2580. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2581. auto se = detail::scope_exit([&] {
  2582. svr.stop();
  2583. thread.join();
  2584. ASSERT_FALSE(svr.is_running());
  2585. });
  2586. svr.wait_until_ready();
  2587. Client cli(HOST, PORT);
  2588. cli.set_connection_timeout(std::chrono::seconds(5));
  2589. auto res =
  2590. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2591. "application/json", [](uint64_t, uint64_t) { return true; });
  2592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2593. EXPECT_EQ("Hello World!", res->body);
  2594. EXPECT_EQ(StatusCode::OK_200, res->status);
  2595. }
  2596. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2597. Server svr;
  2598. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2599. res.set_content("Hello World!", "text/plain");
  2600. });
  2601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2602. auto se = detail::scope_exit([&] {
  2603. svr.stop();
  2604. thread.join();
  2605. ASSERT_FALSE(svr.is_running());
  2606. });
  2607. svr.wait_until_ready();
  2608. Client cli(HOST, PORT);
  2609. cli.set_connection_timeout(std::chrono::seconds(5));
  2610. auto res =
  2611. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2612. "application/json", [](uint64_t, uint64_t) { return false; });
  2613. ASSERT_TRUE(!res);
  2614. EXPECT_EQ(Error::Canceled, res.error());
  2615. }
  2616. TEST(CancelTest, WithCancelLargePayloadPost) {
  2617. Server svr;
  2618. svr.set_payload_max_length(200 * 1024 * 1024);
  2619. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2620. res.set_content(LARGE_DATA, "text/plain");
  2621. });
  2622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2623. auto se = detail::scope_exit([&] {
  2624. svr.stop();
  2625. thread.join();
  2626. ASSERT_FALSE(svr.is_running());
  2627. });
  2628. svr.wait_until_ready();
  2629. Client cli(HOST, PORT);
  2630. cli.set_payload_max_length(200 * 1024 * 1024);
  2631. cli.set_connection_timeout(std::chrono::seconds(5));
  2632. auto res =
  2633. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2634. "application/json", [](uint64_t, uint64_t) { return false; });
  2635. ASSERT_TRUE(!res);
  2636. EXPECT_EQ(Error::Canceled, res.error());
  2637. }
  2638. TEST(CancelTest, NoCancelPut) {
  2639. Server svr;
  2640. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2641. res.set_content("Hello World!", "text/plain");
  2642. });
  2643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2644. auto se = detail::scope_exit([&] {
  2645. svr.stop();
  2646. thread.join();
  2647. ASSERT_FALSE(svr.is_running());
  2648. });
  2649. svr.wait_until_ready();
  2650. Client cli(HOST, PORT);
  2651. cli.set_connection_timeout(std::chrono::seconds(5));
  2652. auto res =
  2653. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2654. "application/json", [](uint64_t, uint64_t) { return true; });
  2655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2656. EXPECT_EQ("Hello World!", res->body);
  2657. EXPECT_EQ(StatusCode::OK_200, res->status);
  2658. }
  2659. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2660. Server svr;
  2661. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2662. res.set_content("Hello World!", "text/plain");
  2663. });
  2664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2665. auto se = detail::scope_exit([&] {
  2666. svr.stop();
  2667. thread.join();
  2668. ASSERT_FALSE(svr.is_running());
  2669. });
  2670. svr.wait_until_ready();
  2671. Client cli(HOST, PORT);
  2672. cli.set_connection_timeout(std::chrono::seconds(5));
  2673. auto res =
  2674. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2675. "application/json", [](uint64_t, uint64_t) { return false; });
  2676. ASSERT_TRUE(!res);
  2677. EXPECT_EQ(Error::Canceled, res.error());
  2678. }
  2679. TEST(CancelTest, WithCancelLargePayloadPut) {
  2680. Server svr;
  2681. svr.set_payload_max_length(200 * 1024 * 1024);
  2682. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2683. res.set_content(LARGE_DATA, "text/plain");
  2684. });
  2685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2686. auto se = detail::scope_exit([&] {
  2687. svr.stop();
  2688. thread.join();
  2689. ASSERT_FALSE(svr.is_running());
  2690. });
  2691. svr.wait_until_ready();
  2692. Client cli(HOST, PORT);
  2693. cli.set_payload_max_length(200 * 1024 * 1024);
  2694. cli.set_connection_timeout(std::chrono::seconds(5));
  2695. auto res =
  2696. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2697. "application/json", [](uint64_t, uint64_t) { return false; });
  2698. ASSERT_TRUE(!res);
  2699. EXPECT_EQ(Error::Canceled, res.error());
  2700. }
  2701. TEST(CancelTest, NoCancelPatch) {
  2702. Server svr;
  2703. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content("Hello World!", "text/plain");
  2705. });
  2706. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2707. auto se = detail::scope_exit([&] {
  2708. svr.stop();
  2709. thread.join();
  2710. ASSERT_FALSE(svr.is_running());
  2711. });
  2712. svr.wait_until_ready();
  2713. Client cli(HOST, PORT);
  2714. cli.set_connection_timeout(std::chrono::seconds(5));
  2715. auto res =
  2716. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2717. "application/json", [](uint64_t, uint64_t) { return true; });
  2718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2719. EXPECT_EQ("Hello World!", res->body);
  2720. EXPECT_EQ(StatusCode::OK_200, res->status);
  2721. }
  2722. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2723. Server svr;
  2724. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2725. res.set_content("Hello World!", "text/plain");
  2726. });
  2727. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2728. auto se = detail::scope_exit([&] {
  2729. svr.stop();
  2730. thread.join();
  2731. ASSERT_FALSE(svr.is_running());
  2732. });
  2733. svr.wait_until_ready();
  2734. Client cli(HOST, PORT);
  2735. cli.set_connection_timeout(std::chrono::seconds(5));
  2736. auto res =
  2737. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2738. "application/json", [](uint64_t, uint64_t) { return false; });
  2739. ASSERT_TRUE(!res);
  2740. EXPECT_EQ(Error::Canceled, res.error());
  2741. }
  2742. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2743. Server svr;
  2744. svr.set_payload_max_length(200 * 1024 * 1024);
  2745. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2746. res.set_content(LARGE_DATA, "text/plain");
  2747. });
  2748. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2749. auto se = detail::scope_exit([&] {
  2750. svr.stop();
  2751. thread.join();
  2752. ASSERT_FALSE(svr.is_running());
  2753. });
  2754. svr.wait_until_ready();
  2755. Client cli(HOST, PORT);
  2756. cli.set_payload_max_length(200 * 1024 * 1024);
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. auto res =
  2759. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2760. "application/json", [](uint64_t, uint64_t) { return false; });
  2761. ASSERT_TRUE(!res);
  2762. EXPECT_EQ(Error::Canceled, res.error());
  2763. }
  2764. TEST(CancelTest, NoCancelDelete) {
  2765. Server svr;
  2766. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2767. res.set_content("Hello World!", "text/plain");
  2768. });
  2769. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2770. auto se = detail::scope_exit([&] {
  2771. svr.stop();
  2772. thread.join();
  2773. ASSERT_FALSE(svr.is_running());
  2774. });
  2775. svr.wait_until_ready();
  2776. Client cli(HOST, PORT);
  2777. cli.set_connection_timeout(std::chrono::seconds(5));
  2778. auto res =
  2779. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2780. "application/json", [](uint64_t, uint64_t) { return true; });
  2781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2782. EXPECT_EQ("Hello World!", res->body);
  2783. EXPECT_EQ(StatusCode::OK_200, res->status);
  2784. }
  2785. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2786. Server svr;
  2787. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2788. res.set_content("Hello World!", "text/plain");
  2789. });
  2790. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2791. auto se = detail::scope_exit([&] {
  2792. svr.stop();
  2793. thread.join();
  2794. ASSERT_FALSE(svr.is_running());
  2795. });
  2796. svr.wait_until_ready();
  2797. Client cli(HOST, PORT);
  2798. cli.set_connection_timeout(std::chrono::seconds(5));
  2799. auto res =
  2800. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2801. "application/json", [](uint64_t, uint64_t) { return false; });
  2802. ASSERT_TRUE(!res);
  2803. EXPECT_EQ(Error::Canceled, res.error());
  2804. }
  2805. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2806. Server svr;
  2807. svr.set_payload_max_length(200 * 1024 * 1024);
  2808. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2809. res.set_content(LARGE_DATA, "text/plain");
  2810. });
  2811. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2812. auto se = detail::scope_exit([&] {
  2813. svr.stop();
  2814. thread.join();
  2815. ASSERT_FALSE(svr.is_running());
  2816. });
  2817. svr.wait_until_ready();
  2818. Client cli(HOST, PORT);
  2819. cli.set_payload_max_length(200 * 1024 * 1024);
  2820. cli.set_connection_timeout(std::chrono::seconds(5));
  2821. auto res =
  2822. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2823. "application/json", [](uint64_t, uint64_t) { return false; });
  2824. ASSERT_TRUE(!res);
  2825. EXPECT_EQ(Error::Canceled, res.error());
  2826. }
  2827. static std::string remove_whitespace(const std::string &input) {
  2828. std::string output;
  2829. output.reserve(input.size());
  2830. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2831. [](unsigned char c) { return !std::isspace(c); });
  2832. return output;
  2833. }
  2834. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2835. auto host = "httpbingo.org";
  2836. auto path = std::string{"/basic-auth/hello/world"};
  2837. #ifdef CPPHTTPLIB_SSL_ENABLED
  2838. auto port = 443;
  2839. SSLClient cli(host, port);
  2840. #else
  2841. auto port = 80;
  2842. Client cli(host, port);
  2843. #endif
  2844. {
  2845. auto res = cli.Get(path);
  2846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2848. }
  2849. {
  2850. auto res = cli.Get(
  2851. path, Headers{make_basic_authentication_header("hello", "world")});
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. auto body = remove_whitespace(res->body);
  2854. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2855. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2856. EXPECT_EQ(StatusCode::OK_200, res->status);
  2857. }
  2858. {
  2859. cli.set_basic_auth("hello", "world");
  2860. auto res = cli.Get(path);
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. auto body = remove_whitespace(res->body);
  2863. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2864. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2865. EXPECT_EQ(StatusCode::OK_200, res->status);
  2866. }
  2867. {
  2868. cli.set_basic_auth("hello", "bad");
  2869. auto res = cli.Get(path);
  2870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2871. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2872. }
  2873. {
  2874. cli.set_basic_auth("bad", "world");
  2875. auto res = cli.Get(path);
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2878. }
  2879. }
  2880. #ifdef CPPHTTPLIB_SSL_ENABLED
  2881. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2882. auto host = "httpbingo.org";
  2883. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2884. auto paths = std::vector<std::string>{
  2885. "/digest-auth/auth/hello/world/MD5",
  2886. "/digest-auth/auth/hello/world/SHA-256",
  2887. };
  2888. auto port = 443;
  2889. SSLClient cli(host, port);
  2890. {
  2891. auto res = cli.Get(unauth_path);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2894. }
  2895. {
  2896. cli.set_digest_auth("hello", "world");
  2897. for (const auto &path : paths) {
  2898. auto res = cli.Get(path.c_str());
  2899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2900. auto body = remove_whitespace(res->body);
  2901. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2902. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2903. EXPECT_EQ(StatusCode::OK_200, res->status);
  2904. }
  2905. cli.set_digest_auth("hello", "bad");
  2906. for (const auto &path : paths) {
  2907. auto res = cli.Get(path.c_str());
  2908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2909. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2910. }
  2911. }
  2912. }
  2913. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2914. // comma-separated list of challenges, and each challenge may itself carry a
  2915. // comma-separated auth-param list, so a server can legally offer Basic
  2916. // before Digest, either as two field lines or packed into one. Runs one 401
  2917. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2918. // value() joins them in receipt order) and checks that the retry carries a
  2919. // well-formed Digest Authorization header naming expected_realm.
  2920. static void
  2921. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2922. const std::string &expected_realm) {
  2923. std::atomic<int> hits{0};
  2924. Server svr;
  2925. svr.Get("/x", [&](const Request &req, Response &res) {
  2926. if (++hits == 1) {
  2927. res.status = StatusCode::Unauthorized_401;
  2928. for (const auto &challenge : challenges) {
  2929. res.set_header("WWW-Authenticate", challenge);
  2930. }
  2931. } else {
  2932. auto authorization = req.get_header_value("Authorization");
  2933. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2934. EXPECT_NE(std::string::npos,
  2935. authorization.find("realm=\"" + expected_realm + "\""));
  2936. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2937. res.set_content("ok", "text/plain");
  2938. }
  2939. });
  2940. auto port = svr.bind_to_any_port(HOST);
  2941. std::thread t([&]() { svr.listen_after_bind(); });
  2942. auto se = detail::scope_exit([&] {
  2943. svr.stop();
  2944. t.join();
  2945. });
  2946. svr.wait_until_ready();
  2947. Client cli(HOST, port);
  2948. cli.set_digest_auth("hello", "world");
  2949. auto res = cli.Get("/x");
  2950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2951. EXPECT_EQ(2, hits.load());
  2952. }
  2953. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2954. static const char *kDigestChallenge =
  2955. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2956. "algorithm=MD5";
  2957. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2958. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2959. "testrealm");
  2960. }
  2961. // Same challenge list with the schemes in the opposite order, to make sure
  2962. // the fix above didn't just special-case "Basic first".
  2963. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2964. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2965. "testrealm");
  2966. }
  2967. // A comma inside a quoted auth-param value must not be mistaken for the
  2968. // separator between two challenges (or two auth-params).
  2969. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2970. run_digest_challenge_list_test(
  2971. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2972. "algorithm=MD5"},
  2973. "test,realm");
  2974. }
  2975. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2976. // the params and leaves out the fragment.
  2977. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2978. Server svr;
  2979. std::string uri, target;
  2980. svr.Get("/a b", [&](const Request &req, Response &res) {
  2981. auto auth = req.get_header_value("Authorization");
  2982. if (auth.empty()) {
  2983. res.status = StatusCode::Unauthorized_401;
  2984. res.set_header("WWW-Authenticate",
  2985. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2986. return;
  2987. }
  2988. auto b = auth.find("uri=\"") + 5;
  2989. uri = auth.substr(b, auth.find('"', b) - b);
  2990. target = req.target;
  2991. });
  2992. auto port = svr.bind_to_any_port(HOST);
  2993. std::thread t([&]() { svr.listen_after_bind(); });
  2994. auto se = detail::scope_exit([&] {
  2995. svr.stop();
  2996. t.join();
  2997. });
  2998. svr.wait_until_ready();
  2999. Client cli(HOST, port);
  3000. cli.set_digest_auth("hello", "world");
  3001. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. EXPECT_EQ("/a%20b?x=1", target);
  3004. EXPECT_EQ(target, uri);
  3005. }
  3006. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3007. // make_digest_authentication_header() dereferences both unconditionally, so
  3008. // a server sending a challenge missing either one must not be treated as
  3009. // usable -- doing so used to crash the client with std::out_of_range.
  3010. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3011. Server svr;
  3012. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3013. res.status = StatusCode::Unauthorized_401;
  3014. res.set_header("WWW-Authenticate", challenge);
  3015. });
  3016. auto port = svr.bind_to_any_port(HOST);
  3017. std::thread t([&]() { svr.listen_after_bind(); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. t.join();
  3021. });
  3022. svr.wait_until_ready();
  3023. Client cli(HOST, port);
  3024. cli.set_digest_auth("hello", "world");
  3025. auto res = cli.Get("/x");
  3026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3027. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3028. }
  3029. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3030. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3031. }
  3032. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3033. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3034. }
  3035. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3036. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3037. }
  3038. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3039. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3040. // when storing the values, so the header builder has to re-escape them (and
  3041. // keep algorithm a bare token); otherwise the value breaks out of its
  3042. // quoted-string and injects extra auth-params into the client's Authorization.
  3043. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3044. std::atomic<int> hits{0};
  3045. std::string authorization;
  3046. Server svr;
  3047. svr.Get("/x", [&](const Request &req, Response &res) {
  3048. if (++hits == 1) {
  3049. res.status = StatusCode::Unauthorized_401;
  3050. // On the wire the quotes embedded in the values are backslash-escaped.
  3051. res.set_header("WWW-Authenticate",
  3052. "Digest realm=\"testrealm\", "
  3053. "nonce=\"n\\\"; injected=\\\"x\", "
  3054. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3055. } else {
  3056. authorization = req.get_header_value("Authorization");
  3057. res.set_content("ok", "text/plain");
  3058. }
  3059. });
  3060. auto port = svr.bind_to_any_port(HOST);
  3061. std::thread t([&]() { svr.listen_after_bind(); });
  3062. auto se = detail::scope_exit([&] {
  3063. svr.stop();
  3064. t.join();
  3065. });
  3066. svr.wait_until_ready();
  3067. Client cli(HOST, port);
  3068. cli.set_digest_auth("hello", "world");
  3069. auto res = cli.Get("/x");
  3070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3071. EXPECT_EQ(2, hits.load());
  3072. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3073. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3074. // inside its quoted-string rather than starting an "injected" auth-param.
  3075. EXPECT_NE(std::string::npos,
  3076. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3077. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3078. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3079. }
  3080. #endif
  3081. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3082. auto host = "google.com";
  3083. auto another_host = "example.com";
  3084. auto wrong_ip = "0.0.0.0";
  3085. #ifdef CPPHTTPLIB_SSL_ENABLED
  3086. SSLClient cli(host);
  3087. #else
  3088. Client cli(host);
  3089. #endif
  3090. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3091. auto res = cli.Get("/");
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3094. }
  3095. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3096. auto host = "google.com";
  3097. auto wrong_ip = "0.0.0.0";
  3098. #ifdef CPPHTTPLIB_SSL_ENABLED
  3099. SSLClient cli(host);
  3100. #else
  3101. Client cli(host);
  3102. #endif
  3103. cli.set_hostname_addr_map({{host, wrong_ip}});
  3104. auto res = cli.Get("/");
  3105. ASSERT_TRUE(!res);
  3106. EXPECT_EQ(Error::Connection, res.error());
  3107. }
  3108. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3109. // A mapped value that is not an IP literal must be resolved. "localhost"
  3110. // resolves from the hosts file, so this test needs no external DNS.
  3111. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3112. auto host = "target.invalid";
  3113. Server svr;
  3114. std::string received_host;
  3115. svr.Get("/hi", [&](const Request &req, Response &res) {
  3116. received_host = req.get_header_value("Host");
  3117. res.set_content("Hello World!", "text/plain");
  3118. });
  3119. auto port = svr.bind_to_any_port(HOST);
  3120. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3121. auto se = detail::scope_exit([&] {
  3122. svr.stop();
  3123. thread.join();
  3124. ASSERT_FALSE(svr.is_running());
  3125. });
  3126. svr.wait_until_ready();
  3127. Client cli(host, port);
  3128. cli.set_hostname_addr_map({{host, HOST}});
  3129. auto res = cli.Get("/hi");
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. // The mapping only redirects the connection; the identity stays host_.
  3133. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3134. }
  3135. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3136. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3137. auto host = "target.invalid";
  3138. Server svr;
  3139. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3140. res.set_content("Hello World!", "text/plain");
  3141. });
  3142. auto port = svr.bind_to_any_port("127.0.0.1");
  3143. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3144. auto se = detail::scope_exit([&] {
  3145. svr.stop();
  3146. thread.join();
  3147. ASSERT_FALSE(svr.is_running());
  3148. });
  3149. svr.wait_until_ready();
  3150. Client cli(host, port);
  3151. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3152. auto res = cli.Get("/hi");
  3153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3154. EXPECT_EQ(StatusCode::OK_200, res->status);
  3155. }
  3156. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3157. // An empty mapped value must leave host_ as the connection target. Without
  3158. // that guard the empty value would become the host argument, getaddrinfo
  3159. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3160. // loopback - silently connecting somewhere the caller never asked for.
  3161. // The server listens on loopback, so such a fallback would succeed and is
  3162. // therefore observable as a failure of this test.
  3163. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3164. Server svr;
  3165. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3166. res.set_content("Hello World!", "text/plain");
  3167. });
  3168. auto port = svr.bind_to_any_port(HOST);
  3169. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3170. auto se = detail::scope_exit([&] {
  3171. svr.stop();
  3172. thread.join();
  3173. ASSERT_FALSE(svr.is_running());
  3174. });
  3175. svr.wait_until_ready();
  3176. Client cli(blackhole, port);
  3177. cli.set_hostname_addr_map({{blackhole, ""}});
  3178. cli.set_connection_timeout(1);
  3179. auto res = cli.Get("/hi");
  3180. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3181. }
  3182. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3183. auto host = "httpbingo.org";
  3184. auto path = std::string{"/absolute-redirect/3"};
  3185. #ifdef CPPHTTPLIB_SSL_ENABLED
  3186. SSLClient cli(host);
  3187. #else
  3188. Client cli(host);
  3189. #endif
  3190. cli.set_follow_location(true);
  3191. auto res = cli.Get(path);
  3192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3193. EXPECT_EQ(StatusCode::OK_200, res->status);
  3194. }
  3195. TEST(RedirectTest, Redirect_Online) {
  3196. auto host = "httpbingo.org";
  3197. auto path = std::string{"/redirect/3"};
  3198. #ifdef CPPHTTPLIB_SSL_ENABLED
  3199. SSLClient cli(host);
  3200. #else
  3201. Client cli(host);
  3202. #endif
  3203. cli.set_follow_location(true);
  3204. auto res = cli.Get(path);
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(RelativeRedirectTest, Redirect_Online) {
  3209. auto host = "httpbingo.org";
  3210. auto path = std::string{"/relative-redirect/3"};
  3211. #ifdef CPPHTTPLIB_SSL_ENABLED
  3212. SSLClient cli(host);
  3213. #else
  3214. Client cli(host);
  3215. #endif
  3216. cli.set_follow_location(true);
  3217. auto res = cli.Get(path);
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(TooManyRedirectTest, Redirect_Online) {
  3222. auto host = "httpbingo.org";
  3223. auto path = std::string{"/redirect/21"};
  3224. #ifdef CPPHTTPLIB_SSL_ENABLED
  3225. SSLClient cli(host);
  3226. #else
  3227. Client cli(host);
  3228. #endif
  3229. cli.set_follow_location(true);
  3230. auto res = cli.Get(path);
  3231. ASSERT_TRUE(!res);
  3232. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3233. }
  3234. #ifdef CPPHTTPLIB_SSL_ENABLED
  3235. TEST(YahooRedirectTest, Redirect_Online) {
  3236. Client cli("yahoo.com");
  3237. auto res = cli.Get("/");
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3240. cli.set_follow_location(true);
  3241. res = cli.Get("/");
  3242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3243. EXPECT_EQ(StatusCode::OK_200, res->status);
  3244. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3245. }
  3246. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3247. #define REDIR_HOST "httpbingo.org"
  3248. #define REDIR_PATH "/redirect-to"
  3249. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3250. SSLClient cli(REDIR_HOST);
  3251. cli.set_follow_location(true);
  3252. auto res =
  3253. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. }
  3257. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3258. SSLClient cli(REDIR_HOST);
  3259. cli.set_follow_location(true);
  3260. Params params;
  3261. params.emplace("url", "http://example.com");
  3262. params.emplace("status_code", "302");
  3263. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. }
  3267. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3268. SSLClient cli(REDIR_HOST);
  3269. cli.set_follow_location(true);
  3270. Params params;
  3271. params.emplace("url", "http://example.com");
  3272. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. EXPECT_EQ(StatusCode::OK_200, res->status);
  3275. }
  3276. TEST(UrlWithSpace, Redirect_Online) {
  3277. SSLClient cli("edge.forgecdn.net");
  3278. cli.set_follow_location(true);
  3279. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3281. EXPECT_EQ(StatusCode::OK_200, res->status);
  3282. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3283. }
  3284. #endif
  3285. #if !defined(_WIN32) && !defined(_WIN64)
  3286. TEST(ReceiveSignals, Signal) {
  3287. auto setupSignalHandlers = []() {
  3288. struct sigaction act;
  3289. sigemptyset(&act.sa_mask);
  3290. act.sa_flags = SA_SIGINFO;
  3291. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3292. switch (sig) {
  3293. case SIGINT:
  3294. default: break;
  3295. }
  3296. };
  3297. ::sigaction(SIGINT, &act, nullptr);
  3298. };
  3299. Server svr;
  3300. int port = 0;
  3301. auto thread = std::thread([&]() {
  3302. setupSignalHandlers();
  3303. port = svr.bind_to_any_port(HOST);
  3304. svr.listen_after_bind();
  3305. });
  3306. auto se = detail::scope_exit([&] {
  3307. svr.stop();
  3308. thread.join();
  3309. ASSERT_FALSE(svr.is_running());
  3310. });
  3311. svr.wait_until_ready();
  3312. ASSERT_TRUE(svr.is_running());
  3313. pthread_kill(thread.native_handle(), SIGINT);
  3314. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3315. ASSERT_TRUE(svr.is_running());
  3316. }
  3317. #endif
  3318. TEST(RedirectToDifferentPort, Redirect) {
  3319. Server svr1;
  3320. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3321. res.set_content("Hello World!", "text/plain");
  3322. });
  3323. int svr1_port = 0;
  3324. auto thread1 = std::thread([&]() {
  3325. svr1_port = svr1.bind_to_any_port(HOST);
  3326. svr1.listen_after_bind();
  3327. });
  3328. Server svr2;
  3329. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3330. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3331. });
  3332. int svr2_port = 0;
  3333. auto thread2 = std::thread([&]() {
  3334. svr2_port = svr2.bind_to_any_port(HOST);
  3335. svr2.listen_after_bind();
  3336. });
  3337. auto se = detail::scope_exit([&] {
  3338. svr2.stop();
  3339. thread2.join();
  3340. svr1.stop();
  3341. thread1.join();
  3342. ASSERT_FALSE(svr2.is_running());
  3343. ASSERT_FALSE(svr1.is_running());
  3344. });
  3345. svr1.wait_until_ready();
  3346. svr2.wait_until_ready();
  3347. Client cli("localhost", svr2_port);
  3348. cli.set_follow_location(true);
  3349. auto res = cli.Get("/2");
  3350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3351. EXPECT_EQ(StatusCode::OK_200, res->status);
  3352. EXPECT_EQ("Hello World!", res->body);
  3353. }
  3354. // GET /redir on one server redirects to /target on another port, so the
  3355. // client follows it with a new client.
  3356. static Result
  3357. GetThroughRedirectToDifferentPort(Server::Handler target,
  3358. const std::function<void(Client &)> &setup,
  3359. const Headers &headers = Headers()) {
  3360. Server target_svr;
  3361. target_svr.Get("/target", target);
  3362. int target_port = 0;
  3363. auto target_thread = std::thread([&]() {
  3364. target_port = target_svr.bind_to_any_port(HOST);
  3365. target_svr.listen_after_bind();
  3366. });
  3367. Server origin_svr;
  3368. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3369. res.set_redirect(
  3370. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3371. });
  3372. int origin_port = 0;
  3373. auto origin_thread = std::thread([&]() {
  3374. origin_port = origin_svr.bind_to_any_port(HOST);
  3375. origin_svr.listen_after_bind();
  3376. });
  3377. auto se = detail::scope_exit([&] {
  3378. origin_svr.stop();
  3379. origin_thread.join();
  3380. target_svr.stop();
  3381. target_thread.join();
  3382. });
  3383. target_svr.wait_until_ready();
  3384. origin_svr.wait_until_ready();
  3385. Client cli("localhost", origin_port);
  3386. cli.set_follow_location(true);
  3387. setup(cli);
  3388. return cli.Get("/redir", headers);
  3389. }
  3390. static void
  3391. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3392. std::string captured_authorization;
  3393. auto result = GetThroughRedirectToDifferentPort(
  3394. [&](const Request &req, Response &res) {
  3395. captured_authorization = req.get_header_value("Authorization");
  3396. res.set_content("OK", "text/plain");
  3397. },
  3398. set_auth);
  3399. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3400. EXPECT_EQ(StatusCode::OK_200, result->status);
  3401. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3402. EXPECT_TRUE(captured_authorization.empty());
  3403. }
  3404. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3405. TestDoNotForwardCredentialsOnRedirect(
  3406. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3407. }
  3408. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3409. TestDoNotForwardCredentialsOnRedirect(
  3410. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3411. }
  3412. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3413. std::string captured_cookie;
  3414. auto result = GetThroughRedirectToDifferentPort(
  3415. [&](const Request &req, Response &res) {
  3416. captured_cookie = req.get_header_value("Cookie");
  3417. res.set_content("OK", "text/plain");
  3418. },
  3419. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3420. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3421. EXPECT_EQ(StatusCode::OK_200, result->status);
  3422. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3423. EXPECT_TRUE(captured_cookie.empty());
  3424. }
  3425. TEST(RedirectToSamePort, ForwardCookie) {
  3426. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3427. // header so that ordinary session flows keep working.
  3428. Server svr;
  3429. std::string captured_cookie;
  3430. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3431. res.set_redirect("/target", 302);
  3432. });
  3433. svr.Get("/target", [&](const Request &req, Response &res) {
  3434. captured_cookie = req.get_header_value("Cookie");
  3435. res.set_content("OK", "text/plain");
  3436. });
  3437. auto port = svr.bind_to_any_port(HOST);
  3438. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3439. auto se = detail::scope_exit([&] {
  3440. svr.stop();
  3441. thread.join();
  3442. ASSERT_FALSE(svr.is_running());
  3443. });
  3444. svr.wait_until_ready();
  3445. Client cli(HOST, port);
  3446. cli.set_follow_location(true);
  3447. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3448. auto res = cli.Get("/redir", headers);
  3449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3450. EXPECT_EQ(StatusCode::OK_200, res->status);
  3451. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3452. }
  3453. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3454. std::string authorization;
  3455. std::string trace_id;
  3456. auto result = GetThroughRedirectToDifferentPort(
  3457. [&](const Request &req, Response &res) {
  3458. authorization = req.get_header_value("Authorization");
  3459. trace_id = req.get_header_value("X-Trace-Id");
  3460. res.set_content("OK", "text/plain");
  3461. },
  3462. [](Client &cli) {
  3463. cli.set_default_headers(
  3464. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3465. });
  3466. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3467. EXPECT_EQ(StatusCode::OK_200, result->status);
  3468. // Like a header given with the request, a default one goes along unless it
  3469. // carries credentials (RFC 9110 15.4).
  3470. EXPECT_TRUE(authorization.empty());
  3471. EXPECT_EQ("42", trace_id);
  3472. }
  3473. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3474. auto result = GetThroughRedirectToDifferentPort(
  3475. [](const Request &, Response &res) {
  3476. res.set_content(std::string(2048, 'x'), "text/plain");
  3477. },
  3478. [](Client &cli) { cli.set_payload_max_length(1024); });
  3479. EXPECT_FALSE(result);
  3480. }
  3481. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3482. auto result = GetThroughRedirectToDifferentPort(
  3483. [](const Request &req, Response &res) {
  3484. // Answer after a second, or once the client gives up.
  3485. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3486. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3487. }
  3488. res.set_content("late", "text/plain");
  3489. },
  3490. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3491. ASSERT_FALSE(result);
  3492. EXPECT_EQ(Error::Read, result.error());
  3493. }
  3494. #ifdef CPPHTTPLIB_SSL_ENABLED
  3495. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3496. auto result = GetThroughRedirectToDifferentPort(
  3497. [](const Request &, Response &res) {
  3498. res.status = StatusCode::Unauthorized_401;
  3499. res.set_header("WWW-Authenticate",
  3500. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3501. },
  3502. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3503. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3504. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3505. }
  3506. #endif
  3507. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3508. Server svr;
  3509. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3510. // Port number that overflows int — should not crash
  3511. res.set_redirect("http://localhost:99999999999999999999/target");
  3512. });
  3513. auto port = svr.bind_to_any_port(HOST);
  3514. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3515. auto se = detail::scope_exit([&] {
  3516. svr.stop();
  3517. thread.join();
  3518. ASSERT_FALSE(svr.is_running());
  3519. });
  3520. svr.wait_until_ready();
  3521. Client cli(HOST, port);
  3522. cli.set_follow_location(true);
  3523. auto res = cli.Get("/redir");
  3524. // Should fail gracefully, not crash (no valid response due to bad port)
  3525. EXPECT_FALSE(res);
  3526. }
  3527. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3528. Server svr;
  3529. auto port = svr.bind_to_any_port(HOST);
  3530. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3531. // The server's own port followed by junk must not be followed
  3532. res.set_redirect("http://" + std::string(HOST) + ":" +
  3533. std::to_string(port) + "junk/target");
  3534. });
  3535. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3536. res.set_content("target", "text/plain");
  3537. });
  3538. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3539. auto se = detail::scope_exit([&] {
  3540. svr.stop();
  3541. thread.join();
  3542. ASSERT_FALSE(svr.is_running());
  3543. });
  3544. svr.wait_until_ready();
  3545. Client cli(HOST, port);
  3546. cli.set_follow_location(true);
  3547. auto res = cli.Get("/redir");
  3548. EXPECT_FALSE(res);
  3549. }
  3550. TEST(RedirectFromPageWithContent, Redirect) {
  3551. Server svr;
  3552. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3553. res.set_content("___", "text/plain");
  3554. res.set_redirect("/2");
  3555. });
  3556. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3557. res.set_content("Hello World!", "text/plain");
  3558. });
  3559. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3560. auto se = detail::scope_exit([&] {
  3561. svr.stop();
  3562. th.join();
  3563. ASSERT_FALSE(svr.is_running());
  3564. });
  3565. svr.wait_until_ready();
  3566. {
  3567. Client cli("localhost", PORT);
  3568. cli.set_follow_location(true);
  3569. std::string body;
  3570. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3571. body.append(data, data_length);
  3572. return true;
  3573. });
  3574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3575. EXPECT_EQ(StatusCode::OK_200, res->status);
  3576. EXPECT_EQ("Hello World!", body);
  3577. }
  3578. {
  3579. Client cli("localhost", PORT);
  3580. std::string body;
  3581. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3582. body.append(data, data_length);
  3583. return true;
  3584. });
  3585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3586. EXPECT_EQ(StatusCode::Found_302, res->status);
  3587. EXPECT_EQ("___", body);
  3588. }
  3589. }
  3590. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3591. Server svr;
  3592. auto port_str = std::to_string(PORT);
  3593. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3594. auto expected_host = "[::1]:" + port_str;
  3595. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3596. res.set_content("___", "text/plain");
  3597. // res.set_redirect("/2");
  3598. res.set_redirect(redirect_url);
  3599. });
  3600. svr.Get("/2", [&](const Request &req, Response &res) {
  3601. auto host_header = req.headers.find("Host");
  3602. ASSERT_TRUE(host_header != req.headers.end());
  3603. EXPECT_EQ(expected_host, host_header->second);
  3604. res.set_content("Hello World!", "text/plain");
  3605. });
  3606. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3607. auto se = detail::scope_exit([&] {
  3608. svr.stop();
  3609. th.join();
  3610. ASSERT_FALSE(svr.is_running());
  3611. });
  3612. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3613. // actually starts anything, so the condition !svr.is_running() will
  3614. // always remain true, and the loop never stops.
  3615. // This basically counts how many milliseconds have passed since the
  3616. // call to svr.listen(), and if after 5 seconds nothing started yet
  3617. // aborts the test.
  3618. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3619. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3620. ASSERT_LT(milliseconds, 5000U);
  3621. }
  3622. {
  3623. Client cli("::1", PORT);
  3624. cli.set_follow_location(true);
  3625. std::string body;
  3626. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3627. body.append(data, data_length);
  3628. return true;
  3629. });
  3630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3631. EXPECT_EQ(StatusCode::OK_200, res->status);
  3632. EXPECT_EQ("Hello World!", body);
  3633. }
  3634. {
  3635. Client cli("::1", PORT);
  3636. std::string body;
  3637. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3638. body.append(data, data_length);
  3639. return true;
  3640. });
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::Found_302, res->status);
  3643. EXPECT_EQ("___", body);
  3644. }
  3645. }
  3646. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3647. Server svr;
  3648. svr.Get("/foo", [](const Request &req, Response &res) {
  3649. auto a = req.params.find("a");
  3650. if (a != req.params.end()) {
  3651. res.set_content((*a).second, "text/plain");
  3652. res.status = StatusCode::OK_200;
  3653. } else {
  3654. res.status = StatusCode::BadRequest_400;
  3655. }
  3656. });
  3657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3658. auto se = detail::scope_exit([&] {
  3659. svr.stop();
  3660. thread.join();
  3661. ASSERT_FALSE(svr.is_running());
  3662. });
  3663. svr.wait_until_ready();
  3664. {
  3665. Client cli(HOST, PORT);
  3666. cli.set_path_encode(false);
  3667. auto res = cli.Get("/foo?a=explicitly+encoded");
  3668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3669. EXPECT_EQ(StatusCode::OK_200, res->status);
  3670. // This expects it back with a space, as the `+` won't have been
  3671. // url-encoded, and server-side the params get decoded turning `+`
  3672. // into spaces.
  3673. EXPECT_EQ("explicitly encoded", res->body);
  3674. }
  3675. }
  3676. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3677. // When path encoding is disabled the client must transmit the supplied
  3678. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3679. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3680. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3681. // than a space (0x20). Assert on the raw wire target to catch this.
  3682. Server svr;
  3683. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3684. svr.Get("/foo", [&](const Request &req, Response &res) {
  3685. EXPECT_EQ(expected_target, req.target);
  3686. res.status = StatusCode::OK_200;
  3687. });
  3688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3689. auto se = detail::scope_exit([&] {
  3690. svr.stop();
  3691. thread.join();
  3692. ASSERT_FALSE(svr.is_running());
  3693. });
  3694. svr.wait_until_ready();
  3695. {
  3696. Client cli(HOST, PORT);
  3697. cli.set_path_encode(false);
  3698. auto res = cli.Get(expected_target.c_str());
  3699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3700. EXPECT_EQ(StatusCode::OK_200, res->status);
  3701. }
  3702. }
  3703. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3704. // `open_stream()` used to skip the path encoding that the buffered send
  3705. // path applies, so the same `path` produced different bytes in the request
  3706. // line depending on which API was used. Assert the two agree.
  3707. Server svr;
  3708. std::string target;
  3709. svr.Get(".*", [&](const Request &req, Response &res) {
  3710. target = req.target;
  3711. res.status = StatusCode::OK_200;
  3712. });
  3713. auto port = svr.bind_to_any_port(HOST);
  3714. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3715. auto se = detail::scope_exit([&] {
  3716. svr.stop();
  3717. thread.join();
  3718. ASSERT_FALSE(svr.is_running());
  3719. });
  3720. svr.wait_until_ready();
  3721. struct {
  3722. const char *path;
  3723. const char *expected;
  3724. } cases[] = {
  3725. {"/a b?x=1", "/a%20b?x=1"},
  3726. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3727. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3728. };
  3729. for (const auto &c : cases) {
  3730. Client cli(HOST, port);
  3731. target.clear();
  3732. auto res = cli.Get(c.path);
  3733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3734. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3735. auto buffered_target = target;
  3736. target.clear();
  3737. auto handle = cli.open_stream("GET", c.path);
  3738. EXPECT_TRUE(handle.is_valid())
  3739. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3740. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3741. }
  3742. }
  3743. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3744. // The `set_path_encode(false)` contract — transmit the supplied target
  3745. // verbatim — must hold for the streaming API too.
  3746. Server svr;
  3747. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3748. std::string target;
  3749. svr.Get("/foo", [&](const Request &req, Response &res) {
  3750. target = req.target;
  3751. res.status = StatusCode::OK_200;
  3752. });
  3753. auto port = svr.bind_to_any_port(HOST);
  3754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3755. auto se = detail::scope_exit([&] {
  3756. svr.stop();
  3757. thread.join();
  3758. ASSERT_FALSE(svr.is_running());
  3759. });
  3760. svr.wait_until_ready();
  3761. {
  3762. Client cli(HOST, port);
  3763. cli.set_path_encode(false);
  3764. auto handle = cli.open_stream("GET", expected_target);
  3765. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3766. EXPECT_EQ(expected_target, target);
  3767. }
  3768. }
  3769. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3770. // With path encoding enabled a CR/LF in the target is percent-encoded
  3771. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3772. // write_request_line still backstops `set_path_encode(false)`, which is
  3773. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3774. Server svr;
  3775. // Captured before routing: the decoded path contains a newline, which a
  3776. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3777. std::string target;
  3778. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3779. target = req.target;
  3780. res.status = StatusCode::OK_200;
  3781. return Server::HandlerResponse::Handled;
  3782. });
  3783. auto port = svr.bind_to_any_port(HOST);
  3784. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3785. auto se = detail::scope_exit([&] {
  3786. svr.stop();
  3787. thread.join();
  3788. ASSERT_FALSE(svr.is_running());
  3789. });
  3790. svr.wait_until_ready();
  3791. {
  3792. Client cli(HOST, port);
  3793. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3794. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3795. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3796. }
  3797. }
  3798. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3799. // Every control character is percent-encoded, not just CR/LF, so the target
  3800. // passes the request-target check in write_request_line.
  3801. Server svr;
  3802. std::string target;
  3803. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3804. target = req.target;
  3805. res.status = StatusCode::OK_200;
  3806. return Server::HandlerResponse::Handled;
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. Client cli(HOST, port);
  3818. auto res = cli.Get("/a\tb\x1b\x7f");
  3819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3820. EXPECT_EQ("/a%09b%1B%7F", target);
  3821. }
  3822. }
  3823. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3824. // Nothing may reach the wire: a raw CR/LF target would split the request
  3825. // line and inject headers.
  3826. Server svr;
  3827. // Pre-routing so that "not called" means nothing reached the server at all,
  3828. // rather than merely failing to match a handler pattern.
  3829. auto handler_called = false;
  3830. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3831. handler_called = true;
  3832. res.status = StatusCode::OK_200;
  3833. return Server::HandlerResponse::Handled;
  3834. });
  3835. auto port = svr.bind_to_any_port(HOST);
  3836. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3837. auto se = detail::scope_exit([&] {
  3838. svr.stop();
  3839. thread.join();
  3840. ASSERT_FALSE(svr.is_running());
  3841. });
  3842. svr.wait_until_ready();
  3843. {
  3844. Client cli(HOST, port);
  3845. cli.set_path_encode(false);
  3846. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3847. EXPECT_FALSE(handle.is_valid());
  3848. EXPECT_EQ(Error::Write, handle.error);
  3849. EXPECT_FALSE(handler_called);
  3850. }
  3851. }
  3852. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3853. // Which of the two branches runs is decided by whether the query component
  3854. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3855. // an empty query and must still fall back to building one from
  3856. // `req.params`, while a non-empty query must win over `req.params`.
  3857. Server svr;
  3858. std::string target;
  3859. svr.Get("/foo", [&](const Request &req, Response &res) {
  3860. target = req.target;
  3861. res.status = StatusCode::OK_200;
  3862. });
  3863. auto port = svr.bind_to_any_port(HOST);
  3864. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3865. auto se = detail::scope_exit([&] {
  3866. svr.stop();
  3867. thread.join();
  3868. ASSERT_FALSE(svr.is_running());
  3869. });
  3870. svr.wait_until_ready();
  3871. {
  3872. // Trailing `?` -> empty query component -> `req.params` is used.
  3873. Client cli(HOST, port);
  3874. Request req;
  3875. req.method = "GET";
  3876. req.path = "/foo?";
  3877. req.params.emplace("a", "1");
  3878. target.clear();
  3879. auto res = cli.send(req);
  3880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3881. EXPECT_EQ("/foo?a=1", target);
  3882. }
  3883. {
  3884. // Non-empty query in `req.path` -> `req.params` is not appended.
  3885. Client cli(HOST, port);
  3886. Request req;
  3887. req.method = "GET";
  3888. req.path = "/foo?b=2";
  3889. req.params.emplace("a", "1");
  3890. target.clear();
  3891. auto res = cli.send(req);
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ("/foo?b=2", target);
  3894. }
  3895. }
  3896. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3897. Server svr;
  3898. svr.Get("/", [](const Request &req, Response &) {
  3899. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3900. });
  3901. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3902. auto se = detail::scope_exit([&] {
  3903. svr.stop();
  3904. thread.join();
  3905. ASSERT_FALSE(svr.is_running());
  3906. });
  3907. svr.wait_until_ready();
  3908. {
  3909. Client cli(HOST, PORT);
  3910. cli.set_path_encode(false);
  3911. auto res = cli.Get("/?something=%0A");
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. }
  3915. }
  3916. TEST(BindServerTest, BindDualStack) {
  3917. Server svr;
  3918. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3919. res.set_content("Hello World!", "text/plain");
  3920. });
  3921. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3922. auto se = detail::scope_exit([&] {
  3923. svr.stop();
  3924. thread.join();
  3925. ASSERT_FALSE(svr.is_running());
  3926. });
  3927. svr.wait_until_ready();
  3928. {
  3929. Client cli("127.0.0.1", PORT);
  3930. auto res = cli.Get("/1");
  3931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3932. EXPECT_EQ(StatusCode::OK_200, res->status);
  3933. EXPECT_EQ("Hello World!", res->body);
  3934. }
  3935. {
  3936. Client cli("::1", PORT);
  3937. auto res = cli.Get("/1");
  3938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3939. EXPECT_EQ(StatusCode::OK_200, res->status);
  3940. EXPECT_EQ("Hello World!", res->body);
  3941. }
  3942. }
  3943. TEST(BindServerTest, BindAndListenSeparately) {
  3944. Server svr;
  3945. int port = svr.bind_to_any_port("0.0.0.0");
  3946. ASSERT_TRUE(svr.is_valid());
  3947. ASSERT_TRUE(port > 0);
  3948. svr.stop();
  3949. }
  3950. // Reports whether anything is still listening on a loopback port. A plain
  3951. // connect() is used instead of a Client request because a socket left bound by
  3952. // mistake accepts the connection into its backlog and never answers, which
  3953. // would hang the test instead of failing it.
  3954. static bool is_loopback_port_accepting(int port) {
  3955. sockaddr_in addr{};
  3956. addr.sin_family = AF_INET;
  3957. addr.sin_port = htons(static_cast<uint16_t>(port));
  3958. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3959. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3960. EXPECT_NE(sock, INVALID_SOCKET);
  3961. if (sock == INVALID_SOCKET) { return false; }
  3962. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3963. static_cast<socklen_t>(sizeof(addr)));
  3964. detail::close_socket(sock);
  3965. return ret == 0;
  3966. }
  3967. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3968. Server svr;
  3969. auto port = svr.bind_to_any_port("127.0.0.1");
  3970. ASSERT_TRUE(port > 0);
  3971. svr.stop();
  3972. // bind_to_any_port() already called listen(2), so until stop() closed the
  3973. // descriptor the port kept accepting connections into the backlog. ASSERT
  3974. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3975. // below blocks forever in the accept loop.
  3976. ASSERT_FALSE(is_loopback_port_accepting(port));
  3977. // Nothing is left to accept on, so listen_after_bind() must report failure
  3978. // instead of returning success without ever serving.
  3979. EXPECT_FALSE(svr.listen_after_bind());
  3980. // The failed listen marks the server decommissioned, so a waiter returns
  3981. // instead of spinning forever.
  3982. svr.wait_until_ready();
  3983. }
  3984. #ifdef CPPHTTPLIB_SSL_ENABLED
  3985. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3987. CLIENT_CA_CERT_DIR);
  3988. int port = svr.bind_to_any_port("0.0.0.0");
  3989. ASSERT_TRUE(svr.is_valid());
  3990. ASSERT_TRUE(port > 0);
  3991. svr.stop();
  3992. }
  3993. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3994. // or a rejected CustomRoute() registration would not stop the server binding.
  3995. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3997. CLIENT_CA_CERT_DIR);
  3998. ASSERT_TRUE(svr.is_valid());
  3999. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4000. EXPECT_FALSE(svr.is_valid());
  4001. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4002. }
  4003. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4004. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4005. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4006. int port = svr.bind_to_any_port("0.0.0.0");
  4007. ASSERT_TRUE(svr.is_valid());
  4008. ASSERT_TRUE(port > 0);
  4009. svr.stop();
  4010. }
  4011. TEST(BindServerTest, UpdateCertsPem) {
  4012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4013. int port = svr.bind_to_any_port("0.0.0.0");
  4014. ASSERT_TRUE(svr.is_valid());
  4015. ASSERT_TRUE(port > 0);
  4016. // Read PEM files
  4017. std::string cert_pem, key_pem, ca_pem;
  4018. read_file(SERVER_CERT_FILE, cert_pem);
  4019. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4020. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4021. // Update server certificates using PEM API
  4022. ASSERT_TRUE(
  4023. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4024. ASSERT_TRUE(svr.is_valid());
  4025. svr.stop();
  4026. }
  4027. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4028. // Start server with client CA (enables client auth)
  4029. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4030. ASSERT_TRUE(svr.is_valid());
  4031. bool handler_called = false;
  4032. svr.Get("/test", [&](const Request &req, Response &res) {
  4033. handler_called = true;
  4034. // Verify client certificate is present
  4035. auto cert = req.peer_cert();
  4036. EXPECT_TRUE(static_cast<bool>(cert));
  4037. res.set_content("ok", "text/plain");
  4038. });
  4039. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4040. auto se = detail::scope_exit([&] {
  4041. svr.stop();
  4042. t.join();
  4043. ASSERT_FALSE(svr.is_running());
  4044. });
  4045. svr.wait_until_ready();
  4046. // Read PEM files
  4047. std::string cert_pem, key_pem, ca_pem;
  4048. read_file(SERVER_CERT_FILE, cert_pem);
  4049. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4050. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4051. // Update server certificates and client CA using PEM API while server running
  4052. ASSERT_TRUE(
  4053. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4054. // Connect with client certificate
  4055. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4056. cli.enable_server_certificate_verification(false);
  4057. cli.set_connection_timeout(30);
  4058. auto res = cli.Get("/test");
  4059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4060. ASSERT_EQ(StatusCode::OK_200, res->status);
  4061. ASSERT_TRUE(handler_called);
  4062. EXPECT_EQ("ok", res->body);
  4063. }
  4064. // Puts a CA that did not sign the client's certificate in the old one's place.
  4065. static bool replace_client_ca(SSLServer &svr) {
  4066. std::string cert_pem, key_pem, ca_pem;
  4067. read_file(SERVER_CERT_FILE, cert_pem);
  4068. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4069. read_file(SERVER_CERT2_FILE, ca_pem);
  4070. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4071. ca_pem.c_str());
  4072. }
  4073. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4075. ASSERT_TRUE(svr.is_valid());
  4076. svr.Get("/test", [](const Request &, Response &res) {
  4077. res.set_content("ok", "text/plain");
  4078. });
  4079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4080. auto se = detail::scope_exit([&] {
  4081. svr.stop();
  4082. t.join();
  4083. ASSERT_FALSE(svr.is_running());
  4084. });
  4085. svr.wait_until_ready();
  4086. auto get = [] {
  4087. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4088. cli.enable_server_certificate_verification(false);
  4089. return cli.Get("/test");
  4090. };
  4091. ASSERT_TRUE(get());
  4092. ASSERT_TRUE(replace_client_ca(svr));
  4093. EXPECT_FALSE(get());
  4094. }
  4095. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4096. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4098. ASSERT_TRUE(svr.is_valid());
  4099. tls::set_verify_callback(svr.tls_context(),
  4100. [](const tls::VerifyContext &) -> bool {
  4101. throw std::runtime_error("verify");
  4102. });
  4103. svr.Get("/test", [](const Request &, Response &res) {
  4104. res.set_content("ok", "text/plain");
  4105. });
  4106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4107. auto se = detail::scope_exit([&] {
  4108. svr.stop();
  4109. t.join();
  4110. ASSERT_FALSE(svr.is_running());
  4111. });
  4112. svr.wait_until_ready();
  4113. auto get = [] {
  4114. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4115. cli.enable_server_certificate_verification(false);
  4116. return cli.Get("/test");
  4117. };
  4118. EXPECT_FALSE(get());
  4119. // The handshake is over, so an update does not wait for it.
  4120. std::string cert_pem, key_pem;
  4121. read_file(SERVER_CERT_FILE, cert_pem);
  4122. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4123. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4124. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4125. return v.preverify_ok;
  4126. });
  4127. auto res = get();
  4128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4129. EXPECT_EQ("ok", res->body);
  4130. }
  4131. #endif
  4132. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4133. // Sends each request over a new connection with a client certificate,
  4134. // resuming the session of the one before when there is one.
  4135. class ResumingClient {
  4136. public:
  4137. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4138. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4139. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4140. SSL_FILETYPE_PEM);
  4141. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4142. // callback, not through SSL_get1_session().
  4143. SSL_CTX_set_app_data(ctx_, this);
  4144. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4145. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4146. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4147. auto self = static_cast<ResumingClient *>(
  4148. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4149. SSL_SESSION_free(self->session_);
  4150. self->session_ = session;
  4151. return 1; // Keeps the reference
  4152. });
  4153. }
  4154. ~ResumingClient() {
  4155. SSL_SESSION_free(session_);
  4156. SSL_CTX_free(ctx_);
  4157. }
  4158. // Tells whether the request was answered.
  4159. bool get() {
  4160. auto error = Error::Success;
  4161. auto sock = detail::create_client_socket(
  4162. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4163. /*connection_timeout_sec=*/5, 0,
  4164. /*read_timeout_sec=*/5, 0,
  4165. /*write_timeout_sec=*/5, 0, std::string(), error);
  4166. if (sock == INVALID_SOCKET) { return false; }
  4167. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4168. auto ssl = SSL_new(ctx_);
  4169. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4170. SSL_set_fd(ssl, static_cast<int>(sock));
  4171. if (session_) { SSL_set_session(ssl, session_); }
  4172. if (SSL_connect(ssl) != 1) { return false; }
  4173. reused_ = SSL_session_reused(ssl) == 1;
  4174. // Reading the response also takes in a TLS 1.3 session ticket.
  4175. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4176. "Connection: close\r\n\r\n";
  4177. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4178. std::string res;
  4179. char buf[256];
  4180. int n;
  4181. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4182. res.append(buf, static_cast<size_t>(n));
  4183. }
  4184. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4185. SSL_shutdown(ssl);
  4186. return res.find("200 OK") != std::string::npos;
  4187. }
  4188. // Whether the last connection resumed a session
  4189. bool reused() const { return reused_; }
  4190. private:
  4191. SSL_CTX *ctx_;
  4192. SSL_SESSION *session_ = nullptr;
  4193. bool reused_ = false;
  4194. };
  4195. // A client that resumes its session gets through, but not once the client CA
  4196. // has changed, as a resumed session does not show the certificate again.
  4197. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4198. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4199. ASSERT_TRUE(svr.is_valid());
  4200. svr.Get("/test", [](const Request &, Response &res) {
  4201. res.set_content("ok", "text/plain");
  4202. });
  4203. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4204. auto se = detail::scope_exit([&] {
  4205. svr.stop();
  4206. t.join();
  4207. ASSERT_FALSE(svr.is_running());
  4208. });
  4209. svr.wait_until_ready();
  4210. ResumingClient cli;
  4211. ASSERT_TRUE(cli.get());
  4212. ASSERT_TRUE(cli.get());
  4213. EXPECT_TRUE(cli.reused());
  4214. ASSERT_TRUE(replace_client_ca(svr));
  4215. EXPECT_FALSE(cli.get());
  4216. }
  4217. // A resumed session does not show the certificate again, so the server does
  4218. // not resume one with a verify callback to run on it.
  4219. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4221. ASSERT_TRUE(svr.is_valid());
  4222. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4223. return v.preverify_ok;
  4224. });
  4225. svr.Get("/test", [](const Request &, Response &res) {
  4226. res.set_content("ok", "text/plain");
  4227. });
  4228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4229. auto se = detail::scope_exit([&] {
  4230. svr.stop();
  4231. t.join();
  4232. ASSERT_FALSE(svr.is_running());
  4233. });
  4234. svr.wait_until_ready();
  4235. ResumingClient cli;
  4236. ASSERT_TRUE(cli.get());
  4237. ASSERT_TRUE(cli.get());
  4238. EXPECT_FALSE(cli.reused());
  4239. }
  4240. #endif
  4241. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4242. // wolfSSL shares its session cache between contexts, so a resumed session
  4243. // could carry a client certificate checked against another server's CA, or
  4244. // against a client CA since replaced.
  4245. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4247. ASSERT_TRUE(svr.is_valid());
  4248. // Trusts a CA that did not sign the client's certificate.
  4249. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4250. ASSERT_TRUE(other.is_valid());
  4251. for (auto s : {&svr, &other}) {
  4252. s->Get("/test", [](const Request &, Response &res) {
  4253. res.set_content("ok", "text/plain");
  4254. });
  4255. }
  4256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4257. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4258. auto se = detail::scope_exit([&] {
  4259. other.stop();
  4260. svr.stop();
  4261. t2.join();
  4262. t.join();
  4263. });
  4264. svr.wait_until_ready();
  4265. other.wait_until_ready();
  4266. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4267. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4268. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4269. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4270. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4271. ASSERT_EQ(WOLFSSL_SUCCESS,
  4272. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4273. WOLFSSL_FILETYPE_PEM));
  4274. WOLFSSL_SESSION *session = nullptr;
  4275. auto session_se = detail::scope_exit([&] {
  4276. if (session) { wolfSSL_SESSION_free(session); }
  4277. });
  4278. // A request over a new connection, resuming `session` when there is one and
  4279. // keeping the connection's own in its place. Tells whether it was answered.
  4280. auto get = [&](int port) {
  4281. auto error = Error::Success;
  4282. auto sock = detail::create_client_socket(
  4283. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4284. /*connection_timeout_sec=*/5, 0,
  4285. /*read_timeout_sec=*/5, 0,
  4286. /*write_timeout_sec=*/5, 0, std::string(), error);
  4287. if (sock == INVALID_SOCKET) { return false; }
  4288. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4289. auto ssl = wolfSSL_new(ctx);
  4290. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4291. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4292. if (session) { wolfSSL_set_session(ssl, session); }
  4293. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4294. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4295. "Connection: close\r\n\r\n";
  4296. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4297. std::string res;
  4298. char buf[256];
  4299. int n;
  4300. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4301. res.append(buf, static_cast<size_t>(n));
  4302. }
  4303. wolfSSL_shutdown(ssl);
  4304. if (session) { wolfSSL_SESSION_free(session); }
  4305. session = wolfSSL_get1_session(ssl);
  4306. return res.find("200 OK") != std::string::npos;
  4307. };
  4308. ASSERT_TRUE(get(PORT));
  4309. EXPECT_FALSE(get(PORT + 1));
  4310. ASSERT_TRUE(get(PORT));
  4311. ASSERT_TRUE(replace_client_ca(svr));
  4312. EXPECT_FALSE(get(PORT));
  4313. }
  4314. #endif
  4315. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4317. ASSERT_TRUE(svr.is_valid());
  4318. svr.Get("/test", [](const Request &, Response &res) {
  4319. res.set_content("ok", "text/plain");
  4320. });
  4321. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4322. auto se = detail::scope_exit([&] {
  4323. svr.stop();
  4324. t.join();
  4325. ASSERT_FALSE(svr.is_running());
  4326. });
  4327. svr.wait_until_ready();
  4328. // A connection that sends no ClientHello keeps its handshake in progress,
  4329. // once the server has had a moment to start it.
  4330. auto error = Error::Success;
  4331. auto sock = detail::create_client_socket(
  4332. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4333. /*connection_timeout_sec=*/5, 0,
  4334. /*read_timeout_sec=*/5, 0,
  4335. /*write_timeout_sec=*/5, 0, std::string(), error);
  4336. ASSERT_NE(INVALID_SOCKET, sock);
  4337. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4338. std::string cert_pem, key_pem;
  4339. read_file(SERVER_CERT_FILE, cert_pem);
  4340. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4341. auto update = std::async(std::launch::async, [&]() {
  4342. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4343. });
  4344. EXPECT_EQ(std::future_status::timeout,
  4345. update.wait_for(std::chrono::milliseconds(200)));
  4346. detail::close_socket(sock);
  4347. EXPECT_TRUE(update.get());
  4348. SSLClient cli(HOST, PORT);
  4349. cli.enable_server_certificate_verification(false);
  4350. auto res = cli.Get("/test");
  4351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. }
  4354. #endif
  4355. TEST(ErrorHandlerTest, ContentLength) {
  4356. Server svr;
  4357. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4358. res.status = StatusCode::OK_200;
  4359. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4360. "text/html"); // <= Content-Length still 13
  4361. });
  4362. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4363. res.set_content("Hello World!\n", "text/plain");
  4364. res.status = 524;
  4365. });
  4366. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4367. auto se = detail::scope_exit([&] {
  4368. svr.stop();
  4369. thread.join();
  4370. ASSERT_FALSE(svr.is_running());
  4371. });
  4372. svr.wait_until_ready();
  4373. {
  4374. Client cli(HOST, PORT);
  4375. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4379. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4380. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4381. }
  4382. }
  4383. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4384. TEST(ExceptionTest, WithoutExceptionHandler) {
  4385. Server svr;
  4386. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4387. throw std::runtime_error("exception...");
  4388. });
  4389. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4390. throw std::runtime_error("exception\r\n...");
  4391. });
  4392. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4393. auto se = detail::scope_exit([&] {
  4394. svr.stop();
  4395. listen_thread.join();
  4396. ASSERT_FALSE(svr.is_running());
  4397. });
  4398. svr.wait_until_ready();
  4399. Client cli("localhost", PORT);
  4400. {
  4401. auto res = cli.Get("/exception");
  4402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4403. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4404. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4405. }
  4406. {
  4407. auto res = cli.Get("/unknown");
  4408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4409. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4410. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4411. }
  4412. }
  4413. TEST(ExceptionTest, WithExceptionHandler) {
  4414. Server svr;
  4415. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4416. std::exception_ptr ep) {
  4417. EXPECT_FALSE(ep == nullptr);
  4418. try {
  4419. std::rethrow_exception(ep);
  4420. } catch (std::exception &e) {
  4421. EXPECT_EQ("abc", std::string(e.what()));
  4422. } catch (...) {}
  4423. res.status = StatusCode::InternalServerError_500;
  4424. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4425. "text/html"); // <= Content-Length still 13 at this point
  4426. });
  4427. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("Hello World!\n", "text/plain");
  4429. throw std::runtime_error("abc");
  4430. });
  4431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. for (size_t i = 0; i < 10; i++) {
  4439. Client cli(HOST, PORT);
  4440. for (size_t j = 0; j < 100; j++) {
  4441. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4443. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4444. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4445. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4446. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4447. }
  4448. cli.set_keep_alive(true);
  4449. for (size_t j = 0; j < 100; j++) {
  4450. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4452. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4453. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4454. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4455. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4456. }
  4457. }
  4458. }
  4459. TEST(ExceptionTest, AndErrorHandler) {
  4460. Server svr;
  4461. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4462. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4463. });
  4464. svr.set_exception_handler(
  4465. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4466. EXPECT_FALSE(ep == nullptr);
  4467. try {
  4468. std::rethrow_exception(ep);
  4469. } catch (std::exception &e) {
  4470. res.set_content(e.what(), "text/html");
  4471. } catch (...) {}
  4472. res.status = StatusCode::InternalServerError_500;
  4473. });
  4474. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4475. throw std::runtime_error("EXCEPTION");
  4476. });
  4477. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4478. res.set_content("ERROR", "text/html");
  4479. res.status = StatusCode::InternalServerError_500;
  4480. });
  4481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4482. auto se = detail::scope_exit([&] {
  4483. svr.stop();
  4484. thread.join();
  4485. ASSERT_FALSE(svr.is_running());
  4486. });
  4487. svr.wait_until_ready();
  4488. Client cli(HOST, PORT);
  4489. {
  4490. auto res = cli.Get("/exception");
  4491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4492. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4493. EXPECT_EQ("EXCEPTION", res->body);
  4494. }
  4495. {
  4496. auto res = cli.Get("/error");
  4497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4498. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4499. EXPECT_EQ("ERROR", res->body);
  4500. }
  4501. {
  4502. auto res = cli.Get("/invalid");
  4503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4504. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4505. EXPECT_EQ("NOT_FOUND", res->body);
  4506. }
  4507. }
  4508. #endif
  4509. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4510. // process_request() wraps only routing() in a try/catch, so an exception from
  4511. // any other user callback used to unwind into the task queue - which does not
  4512. // catch - and terminate the process. Each test below runs the server on a
  4513. // single worker thread: a guard that catches the exception but still loses the
  4514. // thread would otherwise be hidden by a spare worker serving the follow-up
  4515. // request. Note that a regression here aborts the whole test binary rather
  4516. // than failing one test.
  4517. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4518. Server svr;
  4519. svr.new_task_queue = [] { return new ThreadPool(1); };
  4520. std::atomic<int> reported{0};
  4521. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4522. if (err == Error::UserCallbackException) { reported++; }
  4523. });
  4524. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4525. res.set_content_provider(
  4526. 1024, "text/plain",
  4527. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4528. sink.write("hello", 5);
  4529. throw std::runtime_error("from the content provider");
  4530. });
  4531. });
  4532. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4533. res.set_content("ok", "text/plain");
  4534. });
  4535. auto port = svr.bind_to_any_port(HOST);
  4536. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4537. auto se = detail::scope_exit([&] {
  4538. svr.stop();
  4539. listen_thread.join();
  4540. ASSERT_FALSE(svr.is_running());
  4541. });
  4542. svr.wait_until_ready();
  4543. {
  4544. Client cli(HOST, port);
  4545. cli.set_read_timeout(5, 0);
  4546. EXPECT_FALSE(cli.Get("/throw"));
  4547. }
  4548. EXPECT_TRUE(svr.is_running());
  4549. EXPECT_EQ(1, reported.load());
  4550. // A request on a fresh connection is still served.
  4551. {
  4552. Client cli(HOST, port);
  4553. auto res = cli.Get("/ok");
  4554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4555. EXPECT_EQ(StatusCode::OK_200, res->status);
  4556. EXPECT_EQ("ok", res->body);
  4557. }
  4558. }
  4559. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4560. Server svr;
  4561. svr.new_task_queue = [] { return new ThreadPool(1); };
  4562. std::atomic<bool> should_throw{true};
  4563. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4564. res.set_content("hi", "text/plain");
  4565. });
  4566. svr.set_post_routing_handler(
  4567. [&](const Request & /*req*/, Response & /*res*/) {
  4568. if (should_throw) {
  4569. throw std::runtime_error("from the post-routing handler");
  4570. }
  4571. });
  4572. auto port = svr.bind_to_any_port(HOST);
  4573. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4574. auto se = detail::scope_exit([&] {
  4575. svr.stop();
  4576. listen_thread.join();
  4577. ASSERT_FALSE(svr.is_running());
  4578. });
  4579. svr.wait_until_ready();
  4580. {
  4581. Client cli(HOST, port);
  4582. cli.set_read_timeout(5, 0);
  4583. EXPECT_FALSE(cli.Get("/hi"));
  4584. }
  4585. EXPECT_TRUE(svr.is_running());
  4586. should_throw = false;
  4587. {
  4588. Client cli(HOST, port);
  4589. auto res = cli.Get("/hi");
  4590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ("hi", res->body);
  4593. }
  4594. }
  4595. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4596. // The guard reports the caught exception through the error logger, which is
  4597. // a user callback too. A logger that throws has to be contained as well, or
  4598. // the process would terminate from inside the catch.
  4599. Server svr;
  4600. svr.new_task_queue = [] { return new ThreadPool(1); };
  4601. std::atomic<int> reported{0};
  4602. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4603. if (err == Error::UserCallbackException) {
  4604. reported++;
  4605. throw std::runtime_error("from the error logger");
  4606. }
  4607. });
  4608. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4609. res.set_content_provider(
  4610. 1024, "text/plain",
  4611. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4612. sink.write("hello", 5);
  4613. throw std::runtime_error("from the content provider");
  4614. });
  4615. });
  4616. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4617. res.set_content("ok", "text/plain");
  4618. });
  4619. auto port = svr.bind_to_any_port(HOST);
  4620. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4621. auto se = detail::scope_exit([&] {
  4622. svr.stop();
  4623. listen_thread.join();
  4624. ASSERT_FALSE(svr.is_running());
  4625. });
  4626. svr.wait_until_ready();
  4627. {
  4628. Client cli(HOST, port);
  4629. cli.set_read_timeout(5, 0);
  4630. EXPECT_FALSE(cli.Get("/throw"));
  4631. }
  4632. EXPECT_TRUE(svr.is_running());
  4633. EXPECT_EQ(1, reported.load());
  4634. {
  4635. Client cli(HOST, port);
  4636. auto res = cli.Get("/ok");
  4637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4638. EXPECT_EQ(StatusCode::OK_200, res->status);
  4639. EXPECT_EQ("ok", res->body);
  4640. }
  4641. }
  4642. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4643. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4644. // so the exception unwinds through the ws::WebSocket object on its way to
  4645. // the guard. None of the HTTP cases above cross that.
  4646. Server svr;
  4647. svr.new_task_queue = [] { return new ThreadPool(1); };
  4648. std::atomic<int> reported{0};
  4649. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4650. if (err == Error::UserCallbackException) { reported++; }
  4651. });
  4652. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4653. throw std::runtime_error("from the WebSocket handler");
  4654. });
  4655. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4656. res.set_content("ok", "text/plain");
  4657. });
  4658. auto port = svr.bind_to_any_port(HOST);
  4659. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4660. auto se = detail::scope_exit([&] {
  4661. svr.stop();
  4662. listen_thread.join();
  4663. ASSERT_FALSE(svr.is_running());
  4664. });
  4665. svr.wait_until_ready();
  4666. {
  4667. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4668. "/ws");
  4669. auto res = client.connect();
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. // The server dropped the connection instead of dying.
  4672. std::string msg;
  4673. EXPECT_FALSE(client.read(msg));
  4674. client.close();
  4675. }
  4676. EXPECT_TRUE(svr.is_running());
  4677. EXPECT_EQ(1, reported.load());
  4678. {
  4679. Client cli(HOST, port);
  4680. auto res = cli.Get("/ok");
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. EXPECT_EQ(StatusCode::OK_200, res->status);
  4683. EXPECT_EQ("ok", res->body);
  4684. }
  4685. }
  4686. #ifdef CPPHTTPLIB_SSL_ENABLED
  4687. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4688. // SSLServer::process_and_close_socket() is a separate overload with its own
  4689. // guard, so it is exercised on its own.
  4690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4691. ASSERT_TRUE(svr.is_valid());
  4692. svr.new_task_queue = [] { return new ThreadPool(1); };
  4693. std::atomic<int> reported{0};
  4694. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4695. if (err == Error::UserCallbackException) { reported++; }
  4696. });
  4697. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4698. res.set_content_provider(
  4699. 1024, "text/plain",
  4700. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4701. sink.write("hello", 5);
  4702. throw std::runtime_error("from the content provider");
  4703. });
  4704. });
  4705. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4706. res.set_content("ok", "text/plain");
  4707. });
  4708. auto port = svr.bind_to_any_port(HOST);
  4709. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4710. auto se = detail::scope_exit([&] {
  4711. svr.stop();
  4712. listen_thread.join();
  4713. ASSERT_FALSE(svr.is_running());
  4714. });
  4715. svr.wait_until_ready();
  4716. {
  4717. SSLClient cli(HOST, port);
  4718. cli.enable_server_certificate_verification(false);
  4719. cli.set_read_timeout(5, 0);
  4720. EXPECT_FALSE(cli.Get("/throw"));
  4721. }
  4722. EXPECT_TRUE(svr.is_running());
  4723. EXPECT_EQ(1, reported.load());
  4724. {
  4725. SSLClient cli(HOST, port);
  4726. cli.enable_server_certificate_verification(false);
  4727. auto res = cli.Get("/ok");
  4728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("ok", res->body);
  4731. }
  4732. }
  4733. #endif
  4734. #endif
  4735. TEST(NoContentTest, ContentLength) {
  4736. Server svr;
  4737. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4738. res.status = StatusCode::NoContent_204;
  4739. });
  4740. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4741. auto se = detail::scope_exit([&] {
  4742. svr.stop();
  4743. thread.join();
  4744. ASSERT_FALSE(svr.is_running());
  4745. });
  4746. svr.wait_until_ready();
  4747. {
  4748. Client cli(HOST, PORT);
  4749. auto res = cli.Get("/hi");
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4752. // RFC 9110 8.6: none in a 204 response
  4753. EXPECT_FALSE(res->has_header("Content-Length"));
  4754. }
  4755. }
  4756. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4757. Server svr;
  4758. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4759. res.set_header("Content-Length", "5");
  4760. res.set_content("hello world", "text/plain");
  4761. });
  4762. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4763. // A body that reads as the last chunk, were it taken as chunked
  4764. res.set_header("Transfer-Encoding", "chunked");
  4765. res.set_content("0\r\n\r\n", "text/plain");
  4766. });
  4767. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4768. res.set_header("Content-Length", "2");
  4769. res.set_content_provider(5, "text/plain",
  4770. [](size_t offset, size_t length, DataSink &sink) {
  4771. sink.write(&"hello"[offset], length);
  4772. return true;
  4773. });
  4774. });
  4775. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4776. res.set_header("Content-Length", "1234");
  4777. });
  4778. thread t = thread([&] { svr.listen(HOST, PORT); });
  4779. auto se = detail::scope_exit([&] {
  4780. svr.stop();
  4781. t.join();
  4782. ASSERT_FALSE(svr.is_running());
  4783. });
  4784. svr.wait_until_ready();
  4785. Client cli(HOST, PORT);
  4786. cli.set_read_timeout(1, 0);
  4787. auto expect_body = [&](const Result &res, const std::string &body) {
  4788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4789. EXPECT_EQ(body, res->body);
  4790. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4791. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4792. };
  4793. Headers identity{{"Accept-Encoding", ""}};
  4794. expect_body(cli.Get("/body", identity), "hello world");
  4795. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4796. expect_body(cli.Get("/body",
  4797. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4798. "he");
  4799. expect_body(cli.Get("/provider", identity), "hello");
  4800. expect_body(cli.Get("/empty", identity), "");
  4801. // A HEAD response may give the length of the body a GET would get.
  4802. auto res = cli.Head("/empty");
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4805. }
  4806. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4807. Server svr;
  4808. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4809. res.set_content("short", "text/plain");
  4810. });
  4811. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4812. res.body += " with a footer";
  4813. res.set_header("Transfer-Encoding", "chunked");
  4814. });
  4815. thread t = thread([&] { svr.listen(HOST, PORT); });
  4816. auto se = detail::scope_exit([&] {
  4817. svr.stop();
  4818. t.join();
  4819. ASSERT_FALSE(svr.is_running());
  4820. });
  4821. svr.wait_until_ready();
  4822. Client cli(HOST, PORT);
  4823. cli.set_read_timeout(1, 0);
  4824. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. EXPECT_EQ("short with a footer", res->body);
  4827. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4828. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4829. }
  4830. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4831. Server svr;
  4832. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4833. res.set_header("Content-Length", "3");
  4834. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4835. sink.write("abc", 3);
  4836. sink.done();
  4837. return true;
  4838. });
  4839. });
  4840. thread t = thread([&] { svr.listen(HOST, PORT); });
  4841. auto se = detail::scope_exit([&] {
  4842. svr.stop();
  4843. t.join();
  4844. ASSERT_FALSE(svr.is_running());
  4845. });
  4846. svr.wait_until_ready();
  4847. Client cli(HOST, PORT);
  4848. cli.set_keep_alive(true);
  4849. auto res = cli.Get("/");
  4850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4851. EXPECT_EQ("abc", res->body);
  4852. EXPECT_FALSE(res->has_header("Content-Length"));
  4853. EXPECT_EQ("close", res->get_header_value("Connection"));
  4854. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4855. // No body to delimit
  4856. auto head = cli.Head("/");
  4857. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4858. EXPECT_FALSE(head->has_header("Connection"));
  4859. }
  4860. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4861. #ifdef CPPHTTPLIB_SSL_ENABLED
  4862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4863. ASSERT_TRUE(svr.is_valid());
  4864. #else
  4865. Server svr;
  4866. #endif
  4867. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4868. if (req.path == "/routing_handler") {
  4869. res.set_header("PRE_ROUTING", "on");
  4870. res.set_content("Routing Handler", "text/plain");
  4871. return httplib::Server::HandlerResponse::Handled;
  4872. }
  4873. return httplib::Server::HandlerResponse::Unhandled;
  4874. });
  4875. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4876. res.set_content("Error", "text/html");
  4877. });
  4878. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4879. if (req.path == "/routing_handler") {
  4880. res.set_header("POST_ROUTING", "on");
  4881. }
  4882. });
  4883. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4884. res.set_content("Hello World!\n", "text/plain");
  4885. });
  4886. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4887. auto se = detail::scope_exit([&] {
  4888. svr.stop();
  4889. thread.join();
  4890. ASSERT_FALSE(svr.is_running());
  4891. });
  4892. svr.wait_until_ready();
  4893. {
  4894. #ifdef CPPHTTPLIB_SSL_ENABLED
  4895. SSLClient cli(HOST, PORT);
  4896. cli.enable_server_certificate_verification(false);
  4897. #else
  4898. Client cli(HOST, PORT);
  4899. #endif
  4900. auto res = cli.Get("/routing_handler");
  4901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4902. EXPECT_EQ(StatusCode::OK_200, res->status);
  4903. EXPECT_EQ("Routing Handler", res->body);
  4904. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4905. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4906. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4907. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4908. }
  4909. {
  4910. #ifdef CPPHTTPLIB_SSL_ENABLED
  4911. SSLClient cli(HOST, PORT);
  4912. cli.enable_server_certificate_verification(false);
  4913. #else
  4914. Client cli(HOST, PORT);
  4915. #endif
  4916. auto res = cli.Get("/hi");
  4917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4918. EXPECT_EQ(StatusCode::OK_200, res->status);
  4919. EXPECT_EQ("Hello World!\n", res->body);
  4920. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4921. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4922. }
  4923. {
  4924. #ifdef CPPHTTPLIB_SSL_ENABLED
  4925. SSLClient cli(HOST, PORT);
  4926. cli.enable_server_certificate_verification(false);
  4927. #else
  4928. Client cli(HOST, PORT);
  4929. #endif
  4930. auto res = cli.Get("/aaa");
  4931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4932. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4933. EXPECT_EQ("Error", res->body);
  4934. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4935. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4936. }
  4937. }
  4938. TEST(RequestHandlerTest, PreRequestHandler) {
  4939. auto route_path = "/user/:user";
  4940. Server svr;
  4941. svr.Get("/hi", [](const Request &, Response &res) {
  4942. res.set_content("hi", "text/plain");
  4943. });
  4944. svr.Get(route_path, [](const Request &req, Response &res) {
  4945. res.set_content(req.path_params.at("user"), "text/plain");
  4946. });
  4947. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4948. if (req.matched_route == route_path) {
  4949. auto user = req.path_params.at("user");
  4950. if (user != "john") {
  4951. res.status = StatusCode::Forbidden_403;
  4952. res.set_content("error", "text/html");
  4953. return Server::HandlerResponse::Handled;
  4954. }
  4955. }
  4956. return Server::HandlerResponse::Unhandled;
  4957. });
  4958. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4959. auto se = detail::scope_exit([&] {
  4960. svr.stop();
  4961. thread.join();
  4962. ASSERT_FALSE(svr.is_running());
  4963. });
  4964. svr.wait_until_ready();
  4965. Client cli(HOST, PORT);
  4966. {
  4967. auto res = cli.Get("/hi");
  4968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("hi", res->body);
  4971. }
  4972. {
  4973. auto res = cli.Get("/user/john");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ("john", res->body);
  4977. }
  4978. {
  4979. auto res = cli.Get("/user/invalid-user");
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4982. EXPECT_EQ("error", res->body);
  4983. }
  4984. }
  4985. // The pre-request handler must run before the request body is read, so a
  4986. // rejected request never forces the server to buffer a (potentially large)
  4987. // body. Here the posted body is larger than the payload limit: if the body
  4988. // were read first the server would answer 413, but because the pre-request
  4989. // handler runs first it answers 403 and the body is never read.
  4990. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4991. Server svr;
  4992. svr.set_payload_max_length(8);
  4993. auto handler_ran = false;
  4994. svr.Post("/reject", [&](const Request &req, Response &res) {
  4995. handler_ran = true;
  4996. res.set_content(req.body, "text/plain");
  4997. });
  4998. svr.Post("/accept", [](const Request &req, Response &res) {
  4999. res.set_content(req.body, "text/plain");
  5000. });
  5001. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5002. if (req.matched_route == "/reject") {
  5003. res.status = StatusCode::Forbidden_403;
  5004. res.set_content("denied", "text/plain");
  5005. return Server::HandlerResponse::Handled;
  5006. }
  5007. return Server::HandlerResponse::Unhandled;
  5008. });
  5009. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5010. auto se = detail::scope_exit([&] {
  5011. svr.stop();
  5012. thread.join();
  5013. ASSERT_FALSE(svr.is_running());
  5014. });
  5015. svr.wait_until_ready();
  5016. Client cli(HOST, PORT);
  5017. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5018. // rejects with 403 before the body is read, so 413 is never reached.
  5019. {
  5020. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5023. EXPECT_EQ("denied", res->body);
  5024. EXPECT_FALSE(handler_ran);
  5025. }
  5026. // An approved route still reads the body and enforces the payload limit.
  5027. {
  5028. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5030. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5031. }
  5032. }
  5033. TEST(UserDataTest, BasicOperations) {
  5034. httplib::UserData ud;
  5035. // Initially empty
  5036. EXPECT_FALSE(ud.has("key"));
  5037. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5038. // set and get
  5039. ud.set("key", 42);
  5040. EXPECT_TRUE(ud.has("key"));
  5041. auto *p = ud.get<int>("key");
  5042. ASSERT_NE(nullptr, p);
  5043. EXPECT_EQ(42, *p);
  5044. // Type mismatch → nullptr
  5045. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5046. // Overwrite with different type
  5047. ud.set("key", std::string("hello"));
  5048. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5049. auto *s = ud.get<std::string>("key");
  5050. ASSERT_NE(nullptr, s);
  5051. EXPECT_EQ("hello", *s);
  5052. // erase
  5053. ud.erase("key");
  5054. EXPECT_FALSE(ud.has("key"));
  5055. // clear
  5056. ud.set("a", 1);
  5057. ud.set("b", 2);
  5058. ud.clear();
  5059. EXPECT_FALSE(ud.has("a"));
  5060. EXPECT_FALSE(ud.has("b"));
  5061. }
  5062. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5063. struct AuthCtx {
  5064. std::string user_id;
  5065. };
  5066. Server svr;
  5067. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5068. res.user_data.set("auth", AuthCtx{"alice"});
  5069. return Server::HandlerResponse::Unhandled;
  5070. });
  5071. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5072. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5073. ASSERT_NE(nullptr, ctx);
  5074. res.set_content("Hello " + ctx->user_id, "text/plain");
  5075. });
  5076. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5077. auto se = detail::scope_exit([&] {
  5078. svr.stop();
  5079. thread.join();
  5080. ASSERT_FALSE(svr.is_running());
  5081. });
  5082. svr.wait_until_ready();
  5083. Client cli(HOST, PORT);
  5084. auto res = cli.Get("/me");
  5085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5086. EXPECT_EQ(StatusCode::OK_200, res->status);
  5087. EXPECT_EQ("Hello alice", res->body);
  5088. }
  5089. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5090. struct RoleCtx {
  5091. std::string role;
  5092. };
  5093. Server svr;
  5094. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5095. res.user_data.set("role", RoleCtx{"admin"});
  5096. return Server::HandlerResponse::Unhandled;
  5097. });
  5098. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5099. auto *ctx = res.user_data.get<RoleCtx>("role");
  5100. ASSERT_NE(nullptr, ctx);
  5101. res.set_content(ctx->role, "text/plain");
  5102. });
  5103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5104. auto se = detail::scope_exit([&] {
  5105. svr.stop();
  5106. thread.join();
  5107. ASSERT_FALSE(svr.is_running());
  5108. });
  5109. svr.wait_until_ready();
  5110. Client cli(HOST, PORT);
  5111. auto res = cli.Get("/role");
  5112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5113. EXPECT_EQ(StatusCode::OK_200, res->status);
  5114. EXPECT_EQ("admin", res->body);
  5115. }
  5116. TEST(InvalidFormatTest, StatusCode) {
  5117. Server svr;
  5118. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5119. res.set_content("Hello World!\n", "text/plain");
  5120. res.status = 9999; // Status should be a three-digit code...
  5121. });
  5122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5123. auto se = detail::scope_exit([&] {
  5124. svr.stop();
  5125. thread.join();
  5126. ASSERT_FALSE(svr.is_running());
  5127. });
  5128. svr.wait_until_ready();
  5129. {
  5130. Client cli(HOST, PORT);
  5131. auto res = cli.Get("/hi");
  5132. ASSERT_FALSE(res);
  5133. }
  5134. }
  5135. TEST(URLFragmentTest, WithFragment) {
  5136. Server svr;
  5137. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5138. EXPECT_TRUE(req.target == "/hi");
  5139. });
  5140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5141. auto se = detail::scope_exit([&] {
  5142. svr.stop();
  5143. thread.join();
  5144. ASSERT_FALSE(svr.is_running());
  5145. });
  5146. svr.wait_until_ready();
  5147. {
  5148. Client cli(HOST, PORT);
  5149. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5150. EXPECT_TRUE(res);
  5151. EXPECT_EQ(StatusCode::OK_200, res->status);
  5152. res = cli.Get("/hi%23key1=val1=key2=val2");
  5153. EXPECT_TRUE(res);
  5154. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5155. }
  5156. }
  5157. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5158. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5159. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5160. Server svr;
  5161. std::vector<std::string> targets;
  5162. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5163. targets.push_back(req.target);
  5164. });
  5165. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5166. auto se = detail::scope_exit([&] {
  5167. svr.stop();
  5168. thread.join();
  5169. ASSERT_FALSE(svr.is_running());
  5170. });
  5171. svr.wait_until_ready();
  5172. Client cli(HOST, PORT);
  5173. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5174. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5175. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5176. // A '?' after the '#' belongs to the fragment, not to the query.
  5177. Request req;
  5178. req.method = "GET";
  5179. req.path = "/hi#f?x=1";
  5180. req.params.emplace("a", "1");
  5181. Response res;
  5182. auto error = Error::Success;
  5183. EXPECT_TRUE(cli.send(req, res, error));
  5184. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5185. "/hi?a=1"}),
  5186. targets);
  5187. }
  5188. TEST(HeaderWriter, SetHeaderWriter) {
  5189. Server svr;
  5190. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5191. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5192. return detail::write_headers(strm, hdrs);
  5193. });
  5194. svr.Get("/hi", [](const Request &req, Response &res) {
  5195. auto it = req.headers.find("CustomClientHeader");
  5196. EXPECT_TRUE(it != req.headers.end());
  5197. EXPECT_EQ(it->second, "CustomClientValue");
  5198. res.set_content("Hello World!\n", "text/plain");
  5199. });
  5200. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5201. auto se = detail::scope_exit([&] {
  5202. svr.stop();
  5203. thread.join();
  5204. ASSERT_FALSE(svr.is_running());
  5205. });
  5206. svr.wait_until_ready();
  5207. {
  5208. Client cli(HOST, PORT);
  5209. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5210. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5211. return detail::write_headers(strm, hdrs);
  5212. });
  5213. auto res = cli.Get("/hi");
  5214. EXPECT_TRUE(res);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. auto it = res->headers.find("CustomServerHeader");
  5217. EXPECT_TRUE(it != res->headers.end());
  5218. EXPECT_EQ(it->second, "CustomServerValue");
  5219. }
  5220. }
  5221. class ServerTest : public ::testing::Test {
  5222. protected:
  5223. ServerTest()
  5224. : cli_(HOST, PORT)
  5225. #ifdef CPPHTTPLIB_SSL_ENABLED
  5226. ,
  5227. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5228. #endif
  5229. {
  5230. #ifdef CPPHTTPLIB_SSL_ENABLED
  5231. cli_.enable_server_certificate_verification(false);
  5232. #endif
  5233. // Allow LARGE_DATA (100MB) responses
  5234. cli_.set_payload_max_length(200 * 1024 * 1024);
  5235. }
  5236. virtual void SetUp() {
  5237. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5238. svr_.set_payload_max_length(200 * 1024 * 1024);
  5239. svr_.set_mount_point("/", "./www");
  5240. svr_.set_mount_point("/mount", "./www2");
  5241. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5242. svr_.Get("/hi",
  5243. [&](const Request & /*req*/, Response &res) {
  5244. res.set_content("Hello World!", "text/plain");
  5245. })
  5246. .Get("/file_content",
  5247. [&](const Request & /*req*/, Response &res) {
  5248. res.set_file_content("./www/dir/test.html");
  5249. })
  5250. .Get("/file_content_with_content_type",
  5251. [&](const Request & /*req*/, Response &res) {
  5252. res.set_file_content("./www/file", "text/plain");
  5253. })
  5254. .Get("/invalid_file_content",
  5255. [&](const Request & /*req*/, Response &res) {
  5256. res.set_file_content("./www/dir/invalid_file_path");
  5257. })
  5258. .Get("/http_response_splitting",
  5259. [&](const Request & /*req*/, Response &res) {
  5260. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5261. EXPECT_EQ(0U, res.headers.size());
  5262. EXPECT_FALSE(res.has_header("a"));
  5263. res.set_header("a", "1\nSet-Cookie: a=1");
  5264. EXPECT_EQ(0U, res.headers.size());
  5265. EXPECT_FALSE(res.has_header("a"));
  5266. res.set_header("a", "1\rSet-Cookie: a=1");
  5267. EXPECT_EQ(0U, res.headers.size());
  5268. EXPECT_FALSE(res.has_header("a"));
  5269. res.set_header("a\r\nb", "0");
  5270. EXPECT_EQ(0U, res.headers.size());
  5271. EXPECT_FALSE(res.has_header("a"));
  5272. res.set_header("a\rb", "0");
  5273. EXPECT_EQ(0U, res.headers.size());
  5274. EXPECT_FALSE(res.has_header("a"));
  5275. res.set_header("a\nb", "0");
  5276. EXPECT_EQ(0U, res.headers.size());
  5277. EXPECT_FALSE(res.has_header("a"));
  5278. res.set_redirect("1\r\nSet-Cookie: a=1");
  5279. EXPECT_EQ(0U, res.headers.size());
  5280. EXPECT_FALSE(res.has_header("Location"));
  5281. })
  5282. .Get("/slow",
  5283. [&](const Request & /*req*/, Response &res) {
  5284. std::this_thread::sleep_for(std::chrono::seconds(4));
  5285. res.set_content("slow", "text/plain");
  5286. })
  5287. #if 0
  5288. .Post("/slowpost",
  5289. [&](const Request & /*req*/, Response &res) {
  5290. std::this_thread::sleep_for(std::chrono::seconds(2));
  5291. res.set_content("slow", "text/plain");
  5292. })
  5293. #endif
  5294. .Get("/remote_addr",
  5295. [&](const Request &req, Response &res) {
  5296. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5297. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5298. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5299. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5300. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5301. #endif
  5302. res.set_content(req.remote_addr, "text/plain");
  5303. })
  5304. .Get("/local_addr",
  5305. [&](const Request &req, Response &res) {
  5306. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5307. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5308. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5309. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5310. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5311. #endif
  5312. auto local_addr = req.local_addr;
  5313. auto local_port = std::to_string(req.local_port);
  5314. res.set_content(local_addr.append(":").append(local_port),
  5315. "text/plain");
  5316. })
  5317. .Get("/endwith%",
  5318. [&](const Request & /*req*/, Response &res) {
  5319. res.set_content("Hello World!", "text/plain");
  5320. })
  5321. .Get("/a\\+\\+b",
  5322. [&](const Request &req, Response &res) {
  5323. ASSERT_TRUE(req.has_param("a +b"));
  5324. auto val = req.get_param_value("a +b");
  5325. res.set_content(val, "text/plain");
  5326. })
  5327. .Get("/", [&](const Request & /*req*/,
  5328. Response &res) { res.set_redirect("/hi"); })
  5329. .Post("/1",
  5330. [](const Request & /*req*/, Response &res) {
  5331. res.set_redirect("/2", StatusCode::SeeOther_303);
  5332. })
  5333. .Get("/2",
  5334. [](const Request & /*req*/, Response &res) {
  5335. res.set_content("redirected.", "text/plain");
  5336. res.status = StatusCode::OK_200;
  5337. })
  5338. .Post("/person",
  5339. [&](const Request &req, Response &res) {
  5340. if (req.has_param("name") && req.has_param("note")) {
  5341. persons_[req.get_param_value("name")] =
  5342. req.get_param_value("note");
  5343. } else {
  5344. res.status = StatusCode::BadRequest_400;
  5345. }
  5346. })
  5347. .Put("/person",
  5348. [&](const Request &req, Response &res) {
  5349. if (req.has_param("name") && req.has_param("note")) {
  5350. persons_[req.get_param_value("name")] =
  5351. req.get_param_value("note");
  5352. } else {
  5353. res.status = StatusCode::BadRequest_400;
  5354. }
  5355. })
  5356. .Get("/person/(.*)",
  5357. [&](const Request &req, Response &res) {
  5358. string name = req.matches[1];
  5359. if (persons_.find(name) != persons_.end()) {
  5360. auto note = persons_[name];
  5361. res.set_content(note, "text/plain");
  5362. } else {
  5363. res.status = StatusCode::NotFound_404;
  5364. }
  5365. })
  5366. .Delete("/person",
  5367. [&](const Request &req, Response &res) {
  5368. if (req.has_param("name")) {
  5369. string name = req.get_param_value("name");
  5370. if (persons_.find(name) != persons_.end()) {
  5371. persons_.erase(name);
  5372. res.set_content("DELETED", "text/plain");
  5373. } else {
  5374. res.status = StatusCode::NotFound_404;
  5375. }
  5376. } else {
  5377. res.status = StatusCode::BadRequest_400;
  5378. }
  5379. })
  5380. .Post("/x-www-form-urlencoded-json",
  5381. [&](const Request &req, Response &res) {
  5382. auto json = req.get_param_value("json");
  5383. ASSERT_EQ(JSON_DATA, json);
  5384. res.set_content(json, "appliation/json");
  5385. res.status = StatusCode::OK_200;
  5386. })
  5387. .Get("/streamed-chunked",
  5388. [&](const Request & /*req*/, Response &res) {
  5389. res.set_chunked_content_provider(
  5390. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5391. sink.os << "123";
  5392. sink.os << "456";
  5393. sink.os << "789";
  5394. sink.done();
  5395. return true;
  5396. });
  5397. })
  5398. .Get("/streamed-chunked-with-prohibited-trailer",
  5399. [&](const Request & /*req*/, Response &res) {
  5400. auto i = new int(0);
  5401. // Declare both a prohibited trailer (Content-Length) and an
  5402. // allowed one
  5403. res.set_header("Trailer", "Content-Length, X-Allowed");
  5404. res.set_chunked_content_provider(
  5405. "text/plain",
  5406. [i](size_t /*offset*/, DataSink &sink) {
  5407. switch (*i) {
  5408. case 0: sink.os << "123"; break;
  5409. case 1: sink.os << "456"; break;
  5410. case 2: sink.os << "789"; break;
  5411. case 3: {
  5412. sink.done_with_trailer(
  5413. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5414. } break;
  5415. }
  5416. (*i)++;
  5417. return true;
  5418. },
  5419. [i](bool success) {
  5420. EXPECT_TRUE(success);
  5421. delete i;
  5422. });
  5423. })
  5424. .Get("/streamed-chunked2",
  5425. [&](const Request & /*req*/, Response &res) {
  5426. auto i = new int(0);
  5427. res.set_chunked_content_provider(
  5428. "text/plain",
  5429. [i](size_t /*offset*/, DataSink &sink) {
  5430. switch (*i) {
  5431. case 0: sink.os << "123"; break;
  5432. case 1: sink.os << "456"; break;
  5433. case 2: sink.os << "789"; break;
  5434. case 3: sink.done(); break;
  5435. }
  5436. (*i)++;
  5437. return true;
  5438. },
  5439. [i](bool success) {
  5440. EXPECT_TRUE(success);
  5441. delete i;
  5442. });
  5443. })
  5444. .Get("/streamed-chunked-with-trailer",
  5445. [&](const Request & /*req*/, Response &res) {
  5446. auto i = new int(0);
  5447. res.set_header("Trailer", "Dummy1, Dummy2");
  5448. res.set_chunked_content_provider(
  5449. "text/plain",
  5450. [i](size_t /*offset*/, DataSink &sink) {
  5451. switch (*i) {
  5452. case 0: sink.os << "123"; break;
  5453. case 1: sink.os << "456"; break;
  5454. case 2: sink.os << "789"; break;
  5455. case 3: {
  5456. sink.done_with_trailer(
  5457. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5458. } break;
  5459. }
  5460. (*i)++;
  5461. return true;
  5462. },
  5463. [i](bool success) {
  5464. EXPECT_TRUE(success);
  5465. delete i;
  5466. });
  5467. })
  5468. .Get("/streamed",
  5469. [&](const Request & /*req*/, Response &res) {
  5470. res.set_content_provider(
  5471. 6, "text/plain",
  5472. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5473. sink.os << (offset < 3 ? "a" : "b");
  5474. return true;
  5475. });
  5476. })
  5477. .Get("/streamed-without-length",
  5478. [&](const Request & /*req*/, Response &res) {
  5479. auto data = new std::string("abcdefg");
  5480. res.set_content_provider(
  5481. "text/plain",
  5482. [data](size_t offset, DataSink &sink) {
  5483. if (offset < data->size()) {
  5484. sink.os << data->substr(offset);
  5485. }
  5486. sink.done();
  5487. return true;
  5488. },
  5489. [data](bool success) {
  5490. EXPECT_TRUE(success);
  5491. delete data;
  5492. });
  5493. })
  5494. .Get("/streamed-with-range",
  5495. [&](const Request &req, Response &res) {
  5496. auto data = new std::string("abcdefg");
  5497. // An explicit status keeps the server from picking the 206 it
  5498. // would otherwise choose for a ranged request, so the response
  5499. // is not a partial representation.
  5500. auto status = req.get_param_value("status");
  5501. if (status == "200") {
  5502. res.status = StatusCode::OK_200;
  5503. } else if (status == "403") {
  5504. res.status = StatusCode::Forbidden_403;
  5505. }
  5506. res.set_content_provider(
  5507. data->size(), "text/plain",
  5508. [data](size_t offset, size_t length, DataSink &sink) {
  5509. size_t DATA_CHUNK_SIZE = 4;
  5510. const auto &d = *data;
  5511. auto out_len =
  5512. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5513. auto ret =
  5514. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5515. EXPECT_TRUE(ret);
  5516. return true;
  5517. },
  5518. [data, &req](bool success) {
  5519. EXPECT_EQ(success, !req.has_param("error"));
  5520. delete data;
  5521. });
  5522. })
  5523. .Get("/streamed-cancel",
  5524. [&](const Request & /*req*/, Response &res) {
  5525. res.set_content_provider(
  5526. size_t(-1), "text/plain",
  5527. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5528. sink.os << "data_chunk";
  5529. return true;
  5530. });
  5531. })
  5532. .Get("/regex-with-delimiter",
  5533. [&](const Request &req, Response & /*res*/) {
  5534. ASSERT_TRUE(req.has_param("key"));
  5535. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5536. })
  5537. .Get("/with-range",
  5538. [&](const Request & /*req*/, Response &res) {
  5539. res.set_content("abcdefg", "text/plain");
  5540. })
  5541. .Get("/test-start-time",
  5542. [&](const Request &req, Response & /*res*/) {
  5543. EXPECT_NE(req.start_time_,
  5544. std::chrono::steady_clock::time_point::min());
  5545. })
  5546. .Get("/with-range-customized-response",
  5547. [&](const Request & /*req*/, Response &res) {
  5548. res.status = StatusCode::BadRequest_400;
  5549. res.set_content(JSON_DATA, "application/json");
  5550. })
  5551. .Post("/chunked",
  5552. [&](const Request &req, Response & /*res*/) {
  5553. EXPECT_EQ(req.body, "dechunked post body");
  5554. })
  5555. .Post("/large-chunked",
  5556. [&](const Request &req, Response & /*res*/) {
  5557. std::string expected(6 * 30 * 1024u, 'a');
  5558. EXPECT_EQ(req.body, expected);
  5559. })
  5560. .Post("/multipart",
  5561. [&](const Request &req, Response & /*res*/) {
  5562. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5563. req.form.get_field_count("text2") +
  5564. req.form.get_field_count("file3") +
  5565. req.form.get_field_count("file4"));
  5566. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5567. req.form.get_file_count("file2"));
  5568. ASSERT_TRUE(!req.form.has_file("???"));
  5569. ASSERT_TRUE(!req.form.has_field("???"));
  5570. ASSERT_TRUE(req.body.empty());
  5571. {
  5572. const auto &text = req.form.get_field("text1");
  5573. EXPECT_EQ("text default", text);
  5574. }
  5575. {
  5576. const auto &text = req.form.get_field("text2");
  5577. EXPECT_EQ("aωb", text);
  5578. }
  5579. {
  5580. const auto &file = req.form.get_file("file1");
  5581. EXPECT_EQ("hello.txt", file.filename);
  5582. EXPECT_EQ("text/plain", file.content_type);
  5583. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5584. }
  5585. {
  5586. const auto &file = req.form.get_file("file2");
  5587. EXPECT_EQ("world.json", file.filename);
  5588. EXPECT_EQ("application/json", file.content_type);
  5589. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5590. }
  5591. {
  5592. const auto &text = req.form.get_field("file3");
  5593. EXPECT_EQ(0u, text.size());
  5594. }
  5595. {
  5596. const auto &text = req.form.get_field("file4");
  5597. EXPECT_EQ(0u, text.size());
  5598. }
  5599. })
  5600. .Post("/multipart/multi_file_values",
  5601. [&](const Request &req, Response & /*res*/) {
  5602. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5603. req.form.get_field_count("multi_text1"));
  5604. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5605. ASSERT_TRUE(!req.form.has_file("???"));
  5606. ASSERT_TRUE(!req.form.has_field("???"));
  5607. ASSERT_TRUE(req.body.empty());
  5608. {
  5609. const auto &text = req.form.get_field("text");
  5610. EXPECT_EQ("default text", text);
  5611. }
  5612. {
  5613. const auto &text1_values = req.form.get_fields("multi_text1");
  5614. EXPECT_EQ(2u, text1_values.size());
  5615. EXPECT_EQ("aaaaa", text1_values[0]);
  5616. EXPECT_EQ("bbbbb", text1_values[1]);
  5617. }
  5618. {
  5619. const auto &file1_values = req.form.get_files("multi_file1");
  5620. EXPECT_EQ(2u, file1_values.size());
  5621. auto file1 = file1_values[0];
  5622. EXPECT_EQ(file1.filename, "hello.txt");
  5623. EXPECT_EQ(file1.content_type, "text/plain");
  5624. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5625. auto file2 = file1_values[1];
  5626. EXPECT_EQ(file2.filename, "world.json");
  5627. EXPECT_EQ(file2.content_type, "application/json");
  5628. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5629. }
  5630. })
  5631. .Post("/empty",
  5632. [&](const Request &req, Response &res) {
  5633. EXPECT_EQ(req.body, "");
  5634. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5635. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5636. res.set_content("empty", "text/plain");
  5637. })
  5638. .Post("/empty-no-content-type",
  5639. [&](const Request &req, Response &res) {
  5640. EXPECT_EQ(req.body, "");
  5641. EXPECT_FALSE(req.has_header("Content-Type"));
  5642. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5643. res.set_content("empty-no-content-type", "text/plain");
  5644. })
  5645. .Post("/path-only",
  5646. [&](const Request &req, Response &res) {
  5647. EXPECT_EQ(req.body, "");
  5648. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5649. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5650. res.set_content("path-only", "text/plain");
  5651. })
  5652. .Post("/path-headers-only",
  5653. [&](const Request &req, Response &res) {
  5654. EXPECT_EQ(req.body, "");
  5655. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5656. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5657. EXPECT_EQ("world", req.get_header_value("hello"));
  5658. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5659. res.set_content("path-headers-only", "text/plain");
  5660. })
  5661. .Post("/post-large",
  5662. [&](const Request &req, Response &res) {
  5663. EXPECT_EQ(req.body, LARGE_DATA);
  5664. res.set_content(req.body, "text/plain");
  5665. })
  5666. .Post("/post-loopback",
  5667. [&](const Request &, Response &res,
  5668. ContentReader const &content_reader) {
  5669. std::string body;
  5670. content_reader([&](const char *data, size_t data_length) {
  5671. body.append(data, data_length);
  5672. return true;
  5673. });
  5674. res.set_content(body, "text/plain");
  5675. })
  5676. .Put("/put-loopback",
  5677. [&](const Request &, Response &res,
  5678. ContentReader const &content_reader) {
  5679. std::string body;
  5680. content_reader([&](const char *data, size_t data_length) {
  5681. body.append(data, data_length);
  5682. return true;
  5683. });
  5684. res.set_content(body, "text/plain");
  5685. })
  5686. .Patch("/patch-loopback",
  5687. [&](const Request &, Response &res,
  5688. ContentReader const &content_reader) {
  5689. std::string body;
  5690. content_reader([&](const char *data, size_t data_length) {
  5691. body.append(data, data_length);
  5692. return true;
  5693. });
  5694. res.set_content(body, "text/plain");
  5695. })
  5696. .Put("/empty-no-content-type",
  5697. [&](const Request &req, Response &res) {
  5698. EXPECT_EQ(req.body, "");
  5699. EXPECT_FALSE(req.has_header("Content-Type"));
  5700. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5701. res.set_content("empty-no-content-type", "text/plain");
  5702. })
  5703. .Put("/put",
  5704. [&](const Request &req, Response &res) {
  5705. EXPECT_EQ(req.body, "PUT");
  5706. res.set_content(req.body, "text/plain");
  5707. })
  5708. .Put("/put-large",
  5709. [&](const Request &req, Response &res) {
  5710. EXPECT_EQ(req.body, LARGE_DATA);
  5711. res.set_content(req.body, "text/plain");
  5712. })
  5713. .Patch("/patch",
  5714. [&](const Request &req, Response &res) {
  5715. EXPECT_EQ(req.body, "PATCH");
  5716. res.set_content(req.body, "text/plain");
  5717. })
  5718. .Delete("/delete",
  5719. [&](const Request & /*req*/, Response &res) {
  5720. res.set_content("DELETE", "text/plain");
  5721. })
  5722. .Delete("/delete-body",
  5723. [&](const Request &req, Response &res) {
  5724. EXPECT_EQ(req.body, "content");
  5725. res.set_content(req.body, "text/plain");
  5726. })
  5727. .Options(R"(\*)",
  5728. [&](const Request & /*req*/, Response &res) {
  5729. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5730. })
  5731. .CustomRoute("PROPFIND", "/dav/:id",
  5732. [&](const Request &req, Response &res) {
  5733. res.set_header("x-body-size",
  5734. std::to_string(req.body.size()));
  5735. res.set_header("x-matched-route", req.matched_route);
  5736. res.set_header("x-dav-id", req.path_params.at("id"));
  5737. res.status = StatusCode::MultiStatus_207;
  5738. res.set_content(req.body, "application/xml");
  5739. })
  5740. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5741. [&](const Request &req, Response &res) {
  5742. res.set_header("x-dav-match", req.matches[1]);
  5743. res.status = StatusCode::MultiStatus_207;
  5744. })
  5745. .CustomRoute("MKCOL", "/dav-mkcol",
  5746. [&](const Request &req, Response &res) {
  5747. EXPECT_TRUE(req.body.empty());
  5748. res.status = StatusCode::Created_201;
  5749. })
  5750. .CustomRoute(
  5751. "REPORT", "/dav-report",
  5752. [&](const Request & /*req*/, Response &res,
  5753. const ContentReader &content_reader) {
  5754. std::string body;
  5755. content_reader([&](const char *data, size_t data_length) {
  5756. body.append(data, data_length);
  5757. return true;
  5758. });
  5759. res.set_header("x-body-size", std::to_string(body.size()));
  5760. res.status = StatusCode::MultiStatus_207;
  5761. res.set_content(body, "application/xml");
  5762. })
  5763. .Get("/request-target",
  5764. [&](const Request &req, Response & /*res*/) {
  5765. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5766. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5767. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5768. })
  5769. .Get("/long-query-value",
  5770. [&](const Request &req, Response & /*res*/) {
  5771. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5772. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5773. })
  5774. .Get("/too-long-query-value",
  5775. [&](const Request &req, Response & /*res*/) {
  5776. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5777. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5778. })
  5779. .Get("/array-param",
  5780. [&](const Request &req, Response & /*res*/) {
  5781. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5782. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5783. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5784. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5785. })
  5786. .Get("/array-param-values",
  5787. [&](const Request &req, Response & /*res*/) {
  5788. auto values = req.get_param_values("array");
  5789. EXPECT_EQ(3u, values.size());
  5790. EXPECT_EQ("value1", values[0]);
  5791. EXPECT_EQ("value2", values[1]);
  5792. EXPECT_EQ("value3", values[2]);
  5793. auto empty = req.get_param_values("nonexistent");
  5794. EXPECT_TRUE(empty.empty());
  5795. })
  5796. .Post("/validate-no-multiple-headers",
  5797. [&](const Request &req, Response & /*res*/) {
  5798. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5799. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5800. })
  5801. .Post("/content_receiver",
  5802. [&](const Request &req, Response &res,
  5803. const ContentReader &content_reader) {
  5804. if (req.is_multipart_form_data()) {
  5805. std::vector<FormData> items;
  5806. content_reader(
  5807. [&](const FormData &file) {
  5808. items.push_back(file);
  5809. return true;
  5810. },
  5811. [&](const char *data, size_t data_length) {
  5812. items.back().content.append(data, data_length);
  5813. return true;
  5814. });
  5815. EXPECT_EQ(5u, items.size());
  5816. {
  5817. const auto &file = get_file_value(items, "text1");
  5818. EXPECT_TRUE(file.filename.empty());
  5819. EXPECT_EQ("text default", file.content);
  5820. }
  5821. {
  5822. const auto &file = get_file_value(items, "text2");
  5823. EXPECT_TRUE(file.filename.empty());
  5824. EXPECT_EQ("aωb", file.content);
  5825. }
  5826. {
  5827. const auto &file = get_file_value(items, "file1");
  5828. EXPECT_EQ("hello.txt", file.filename);
  5829. EXPECT_EQ("text/plain", file.content_type);
  5830. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5831. }
  5832. {
  5833. const auto &file = get_file_value(items, "file2");
  5834. EXPECT_EQ("world.json", file.filename);
  5835. EXPECT_EQ("application/json", file.content_type);
  5836. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5837. }
  5838. {
  5839. const auto &file = get_file_value(items, "file3");
  5840. EXPECT_TRUE(file.filename.empty());
  5841. EXPECT_EQ("application/octet-stream", file.content_type);
  5842. EXPECT_EQ(0u, file.content.size());
  5843. }
  5844. } else {
  5845. std::string body;
  5846. content_reader([&](const char *data, size_t data_length) {
  5847. EXPECT_EQ(7U, data_length);
  5848. body.append(data, data_length);
  5849. return true;
  5850. });
  5851. EXPECT_EQ(body, "content");
  5852. res.set_content(body, "text/plain");
  5853. }
  5854. })
  5855. .Put("/content_receiver",
  5856. [&](const Request & /*req*/, Response &res,
  5857. const ContentReader &content_reader) {
  5858. std::string body;
  5859. content_reader([&](const char *data, size_t data_length) {
  5860. body.append(data, data_length);
  5861. return true;
  5862. });
  5863. EXPECT_EQ(body, "content");
  5864. res.set_content(body, "text/plain");
  5865. })
  5866. .Patch("/content_receiver",
  5867. [&](const Request & /*req*/, Response &res,
  5868. const ContentReader &content_reader) {
  5869. std::string body;
  5870. content_reader([&](const char *data, size_t data_length) {
  5871. body.append(data, data_length);
  5872. return true;
  5873. });
  5874. EXPECT_EQ(body, "content");
  5875. res.set_content(body, "text/plain");
  5876. })
  5877. .Post("/query-string-and-body",
  5878. [&](const Request &req, Response & /*res*/) {
  5879. ASSERT_TRUE(req.has_param("key"));
  5880. EXPECT_EQ(req.get_param_value("key"), "value");
  5881. EXPECT_EQ(req.body, "content");
  5882. })
  5883. .Get("/last-request",
  5884. [&](const Request &req, Response & /*res*/) {
  5885. EXPECT_EQ("close", req.get_header_value("Connection"));
  5886. })
  5887. .Get(R"(/redirect/(\d+))",
  5888. [&](const Request &req, Response &res) {
  5889. auto num = std::stoi(req.matches[1]) + 1;
  5890. std::string url = "/redirect/" + std::to_string(num);
  5891. res.set_redirect(url);
  5892. })
  5893. .Post("/binary",
  5894. [&](const Request &req, Response &res) {
  5895. EXPECT_EQ(4U, req.body.size());
  5896. EXPECT_EQ("application/octet-stream",
  5897. req.get_header_value("Content-Type"));
  5898. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5899. res.set_content(req.body, "application/octet-stream");
  5900. })
  5901. .Put("/binary",
  5902. [&](const Request &req, Response &res) {
  5903. EXPECT_EQ(4U, req.body.size());
  5904. EXPECT_EQ("application/octet-stream",
  5905. req.get_header_value("Content-Type"));
  5906. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5907. res.set_content(req.body, "application/octet-stream");
  5908. })
  5909. .Patch("/binary",
  5910. [&](const Request &req, Response &res) {
  5911. EXPECT_EQ(4U, req.body.size());
  5912. EXPECT_EQ("application/octet-stream",
  5913. req.get_header_value("Content-Type"));
  5914. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5915. res.set_content(req.body, "application/octet-stream");
  5916. })
  5917. .Delete("/binary",
  5918. [&](const Request &req, Response &res) {
  5919. EXPECT_EQ(4U, req.body.size());
  5920. EXPECT_EQ("application/octet-stream",
  5921. req.get_header_value("Content-Type"));
  5922. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5923. res.set_content(req.body, "application/octet-stream");
  5924. })
  5925. .Get("/issue1772",
  5926. [&](const Request & /*req*/, Response &res) {
  5927. res.status = 401;
  5928. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5929. })
  5930. .Delete("/issue609",
  5931. [](const httplib::Request &, httplib::Response &res,
  5932. const httplib::ContentReader &) {
  5933. res.set_content("ok", "text/plain");
  5934. })
  5935. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5936. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5937. .Get("/compress",
  5938. [&](const Request & /*req*/, Response &res) {
  5939. res.set_content(
  5940. "12345678901234567890123456789012345678901234567890123456789"
  5941. "01234567890123456789012345678901234567890",
  5942. "text/plain");
  5943. })
  5944. .Get("/compress-with-charset",
  5945. [&](const Request & /*req*/, Response &res) {
  5946. res.set_content(
  5947. "12345678901234567890123456789012345678901234567890123456789"
  5948. "01234567890123456789012345678901234567890",
  5949. "application/json; charset=utf-8");
  5950. })
  5951. .Get("/nocompress",
  5952. [&](const Request & /*req*/, Response &res) {
  5953. res.set_content(
  5954. "12345678901234567890123456789012345678901234567890123456789"
  5955. "01234567890123456789012345678901234567890",
  5956. "application/octet-stream");
  5957. })
  5958. .Post("/compress-multipart",
  5959. [&](const Request &req, Response & /*res*/) {
  5960. EXPECT_EQ(2u, req.form.fields.size());
  5961. ASSERT_TRUE(!req.form.has_field("???"));
  5962. {
  5963. const auto &text = req.form.get_field("key1");
  5964. EXPECT_EQ("test", text);
  5965. }
  5966. {
  5967. const auto &text = req.form.get_field("key2");
  5968. EXPECT_EQ("--abcdefg123", text);
  5969. }
  5970. })
  5971. #endif
  5972. ;
  5973. persons_["john"] = "programmer";
  5974. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5975. svr_.wait_until_ready();
  5976. }
  5977. virtual void TearDown() {
  5978. svr_.stop();
  5979. if (!request_threads_.empty()) {
  5980. std::this_thread::sleep_for(std::chrono::seconds(1));
  5981. for (auto &t : request_threads_) {
  5982. t.join();
  5983. }
  5984. }
  5985. t_.join();
  5986. }
  5987. map<string, string> persons_;
  5988. #ifdef CPPHTTPLIB_SSL_ENABLED
  5989. SSLClient cli_;
  5990. SSLServer svr_;
  5991. #else
  5992. Client cli_;
  5993. Server svr_;
  5994. #endif
  5995. thread t_;
  5996. std::vector<thread> request_threads_;
  5997. };
  5998. TEST_F(ServerTest, GetMethod200) {
  5999. auto res = cli_.Get("/hi");
  6000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6001. EXPECT_EQ("HTTP/1.1", res->version);
  6002. EXPECT_EQ(StatusCode::OK_200, res->status);
  6003. EXPECT_EQ("OK", res->reason);
  6004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6005. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6006. EXPECT_EQ("Hello World!", res->body);
  6007. }
  6008. TEST_F(ServerTest, GetEmptyFile) {
  6009. auto res = cli_.Get("/empty_file");
  6010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6011. EXPECT_EQ(StatusCode::OK_200, res->status);
  6012. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6013. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6014. EXPECT_EQ("", res->body);
  6015. }
  6016. TEST_F(ServerTest, GetFileContent) {
  6017. auto res = cli_.Get("/file_content");
  6018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6021. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6022. EXPECT_EQ("test.html", res->body);
  6023. }
  6024. TEST_F(ServerTest, GetFileContentWithRange) {
  6025. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6028. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6030. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6031. EXPECT_EQ("est", res->body);
  6032. }
  6033. TEST_F(ServerTest, GetFileContentWithContentType) {
  6034. auto res = cli_.Get("/file_content_with_content_type");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. EXPECT_EQ(StatusCode::OK_200, res->status);
  6037. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6038. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6039. EXPECT_EQ("file\n", res->body);
  6040. }
  6041. TEST_F(ServerTest, GetInvalidFileContent) {
  6042. auto res = cli_.Get("/invalid_file_content");
  6043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6044. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6045. }
  6046. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6047. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. EXPECT_EQ("HTTP/1.1", res->version);
  6050. EXPECT_EQ(StatusCode::OK_200, res->status);
  6051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6052. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6053. EXPECT_EQ("Hello World!", res->body);
  6054. }
  6055. TEST_F(ServerTest, GetMethod302) {
  6056. auto res = cli_.Get("/");
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. EXPECT_EQ(StatusCode::Found_302, res->status);
  6059. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6060. }
  6061. TEST_F(ServerTest, GetMethod302Redirect) {
  6062. cli_.set_follow_location(true);
  6063. auto res = cli_.Get("/");
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. EXPECT_EQ(StatusCode::OK_200, res->status);
  6066. EXPECT_EQ("Hello World!", res->body);
  6067. EXPECT_EQ("/hi", res->location);
  6068. }
  6069. TEST_F(ServerTest, GetMethod404) {
  6070. auto res = cli_.Get("/invalid");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6073. }
  6074. TEST_F(ServerTest, HeadMethod200) {
  6075. auto res = cli_.Head("/hi");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::OK_200, res->status);
  6078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6079. EXPECT_TRUE(res->body.empty());
  6080. }
  6081. TEST_F(ServerTest, HeadMethod200Static) {
  6082. auto res = cli_.Head("/mount/dir/index.html");
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::OK_200, res->status);
  6085. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6086. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6087. EXPECT_TRUE(res->body.empty());
  6088. }
  6089. TEST_F(ServerTest, HeadMethod404) {
  6090. auto res = cli_.Head("/invalid");
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6093. EXPECT_TRUE(res->body.empty());
  6094. }
  6095. TEST_F(ServerTest, GetMethodPersonJohn) {
  6096. auto res = cli_.Get("/person/john");
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::OK_200, res->status);
  6099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6100. EXPECT_EQ("programmer", res->body);
  6101. }
  6102. TEST_F(ServerTest, PostMethod1) {
  6103. auto res = cli_.Get("/person/john1");
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6106. res = cli_.Post("/person", "name=john1&note=coder",
  6107. "application/x-www-form-urlencoded");
  6108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6109. ASSERT_EQ(StatusCode::OK_200, res->status);
  6110. res = cli_.Get("/person/john1");
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. ASSERT_EQ(StatusCode::OK_200, res->status);
  6113. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6114. ASSERT_EQ("coder", res->body);
  6115. }
  6116. TEST_F(ServerTest, PostMethod2) {
  6117. auto res = cli_.Get("/person/john2");
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6120. Params params;
  6121. params.emplace("name", "john2");
  6122. params.emplace("note", "coder");
  6123. res = cli_.Post("/person", params);
  6124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6125. ASSERT_EQ(StatusCode::OK_200, res->status);
  6126. res = cli_.Get("/person/john2");
  6127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6128. ASSERT_EQ(StatusCode::OK_200, res->status);
  6129. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6130. ASSERT_EQ("coder", res->body);
  6131. }
  6132. TEST_F(ServerTest, PutMethod3) {
  6133. auto res = cli_.Get("/person/john3");
  6134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6135. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6136. Params params;
  6137. params.emplace("name", "john3");
  6138. params.emplace("note", "coder");
  6139. res = cli_.Put("/person", params);
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. ASSERT_EQ(StatusCode::OK_200, res->status);
  6142. res = cli_.Get("/person/john3");
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. ASSERT_EQ(StatusCode::OK_200, res->status);
  6145. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6146. ASSERT_EQ("coder", res->body);
  6147. }
  6148. TEST_F(ServerTest, DeleteMethod1) {
  6149. auto res = cli_.Get("/person/john4");
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6152. Params params;
  6153. params.emplace("name", "john4");
  6154. params.emplace("note", "coder");
  6155. res = cli_.Post("/person", params);
  6156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6157. ASSERT_EQ(StatusCode::OK_200, res->status);
  6158. res = cli_.Get("/person/john4");
  6159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6160. ASSERT_EQ(StatusCode::OK_200, res->status);
  6161. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6162. ASSERT_EQ("coder", res->body);
  6163. Params delete_params;
  6164. delete_params.emplace("name", "john4");
  6165. res = cli_.Delete("/person", delete_params);
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. ASSERT_EQ(StatusCode::OK_200, res->status);
  6168. ASSERT_EQ("DELETED", res->body);
  6169. res = cli_.Get("/person/john4");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6172. }
  6173. TEST_F(ServerTest, DeleteMethod2) {
  6174. auto res = cli_.Get("/person/john5");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6177. Params params;
  6178. params.emplace("name", "john5");
  6179. params.emplace("note", "developer");
  6180. res = cli_.Post("/person", params);
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. ASSERT_EQ(StatusCode::OK_200, res->status);
  6183. res = cli_.Get("/person/john5");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. ASSERT_EQ(StatusCode::OK_200, res->status);
  6186. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6187. ASSERT_EQ("developer", res->body);
  6188. Params delete_params;
  6189. delete_params.emplace("name", "john5");
  6190. Headers headers;
  6191. headers.emplace("Custom-Header", "test-value");
  6192. res = cli_.Delete("/person", headers, delete_params);
  6193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6194. ASSERT_EQ(StatusCode::OK_200, res->status);
  6195. ASSERT_EQ("DELETED", res->body);
  6196. res = cli_.Get("/person/john5");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6199. }
  6200. TEST_F(ServerTest, DeleteMethod3) {
  6201. auto res = cli_.Get("/person/john6");
  6202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6203. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6204. Params params;
  6205. params.emplace("name", "john6");
  6206. params.emplace("note", "tester");
  6207. res = cli_.Post("/person", params);
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. ASSERT_EQ(StatusCode::OK_200, res->status);
  6210. res = cli_.Get("/person/john6");
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. ASSERT_EQ(StatusCode::OK_200, res->status);
  6213. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6214. ASSERT_EQ("tester", res->body);
  6215. Params delete_params;
  6216. delete_params.emplace("name", "john6");
  6217. Headers headers;
  6218. headers.emplace("Custom-Header", "test-value");
  6219. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. ASSERT_EQ(StatusCode::OK_200, res->status);
  6222. ASSERT_EQ("DELETED", res->body);
  6223. res = cli_.Get("/person/john6");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6226. }
  6227. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6228. Params params;
  6229. params.emplace("json", JSON_DATA);
  6230. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. ASSERT_EQ(JSON_DATA, res->body);
  6234. }
  6235. TEST_F(ServerTest, PostEmptyContent) {
  6236. auto res = cli_.Post("/empty", "", "text/plain");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. ASSERT_EQ(StatusCode::OK_200, res->status);
  6239. ASSERT_EQ("empty", res->body);
  6240. }
  6241. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6242. auto res = cli_.Post("/empty-no-content-type");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. ASSERT_EQ(StatusCode::OK_200, res->status);
  6245. ASSERT_EQ("empty-no-content-type", res->body);
  6246. }
  6247. TEST_F(ServerTest, PostPathOnly) {
  6248. auto res = cli_.Post("/path-only");
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. ASSERT_EQ(StatusCode::OK_200, res->status);
  6251. ASSERT_EQ("path-only", res->body);
  6252. }
  6253. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6254. auto res = cli_.Post("/path-headers-only",
  6255. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. ASSERT_EQ(StatusCode::OK_200, res->status);
  6258. ASSERT_EQ("path-headers-only", res->body);
  6259. }
  6260. TEST_F(ServerTest, PostLarge) {
  6261. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6263. ASSERT_EQ(StatusCode::OK_200, res->status);
  6264. EXPECT_EQ(LARGE_DATA, res->body);
  6265. }
  6266. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6267. auto res = cli_.Put("/empty-no-content-type");
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. ASSERT_EQ(StatusCode::OK_200, res->status);
  6270. ASSERT_EQ("empty-no-content-type", res->body);
  6271. }
  6272. TEST_F(ServerTest, GetMethodDir) {
  6273. auto res = cli_.Get("/dir/");
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::OK_200, res->status);
  6276. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6277. auto body = R"(<html>
  6278. <head>
  6279. </head>
  6280. <body>
  6281. <a href="/dir/test.html">Test</a>
  6282. <a href="/hi">hi</a>
  6283. </body>
  6284. </html>
  6285. )";
  6286. EXPECT_EQ(body, res->body);
  6287. }
  6288. TEST_F(ServerTest, GetMethodDirTest) {
  6289. auto res = cli_.Get("/dir/test.html");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::OK_200, res->status);
  6292. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6293. EXPECT_EQ("test.html", res->body);
  6294. }
  6295. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6296. auto res = cli_.Get("/dir/../dir/test.html");
  6297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6298. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6299. }
  6300. TEST_F(ServerTest, GetMethodInvalidPath) {
  6301. auto res = cli_.Get("/dir/../test.html");
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6304. }
  6305. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6306. auto res = cli_.Get("/../www/dir/test.html");
  6307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6309. }
  6310. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6311. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6314. }
  6315. TEST_F(ServerTest, GetMethodDirMountTest) {
  6316. auto res = cli_.Get("/mount/dir/test.html");
  6317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6320. EXPECT_EQ("test.html", res->body);
  6321. }
  6322. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6323. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6326. }
  6327. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6328. auto res = cli_.Get("/mount/dir/../test.html");
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6331. }
  6332. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6333. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6336. }
  6337. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6338. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6341. }
  6342. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6343. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6346. }
  6347. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6348. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6351. }
  6352. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6353. auto res = cli_.Get("/mount/dir");
  6354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6355. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6356. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6357. }
  6358. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6359. auto res = cli_.Get("//dir");
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6362. EXPECT_FALSE(res->has_header("Location"));
  6363. }
  6364. TEST_F(ServerTest, PostMethod303) {
  6365. auto res = cli_.Post("/1", "body", "text/plain");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6368. EXPECT_EQ("/2", res->get_header_value("Location"));
  6369. }
  6370. TEST_F(ServerTest, PostMethod303Redirect) {
  6371. cli_.set_follow_location(true);
  6372. auto res = cli_.Post("/1", "body", "text/plain");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::OK_200, res->status);
  6375. EXPECT_EQ("redirected.", res->body);
  6376. EXPECT_EQ("/2", res->location);
  6377. }
  6378. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6379. auto res = cli_.Get("/dir/test.abcde");
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. EXPECT_EQ(StatusCode::OK_200, res->status);
  6382. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6383. EXPECT_EQ("abcde", res->body);
  6384. }
  6385. TEST_F(ServerTest, StaticFileRange) {
  6386. auto res =
  6387. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6390. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6391. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6392. EXPECT_EQ(true, res->has_header("Content-Range"));
  6393. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6394. EXPECT_EQ(std::string("cd"), res->body);
  6395. }
  6396. TEST_F(ServerTest, StaticFileRanges) {
  6397. auto res = cli_.Get("/dir/test.abcde",
  6398. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6401. EXPECT_TRUE(
  6402. res->get_header_value("Content-Type")
  6403. .find(
  6404. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6405. 0);
  6406. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6407. }
  6408. TEST_F(ServerTest, StaticFileRangeHead) {
  6409. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6412. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6413. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6414. EXPECT_EQ(true, res->has_header("Content-Range"));
  6415. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6416. }
  6417. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6418. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6420. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6422. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6423. EXPECT_EQ(true, res->has_header("Content-Range"));
  6424. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6425. res->get_header_value("Content-Range"));
  6426. EXPECT_EQ("LAST\n", res->body);
  6427. }
  6428. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6429. auto res =
  6430. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6434. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6435. EXPECT_EQ(true, res->has_header("Content-Range"));
  6436. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6437. }
  6438. TEST_F(ServerTest, StaticFileBigFile) {
  6439. auto res = cli_.Get("/dir/1MB.txt");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6443. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6444. }
  6445. TEST_F(ServerTest, InvalidBaseDirMount) {
  6446. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6447. }
  6448. TEST_F(ServerTest, Binary) {
  6449. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6450. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6451. "application/octet-stream");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. ASSERT_EQ(StatusCode::OK_200, res->status);
  6454. ASSERT_EQ(4U, res->body.size());
  6455. res = cli_.Put("/binary", binary.data(), binary.size(),
  6456. "application/octet-stream");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. ASSERT_EQ(StatusCode::OK_200, res->status);
  6459. ASSERT_EQ(4U, res->body.size());
  6460. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6461. "application/octet-stream");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. ASSERT_EQ(StatusCode::OK_200, res->status);
  6464. ASSERT_EQ(4U, res->body.size());
  6465. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6466. "application/octet-stream");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. ASSERT_EQ(StatusCode::OK_200, res->status);
  6469. ASSERT_EQ(4U, res->body.size());
  6470. }
  6471. TEST_F(ServerTest, BinaryString) {
  6472. auto binary = std::string("\x00\x01\x02\x03", 4);
  6473. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. ASSERT_EQ(StatusCode::OK_200, res->status);
  6476. ASSERT_EQ(4U, res->body.size());
  6477. res = cli_.Put("/binary", binary, "application/octet-stream");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. ASSERT_EQ(StatusCode::OK_200, res->status);
  6480. ASSERT_EQ(4U, res->body.size());
  6481. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6483. ASSERT_EQ(StatusCode::OK_200, res->status);
  6484. ASSERT_EQ(4U, res->body.size());
  6485. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. ASSERT_EQ(StatusCode::OK_200, res->status);
  6488. ASSERT_EQ(4U, res->body.size());
  6489. }
  6490. TEST_F(ServerTest, EmptyRequest) {
  6491. auto res = cli_.Get("");
  6492. ASSERT_TRUE(!res);
  6493. EXPECT_EQ(Error::Connection, res.error());
  6494. }
  6495. TEST_F(ServerTest, LongRequest) {
  6496. std::string request;
  6497. for (size_t i = 0; i < 545; i++) {
  6498. request += "/TooLongRequest";
  6499. }
  6500. request += "OK";
  6501. auto res = cli_.Get(request.c_str());
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6504. }
  6505. TEST_F(ServerTest, TooLongRequest) {
  6506. std::string request;
  6507. for (size_t i = 0; i < 546; i++) {
  6508. request += "/TooLongRequest";
  6509. }
  6510. request += "_NG";
  6511. auto start = std::chrono::high_resolution_clock::now();
  6512. cli_.set_keep_alive(true);
  6513. auto res = cli_.Get(request.c_str());
  6514. auto end = std::chrono::high_resolution_clock::now();
  6515. auto elapsed =
  6516. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6517. .count();
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6520. EXPECT_LE(elapsed, 1000);
  6521. EXPECT_EQ("close", res->get_header_value("Connection"));
  6522. EXPECT_FALSE(cli_.is_socket_open());
  6523. }
  6524. TEST_F(ServerTest, AlmostTooLongRequest) {
  6525. // test for #2046 - URI length check shouldn't include other content on req
  6526. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6527. // leading /, space, HTTP/1.1)
  6528. std::string request =
  6529. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6530. auto res = cli_.Get(request.c_str());
  6531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6532. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6533. }
  6534. TEST_F(ServerTest, LongHeader) {
  6535. Request req;
  6536. req.method = "GET";
  6537. req.path = "/hi";
  6538. std::string host_and_port;
  6539. host_and_port += HOST;
  6540. host_and_port += ":";
  6541. host_and_port += std::to_string(PORT);
  6542. req.headers.emplace("Host", host_and_port.c_str());
  6543. req.headers.emplace("Accept", "*/*");
  6544. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6545. req.headers.emplace(
  6546. "Header-Name",
  6547. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6548. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6549. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@");
  6576. auto res = std::make_shared<Response>();
  6577. auto error = Error::Success;
  6578. auto ret = cli_.send(req, *res, error);
  6579. ASSERT_TRUE(ret);
  6580. EXPECT_EQ(StatusCode::OK_200, res->status);
  6581. }
  6582. TEST_F(ServerTest, LongQueryValue) {
  6583. auto start = std::chrono::high_resolution_clock::now();
  6584. cli_.set_keep_alive(true);
  6585. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6586. auto end = std::chrono::high_resolution_clock::now();
  6587. auto elapsed =
  6588. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6589. .count();
  6590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6591. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6592. EXPECT_LE(elapsed, 1000);
  6593. EXPECT_EQ("close", res->get_header_value("Connection"));
  6594. EXPECT_FALSE(cli_.is_socket_open());
  6595. }
  6596. TEST_F(ServerTest, TooLongQueryValue) {
  6597. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6598. ASSERT_FALSE(res);
  6599. EXPECT_EQ(Error::Read, res.error());
  6600. }
  6601. TEST_F(ServerTest, TooLongHeader) {
  6602. Request req;
  6603. req.method = "GET";
  6604. req.path = "/hi";
  6605. std::string host_and_port;
  6606. host_and_port += HOST;
  6607. host_and_port += ":";
  6608. host_and_port += std::to_string(PORT);
  6609. req.headers.emplace("Host", host_and_port.c_str());
  6610. req.headers.emplace("Accept", "*/*");
  6611. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6612. req.headers.emplace(
  6613. "Header-Name",
  6614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@");
  6643. auto res = std::make_shared<Response>();
  6644. auto error = Error::Success;
  6645. auto ret = cli_.send(req, *res, error);
  6646. ASSERT_TRUE(ret);
  6647. EXPECT_EQ(StatusCode::OK_200, res->status);
  6648. }
  6649. TEST_F(ServerTest, HeaderCountAtLimit) {
  6650. // Test with headers just under the 100 limit
  6651. httplib::Headers headers;
  6652. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6653. // This should keep us just under the 100 header limit
  6654. for (int i = 0; i < 95; i++) {
  6655. std::string name = "X-Test-Header-" + std::to_string(i);
  6656. std::string value = "value" + std::to_string(i);
  6657. headers.emplace(name, value);
  6658. }
  6659. // This should work fine as we're under the limit
  6660. auto res = cli_.Get("/hi", headers);
  6661. EXPECT_TRUE(res);
  6662. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6663. }
  6664. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6665. // Test with many headers to exceed the 100 limit
  6666. httplib::Headers headers;
  6667. // Add 150 headers to definitely exceed the 100 limit
  6668. for (int i = 0; i < 150; i++) {
  6669. std::string name = "X-Test-Header-" + std::to_string(i);
  6670. std::string value = "value" + std::to_string(i);
  6671. headers.emplace(name, value);
  6672. }
  6673. // This should fail due to exceeding header count limit
  6674. cli_.set_keep_alive(true);
  6675. auto res = cli_.Get("/hi", headers);
  6676. // The server should respond with 400 Bad Request
  6677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6678. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6679. EXPECT_EQ("close", res->get_header_value("Connection"));
  6680. EXPECT_FALSE(cli_.is_socket_open());
  6681. }
  6682. TEST_F(ServerTest, PercentEncoding) {
  6683. auto res = cli_.Get("/e%6edwith%");
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. }
  6687. TEST_F(ServerTest, PercentEncodingUnicode) {
  6688. auto res = cli_.Get("/e%u006edwith%");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. EXPECT_EQ(StatusCode::OK_200, res->status);
  6691. }
  6692. TEST_F(ServerTest, InvalidPercentEncoding) {
  6693. auto res = cli_.Get("/%endwith%");
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6696. }
  6697. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6698. auto res = cli_.Get("/%uendwith%");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6701. }
  6702. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6703. auto res = cli_.Get("/hello?aaa=bbb%");
  6704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6705. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6706. }
  6707. TEST_F(ServerTest, PlusSignEncoding) {
  6708. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. EXPECT_EQ("a +b", res->body);
  6712. }
  6713. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6714. // This test simulates a potential DoS attack using many headers
  6715. // to verify our security fix prevents memory exhaustion
  6716. httplib::Headers attack_headers;
  6717. // Attempt to add many headers like an attacker would (200 headers to far
  6718. // exceed limit)
  6719. for (int i = 0; i < 200; i++) {
  6720. std::string name = "X-Attack-Header-" + std::to_string(i);
  6721. std::string value = "attack_payload_" + std::to_string(i);
  6722. attack_headers.emplace(name, value);
  6723. }
  6724. // Try to POST with excessive headers
  6725. cli_.set_keep_alive(true);
  6726. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6727. // Should either fail or return 400 Bad Request due to security limit
  6728. if (res) {
  6729. // If we get a response, it should be 400 Bad Request
  6730. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6731. EXPECT_EQ("close", res->get_header_value("Connection"));
  6732. }
  6733. EXPECT_FALSE(cli_.is_socket_open());
  6734. }
  6735. TEST_F(ServerTest, MultipartFormData) {
  6736. UploadFormDataItems items = {
  6737. {"text1", "text default", "", ""},
  6738. {"text2", "aωb", "", ""},
  6739. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6740. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6741. {"file3", "", "", "application/octet-stream"},
  6742. {"file4", "", "", " application/json tmp-string "}};
  6743. auto res = cli_.Post("/multipart", items);
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. }
  6747. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6748. UploadFormDataItems items = {
  6749. {"text", "default text", "", ""},
  6750. {"multi_text1", "aaaaa", "", ""},
  6751. {"multi_text1", "bbbbb", "", ""},
  6752. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6753. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6754. "application/json"},
  6755. };
  6756. auto res = cli_.Post("/multipart/multi_file_values", items);
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::OK_200, res->status);
  6759. }
  6760. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6761. auto res = cli_.Get("/hi");
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. EXPECT_EQ(StatusCode::OK_200, res->status);
  6764. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6765. EXPECT_EQ("Hello World!", res->body);
  6766. }
  6767. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6768. Request req;
  6769. req.method = "POST";
  6770. req.path = "/chunked";
  6771. std::string host_and_port;
  6772. host_and_port += HOST;
  6773. host_and_port += ":";
  6774. host_and_port += std::to_string(PORT);
  6775. req.headers.emplace("Host", host_and_port.c_str());
  6776. req.headers.emplace("Accept", "*/*");
  6777. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6778. req.headers.emplace("Content-Type", "text/plain");
  6779. req.headers.emplace("Content-Length", "0");
  6780. req.headers.emplace(
  6781. "Transfer-Encoding",
  6782. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6783. // Client does not chunk, so make a chunked body manually.
  6784. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6785. auto res = std::make_shared<Response>();
  6786. auto error = Error::Success;
  6787. auto ret = cli_.send(req, *res, error);
  6788. ASSERT_TRUE(ret);
  6789. EXPECT_EQ(StatusCode::OK_200, res->status);
  6790. }
  6791. template <typename ClientT>
  6792. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6793. int expected_status) {
  6794. Request req;
  6795. req.method = "POST";
  6796. req.path = "/chunked";
  6797. std::string host_and_port;
  6798. host_and_port += HOST;
  6799. host_and_port += ":";
  6800. host_and_port += std::to_string(PORT);
  6801. req.headers.emplace("Host", host_and_port.c_str());
  6802. req.headers.emplace("Content-Length", "0");
  6803. req.headers.emplace("Transfer-Encoding", "chunked");
  6804. req.body = body;
  6805. auto res = std::make_shared<Response>();
  6806. auto error = Error::Success;
  6807. ASSERT_TRUE(cli.send(req, *res, error));
  6808. EXPECT_EQ(expected_status, res->status);
  6809. }
  6810. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6811. // rather than treat them as valid lengths.
  6812. template <typename ClientT>
  6813. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6814. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6815. }
  6816. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6817. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6818. }
  6819. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6820. expect_chunked_body_rejected(
  6821. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6822. }
  6823. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6824. // chunk-size line carries no CR, LF or other control character ahead of its
  6825. // terminator. Such a line must be refused rather than read as extension text.
  6826. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6827. expect_chunked_body_rejected(
  6828. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6829. }
  6830. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6831. expect_chunked_body_rejected(
  6832. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6833. }
  6834. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6835. expect_chunked_body_rejected(
  6836. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6837. }
  6838. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6839. // The literal stays split: a hex escape consumes every hex digit that
  6840. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6841. expect_chunked_body_rejected(
  6842. cli_, "4;a\x01"
  6843. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6844. }
  6845. // The bytes around chunk data are no payload, so they cannot ride on the
  6846. // payload limit
  6847. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6848. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 2, 'x');
  6849. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 2, '0');
  6850. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 2, ' ');
  6851. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6852. SCOPED_TRACE(size_line.substr(0, 2));
  6853. std::string body;
  6854. for (auto c : std::string("dechunked post body")) {
  6855. body += size_line + "\r\n" + c + "\r\n";
  6856. }
  6857. body += "0\r\n\r\n";
  6858. expect_chunked_body_rejected(cli_, body.c_str());
  6859. }
  6860. }
  6861. TEST_F(ServerTest, AcceptsChunkExtension) {
  6862. expect_chunked_body_status(cli_,
  6863. "4;name=value\r\ndech\r\n"
  6864. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6865. "0;last\r\n\r\n",
  6866. StatusCode::OK_200);
  6867. }
  6868. TEST_F(ServerTest, GetStreamed2) {
  6869. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6872. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6873. EXPECT_EQ(true, res->has_header("Content-Range"));
  6874. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6875. EXPECT_EQ(std::string("ab"), res->body);
  6876. }
  6877. TEST_F(ServerTest, GetStreamed) {
  6878. auto res = cli_.Get("/streamed");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. EXPECT_EQ(StatusCode::OK_200, res->status);
  6881. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6882. EXPECT_EQ(std::string("aaabbb"), res->body);
  6883. }
  6884. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6885. auto res = cli_.Get("/streamed-without-length",
  6886. Headers{make_range_header({{0, -1}})});
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. EXPECT_EQ(false, res->has_header("Content-Length"));
  6890. EXPECT_EQ(false, res->has_header("Content-Range"));
  6891. EXPECT_EQ(std::string("abcdefg"), res->body);
  6892. }
  6893. TEST_F(ServerTest, GetStreamedWithRange1) {
  6894. auto res =
  6895. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6898. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6899. EXPECT_EQ(true, res->has_header("Content-Range"));
  6900. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6901. EXPECT_EQ(std::string("def"), res->body);
  6902. }
  6903. TEST_F(ServerTest, GetStreamedWithRange2) {
  6904. auto res =
  6905. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6908. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6909. EXPECT_EQ(true, res->has_header("Content-Range"));
  6910. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6911. EXPECT_EQ(std::string("bcdefg"), res->body);
  6912. }
  6913. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6914. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6917. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6918. EXPECT_EQ(true, res->has_header("Content-Range"));
  6919. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6920. EXPECT_EQ(std::string("efg"), res->body);
  6921. }
  6922. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6923. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6924. // the entire representation.
  6925. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6926. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6929. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6930. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6931. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6932. }
  6933. }
  6934. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6935. auto res =
  6936. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6939. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6940. EXPECT_EQ(false, res->has_header("Content-Range"));
  6941. EXPECT_EQ(0U, res->body.size());
  6942. }
  6943. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6944. // Only a 206 is served as a partial representation. Under any other status
  6945. // `apply_ranges()` reported the full content length, so the body must match
  6946. // that header, and the content provider must never be asked for an offset
  6947. // outside the representation.
  6948. auto check = [&](int status, const char *range) {
  6949. auto path =
  6950. std::string("/streamed-with-range?status=") + std::to_string(status);
  6951. auto ctx = path + " Range: " + range;
  6952. auto res = cli_.Get(path, Headers{{"Range", range}});
  6953. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6954. EXPECT_EQ(status, res->status) << ctx;
  6955. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6956. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6957. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6958. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6959. };
  6960. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6961. check(403, "bytes=3-5");
  6962. // The offset is far past the representation.
  6963. check(403, "bytes=100000-100200");
  6964. // `first_pos` is still -1 here, and the bounds asserts in
  6965. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6966. check(403, "bytes=-3");
  6967. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6968. // multipart branch would have written one that is empty.
  6969. check(403, "bytes=1-2, 4-5");
  6970. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6971. // covers the whole representation.
  6972. check(200, "bytes=3-5");
  6973. check(200, "bytes=1-2, 4-5");
  6974. }
  6975. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6976. auto res =
  6977. cli_.Get("/streamed-with-range",
  6978. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6979. "92233720368547758079223372036854775807"}});
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6982. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6983. EXPECT_EQ(false, res->has_header("Content-Range"));
  6984. EXPECT_EQ(0U, res->body.size());
  6985. }
  6986. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6987. auto res = cli_.Get(
  6988. "/with-range",
  6989. Headers{{"Range",
  6990. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6991. {"Accept-Encoding", ""}});
  6992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6993. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6994. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6995. EXPECT_EQ(true, res->has_header("Content-Range"));
  6996. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6997. EXPECT_EQ(std::string("abcdefg"), res->body);
  6998. }
  6999. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7000. auto res = cli_.Get("/with-range", Headers{
  7001. {"Range", "bytes=0-"},
  7002. {"Accept-Encoding", ""},
  7003. });
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7006. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7007. EXPECT_EQ(true, res->has_header("Content-Range"));
  7008. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7009. EXPECT_EQ(std::string("abcdefg"), res->body);
  7010. }
  7011. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7012. auto res = cli_.Get("/streamed-with-range",
  7013. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7015. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7016. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7017. EXPECT_EQ(false, res->has_header("Content-Range"));
  7018. EXPECT_EQ(267U, res->body.size());
  7019. // Check that both range contents are present
  7020. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7021. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7022. // Check that Content-Range headers are present for both ranges
  7023. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7024. std::string::npos);
  7025. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7026. std::string::npos);
  7027. }
  7028. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7029. Ranges ranges;
  7030. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7031. ranges.emplace_back(0, -1);
  7032. }
  7033. auto res = cli_.Get("/streamed-with-range?error",
  7034. Headers{{make_range_header(ranges)}});
  7035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7036. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7037. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7038. EXPECT_EQ(false, res->has_header("Content-Range"));
  7039. EXPECT_EQ(0U, res->body.size());
  7040. }
  7041. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7042. auto res = cli_.Get("/streamed-with-range",
  7043. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7046. EXPECT_EQ(5U, res->body.size());
  7047. // Check that overlapping ranges are coalesced into a single range
  7048. EXPECT_EQ("bcdef", res->body);
  7049. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7050. // Should be single range, not multipart
  7051. EXPECT_TRUE(res->has_header("Content-Range"));
  7052. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7053. }
  7054. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7055. auto res = cli_.Get("/streamed-with-range",
  7056. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7059. EXPECT_EQ(268U, res->body.size());
  7060. // Check that both range contents are present
  7061. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7062. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7063. // Check that Content-Range headers are present for both ranges
  7064. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7065. std::string::npos);
  7066. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7067. std::string::npos);
  7068. }
  7069. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7070. auto res = cli_.Get("/streamed-with-range",
  7071. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7073. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7074. EXPECT_EQ(269U, res->body.size());
  7075. // Check that both duplicate range contents are present
  7076. size_t first_abc = res->body.find("abc\r\n");
  7077. EXPECT_TRUE(first_abc != std::string::npos);
  7078. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7079. EXPECT_TRUE(second_abc != std::string::npos);
  7080. // Check that Content-Range headers are present for both ranges
  7081. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7082. EXPECT_TRUE(first_range != std::string::npos);
  7083. size_t second_range =
  7084. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7085. EXPECT_TRUE(second_range != std::string::npos);
  7086. }
  7087. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7088. auto res =
  7089. cli_.Get("/streamed-with-range?error",
  7090. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7092. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7093. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7094. EXPECT_EQ(false, res->has_header("Content-Range"));
  7095. EXPECT_EQ(0U, res->body.size());
  7096. }
  7097. TEST_F(ServerTest, GetStreamedEndless) {
  7098. uint64_t offset = 0;
  7099. auto res = cli_.Get("/streamed-cancel",
  7100. [&](const char * /*data*/, uint64_t data_length) {
  7101. if (offset < 100) {
  7102. offset += data_length;
  7103. return true;
  7104. }
  7105. return false;
  7106. });
  7107. ASSERT_TRUE(!res);
  7108. EXPECT_EQ(Error::Canceled, res.error());
  7109. }
  7110. TEST_F(ServerTest, ClientStop) {
  7111. std::atomic_size_t count{4};
  7112. std::vector<std::thread> threads;
  7113. for (auto i = count.load(); i != 0; --i) {
  7114. threads.emplace_back([&]() {
  7115. auto res = cli_.Get("/streamed-cancel",
  7116. [&](const char *, uint64_t) { return true; });
  7117. --count;
  7118. ASSERT_TRUE(!res);
  7119. EXPECT_TRUE(res.error() == Error::Canceled ||
  7120. res.error() == Error::Read || res.error() == Error::Write);
  7121. });
  7122. }
  7123. std::this_thread::sleep_for(std::chrono::seconds(2));
  7124. while (count != 0) {
  7125. cli_.stop();
  7126. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7127. }
  7128. for (auto &t : threads) {
  7129. t.join();
  7130. }
  7131. }
  7132. TEST_F(ServerTest, GetWithRange1) {
  7133. auto res = cli_.Get("/with-range", Headers{
  7134. make_range_header({{3, 5}}),
  7135. {"Accept-Encoding", ""},
  7136. });
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7139. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7140. EXPECT_EQ(true, res->has_header("Content-Range"));
  7141. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7142. EXPECT_EQ(std::string("def"), res->body);
  7143. }
  7144. TEST_F(ServerTest, GetWithRange2) {
  7145. auto res = cli_.Get("/with-range", Headers{
  7146. make_range_header({{1, -1}}),
  7147. {"Accept-Encoding", ""},
  7148. });
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7151. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7152. EXPECT_EQ(true, res->has_header("Content-Range"));
  7153. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7154. EXPECT_EQ(std::string("bcdefg"), res->body);
  7155. }
  7156. TEST_F(ServerTest, GetWithRange3) {
  7157. auto res = cli_.Get("/with-range", Headers{
  7158. make_range_header({{0, 0}}),
  7159. {"Accept-Encoding", ""},
  7160. });
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7163. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7164. EXPECT_EQ(true, res->has_header("Content-Range"));
  7165. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7166. EXPECT_EQ(std::string("a"), res->body);
  7167. }
  7168. TEST_F(ServerTest, GetWithRange4) {
  7169. auto res = cli_.Get("/with-range", Headers{
  7170. make_range_header({{-1, 2}}),
  7171. {"Accept-Encoding", ""},
  7172. });
  7173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7175. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7176. EXPECT_EQ(true, res->has_header("Content-Range"));
  7177. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7178. EXPECT_EQ(std::string("fg"), res->body);
  7179. }
  7180. TEST_F(ServerTest, GetWithRange5) {
  7181. auto res = cli_.Get("/with-range", Headers{
  7182. make_range_header({{0, 5}}),
  7183. {"Accept-Encoding", ""},
  7184. });
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7187. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(true, res->has_header("Content-Range"));
  7189. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7190. EXPECT_EQ(std::string("abcdef"), res->body);
  7191. }
  7192. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7193. auto res =
  7194. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7197. }
  7198. TEST_F(ServerTest, GetWithRangeMultipart) {
  7199. auto res =
  7200. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7203. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7204. EXPECT_EQ(false, res->has_header("Content-Range"));
  7205. EXPECT_EQ(267U, res->body.size());
  7206. }
  7207. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7208. auto res = cli_.Get("/with-range",
  7209. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7211. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7212. }
  7213. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7214. auto res = cli_.Get("/with-range-customized-response",
  7215. Headers{{make_range_header({{1, 2}})}});
  7216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7217. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7218. EXPECT_EQ(true, res->has_header("Content-Length"));
  7219. EXPECT_EQ(false, res->has_header("Content-Range"));
  7220. EXPECT_EQ(JSON_DATA, res->body);
  7221. }
  7222. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7223. auto res = cli_.Get("/with-range-customized-response",
  7224. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7227. EXPECT_EQ(true, res->has_header("Content-Length"));
  7228. EXPECT_EQ(false, res->has_header("Content-Range"));
  7229. EXPECT_EQ(JSON_DATA, res->body);
  7230. }
  7231. TEST_F(ServerTest, Issue1772) {
  7232. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7234. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7235. }
  7236. TEST_F(ServerTest, Issue609) {
  7237. auto res = cli_.Delete("/issue609");
  7238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7239. EXPECT_EQ(StatusCode::OK_200, res->status);
  7240. EXPECT_EQ(std::string("ok"), res->body);
  7241. }
  7242. TEST_F(ServerTest, GetStreamedChunked) {
  7243. auto res = cli_.Get("/streamed-chunked");
  7244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7245. EXPECT_EQ(StatusCode::OK_200, res->status);
  7246. EXPECT_EQ(std::string("123456789"), res->body);
  7247. }
  7248. TEST_F(ServerTest, GetStreamedChunked2) {
  7249. auto res = cli_.Get("/streamed-chunked2");
  7250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7251. EXPECT_EQ(StatusCode::OK_200, res->status);
  7252. EXPECT_EQ(std::string("123456789"), res->body);
  7253. }
  7254. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7255. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7257. EXPECT_EQ(StatusCode::OK_200, res->status);
  7258. EXPECT_EQ(std::string("123456789"), res->body);
  7259. EXPECT_TRUE(res->has_header("Trailer"));
  7260. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7261. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7262. // Trailers are now stored separately from headers (security fix)
  7263. EXPECT_EQ(2U, res->trailers.size());
  7264. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7265. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7266. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7267. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7268. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7269. // Verify trailers are NOT in headers (security verification)
  7270. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7271. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7272. }
  7273. TEST_F(ServerTest, LargeChunkedPost) {
  7274. Request req;
  7275. req.method = "POST";
  7276. req.path = "/large-chunked";
  7277. std::string host_and_port;
  7278. host_and_port += HOST;
  7279. host_and_port += ":";
  7280. host_and_port += std::to_string(PORT);
  7281. req.headers.emplace("Host", host_and_port.c_str());
  7282. req.headers.emplace("Accept", "*/*");
  7283. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7284. req.headers.emplace("Content-Type", "text/plain");
  7285. req.headers.emplace("Content-Length", "0");
  7286. req.headers.emplace("Transfer-Encoding", "chunked");
  7287. std::string long_string(30 * 1024u, 'a');
  7288. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7289. // Attempt to make a large enough post to exceed OS buffers, to test that
  7290. // the server handles short reads if the full chunk data isn't available.
  7291. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7292. auto res = std::make_shared<Response>();
  7293. auto error = Error::Success;
  7294. auto ret = cli_.send(req, *res, error);
  7295. ASSERT_TRUE(ret);
  7296. EXPECT_EQ(StatusCode::OK_200, res->status);
  7297. }
  7298. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7299. auto res = cli_.Get("/remote_addr");
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::OK_200, res->status);
  7302. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7303. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7304. }
  7305. TEST_F(ServerTest, GetMethodLocalAddr) {
  7306. auto res = cli_.Get("/local_addr");
  7307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7308. EXPECT_EQ(StatusCode::OK_200, res->status);
  7309. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7310. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7311. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7312. }
  7313. TEST_F(ServerTest, HTTPResponseSplitting) {
  7314. auto res = cli_.Get("/http_response_splitting");
  7315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7316. EXPECT_EQ(StatusCode::OK_200, res->status);
  7317. }
  7318. TEST_F(ServerTest, SlowRequest) {
  7319. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7320. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7321. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7322. }
  7323. #if 0
  7324. TEST_F(ServerTest, SlowPost) {
  7325. char buffer[64 * 1024];
  7326. memset(buffer, 0x42, sizeof(buffer));
  7327. auto res = cli_.Post(
  7328. "/slowpost", 64 * 1024 * 1024,
  7329. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7330. auto ret = sink.write(buffer, sizeof(buffer));
  7331. EXPECT_TRUE(ret);
  7332. return true;
  7333. },
  7334. "text/plain");
  7335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7336. EXPECT_EQ(StatusCode::OK_200, res->status);
  7337. }
  7338. TEST_F(ServerTest, SlowPostFail) {
  7339. char buffer[64 * 1024];
  7340. memset(buffer, 0x42, sizeof(buffer));
  7341. cli_.set_write_timeout(std::chrono::seconds(0));
  7342. auto res = cli_.Post(
  7343. "/slowpost", 64 * 1024 * 1024,
  7344. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7345. sink.write(buffer, sizeof(buffer));
  7346. return true;
  7347. },
  7348. "text/plain");
  7349. ASSERT_TRUE(!res);
  7350. EXPECT_EQ(Error::Write, res.error());
  7351. }
  7352. #endif
  7353. TEST_F(ServerTest, Put) {
  7354. auto res = cli_.Put("/put", "PUT", "text/plain");
  7355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7356. EXPECT_EQ(StatusCode::OK_200, res->status);
  7357. EXPECT_EQ("PUT", res->body);
  7358. }
  7359. TEST_F(ServerTest, PutWithContentProvider) {
  7360. auto res = cli_.Put(
  7361. "/put", 3,
  7362. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7363. sink.os << "PUT";
  7364. return true;
  7365. },
  7366. "text/plain");
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::OK_200, res->status);
  7369. EXPECT_EQ("PUT", res->body);
  7370. }
  7371. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7372. auto res = cli_.Post(
  7373. "/post", 42,
  7374. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7375. return false;
  7376. },
  7377. "text/plain");
  7378. ASSERT_TRUE(!res);
  7379. EXPECT_EQ(Error::Canceled, res.error());
  7380. }
  7381. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7382. auto res = cli_.Put(
  7383. "/put",
  7384. [](size_t /*offset*/, DataSink &sink) {
  7385. sink.os << "PUT";
  7386. sink.done();
  7387. return true;
  7388. },
  7389. "text/plain");
  7390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7391. EXPECT_EQ(StatusCode::OK_200, res->status);
  7392. EXPECT_EQ("PUT", res->body);
  7393. }
  7394. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7395. auto res = cli_.Post(
  7396. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7397. "text/plain");
  7398. ASSERT_TRUE(!res);
  7399. EXPECT_EQ(Error::Canceled, res.error());
  7400. }
  7401. TEST_F(ServerTest, PostLoopBack) {
  7402. std::string body;
  7403. auto res = cli_.Post(
  7404. "/post-loopback", 9,
  7405. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7406. EXPECT_EQ(9u, length);
  7407. sink.write("123", 3);
  7408. sink.write("456", 3);
  7409. sink.write("789", 3);
  7410. return true;
  7411. },
  7412. "text/plain",
  7413. [&body](const char *data, size_t data_length) {
  7414. body.append(data, data_length);
  7415. return true;
  7416. });
  7417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7418. EXPECT_EQ(StatusCode::OK_200, res->status);
  7419. EXPECT_EQ("123456789", body);
  7420. }
  7421. TEST_F(ServerTest, PutLoopBack) {
  7422. std::string body;
  7423. auto res = cli_.Put(
  7424. "/put-loopback", 9,
  7425. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7426. EXPECT_EQ(9u, length);
  7427. sink.write("123", 3);
  7428. sink.write("456", 3);
  7429. sink.write("789", 3);
  7430. return true;
  7431. },
  7432. "text/plain",
  7433. [&body](const char *data, size_t data_length) {
  7434. body.append(data, data_length);
  7435. return true;
  7436. });
  7437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7438. EXPECT_EQ(StatusCode::OK_200, res->status);
  7439. EXPECT_EQ("123456789", body);
  7440. }
  7441. TEST_F(ServerTest, PatchLoopBack) {
  7442. std::string body;
  7443. auto res = cli_.Patch(
  7444. "/patch-loopback", 9,
  7445. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7446. EXPECT_EQ(9u, length);
  7447. sink.write("123", 3);
  7448. sink.write("456", 3);
  7449. sink.write("789", 3);
  7450. return true;
  7451. },
  7452. "text/plain",
  7453. [&body](const char *data, size_t data_length) {
  7454. body.append(data, data_length);
  7455. return true;
  7456. });
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. EXPECT_EQ("123456789", body);
  7460. }
  7461. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7462. std::string body;
  7463. auto res = cli_.Post(
  7464. "/post-loopback",
  7465. [](size_t /*offset*/, DataSink &sink) {
  7466. sink.write("123", 3);
  7467. sink.write("456", 3);
  7468. sink.write("789", 3);
  7469. sink.done();
  7470. return true;
  7471. },
  7472. "text/plain",
  7473. [&body](const char *data, size_t data_length) {
  7474. body.append(data, data_length);
  7475. return true;
  7476. });
  7477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7478. EXPECT_EQ(StatusCode::OK_200, res->status);
  7479. EXPECT_EQ("123456789", body);
  7480. }
  7481. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7482. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7483. cli_.set_compress(true);
  7484. auto res = cli_.Put(
  7485. "/put", 3,
  7486. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7487. sink.os << "PUT";
  7488. return true;
  7489. },
  7490. "text/plain");
  7491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7492. EXPECT_EQ(StatusCode::OK_200, res->status);
  7493. EXPECT_EQ("PUT", res->body);
  7494. }
  7495. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7496. cli_.set_compress(true);
  7497. auto res = cli_.Post(
  7498. "/post", 42,
  7499. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7500. return false;
  7501. },
  7502. "text/plain");
  7503. ASSERT_TRUE(!res);
  7504. EXPECT_EQ(Error::Canceled, res.error());
  7505. }
  7506. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7507. cli_.set_compress(true);
  7508. auto res = cli_.Put(
  7509. "/put",
  7510. [](size_t /*offset*/, DataSink &sink) {
  7511. sink.os << "PUT";
  7512. sink.done();
  7513. return true;
  7514. },
  7515. "text/plain");
  7516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7517. EXPECT_EQ(StatusCode::OK_200, res->status);
  7518. EXPECT_EQ("PUT", res->body);
  7519. }
  7520. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7521. cli_.set_compress(true);
  7522. auto res = cli_.Post(
  7523. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7524. "text/plain");
  7525. ASSERT_TRUE(!res);
  7526. EXPECT_EQ(Error::Canceled, res.error());
  7527. }
  7528. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7529. cli_.set_compress(true);
  7530. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7532. EXPECT_EQ(StatusCode::OK_200, res->status);
  7533. EXPECT_EQ(LARGE_DATA, res->body);
  7534. }
  7535. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7536. #ifdef CPPHTTPLIB_SSL_ENABLED
  7537. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7538. Client cli(s.c_str());
  7539. cli.enable_server_certificate_verification(false);
  7540. #else
  7541. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7542. Client cli(s.c_str());
  7543. #endif
  7544. cli.set_compress(true);
  7545. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7547. EXPECT_EQ(StatusCode::OK_200, res->status);
  7548. EXPECT_EQ(LARGE_DATA, res->body);
  7549. // The compressed size should be less than a 10th of the original. May vary
  7550. // depending on the zlib library.
  7551. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7552. static_cast<uint64_t>(10 * 1024 * 1024));
  7553. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7554. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7555. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7556. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7557. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7558. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7559. #endif
  7560. }
  7561. TEST_F(ServerTest, PutContentWithDeflate) {
  7562. cli_.set_compress(false);
  7563. Headers headers;
  7564. headers.emplace("Content-Encoding", "deflate");
  7565. // PUT in deflate format:
  7566. auto res = cli_.Put("/put", headers,
  7567. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7569. EXPECT_EQ(StatusCode::OK_200, res->status);
  7570. EXPECT_EQ("PUT", res->body);
  7571. }
  7572. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7573. Headers headers;
  7574. headers.emplace("Accept-Encoding", "gzip, deflate");
  7575. auto res = cli_.Get("/streamed-chunked", headers);
  7576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7577. EXPECT_EQ(StatusCode::OK_200, res->status);
  7578. EXPECT_EQ(std::string("123456789"), res->body);
  7579. }
  7580. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7581. Headers headers;
  7582. headers.emplace("Accept-Encoding", "gzip, deflate");
  7583. auto res = cli_.Get("/streamed-chunked2", headers);
  7584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7585. EXPECT_EQ(StatusCode::OK_200, res->status);
  7586. EXPECT_EQ(std::string("123456789"), res->body);
  7587. }
  7588. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7589. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7591. EXPECT_EQ(StatusCode::OK_200, res->status);
  7592. }
  7593. TEST(GzipDecompressor, ChunkedDecompression) {
  7594. std::string data;
  7595. for (size_t i = 0; i < 32 * 1024; ++i) {
  7596. data.push_back(static_cast<char>('a' + i % 26));
  7597. }
  7598. std::string compressed_data;
  7599. {
  7600. httplib::detail::gzip_compressor compressor;
  7601. bool result = compressor.compress(
  7602. data.data(), data.size(),
  7603. /*last=*/true,
  7604. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7605. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7606. compressed_data_size);
  7607. return true;
  7608. });
  7609. ASSERT_TRUE(result);
  7610. }
  7611. std::string decompressed_data;
  7612. {
  7613. httplib::detail::gzip_decompressor decompressor;
  7614. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7615. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7616. size_t chunk_size = 130;
  7617. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7618. chunk_begin += chunk_size) {
  7619. size_t current_chunk_size =
  7620. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7621. bool result = decompressor.decompress(
  7622. compressed_data.data() + chunk_begin, current_chunk_size,
  7623. [&](const char *decompressed_data_chunk,
  7624. size_t decompressed_data_chunk_size) {
  7625. decompressed_data.insert(decompressed_data.size(),
  7626. decompressed_data_chunk,
  7627. decompressed_data_chunk_size);
  7628. return true;
  7629. });
  7630. ASSERT_TRUE(result);
  7631. }
  7632. }
  7633. ASSERT_EQ(data, decompressed_data);
  7634. }
  7635. TEST(GzipDecompressor, DeflateDecompression) {
  7636. std::string original_text = "Raw deflate without gzip";
  7637. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7638. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7639. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7640. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7641. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7642. std::string decompressed_data;
  7643. {
  7644. httplib::detail::gzip_decompressor decompressor;
  7645. bool result = decompressor.decompress(
  7646. compressed_data.data(), compressed_data.size(),
  7647. [&](const char *decompressed_data_chunk,
  7648. size_t decompressed_data_chunk_size) {
  7649. decompressed_data.insert(decompressed_data.size(),
  7650. decompressed_data_chunk,
  7651. decompressed_data_chunk_size);
  7652. return true;
  7653. });
  7654. ASSERT_TRUE(result);
  7655. }
  7656. ASSERT_EQ(original_text, decompressed_data);
  7657. }
  7658. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7659. std::string original_text = "Raw deflate without gzip";
  7660. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7661. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7662. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7663. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7664. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7665. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7666. std::string decompressed_data;
  7667. {
  7668. httplib::detail::gzip_decompressor decompressor;
  7669. bool result = decompressor.decompress(
  7670. compressed_data.data(), compressed_data.size(),
  7671. [&](const char *decompressed_data_chunk,
  7672. size_t decompressed_data_chunk_size) {
  7673. decompressed_data.insert(decompressed_data.size(),
  7674. decompressed_data_chunk,
  7675. decompressed_data_chunk_size);
  7676. return true;
  7677. });
  7678. ASSERT_TRUE(result);
  7679. }
  7680. ASSERT_EQ(original_text, decompressed_data);
  7681. }
  7682. #endif
  7683. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7684. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7685. Headers headers;
  7686. headers.emplace("Accept-Encoding", "br");
  7687. auto res = cli_.Get("/streamed-chunked", headers);
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. EXPECT_EQ(std::string("123456789"), res->body);
  7691. }
  7692. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7693. Headers headers;
  7694. headers.emplace("Accept-Encoding", "br");
  7695. auto res = cli_.Get("/streamed-chunked2", headers);
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ(std::string("123456789"), res->body);
  7699. }
  7700. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7701. cli_.set_compress(true);
  7702. auto res = cli_.Put(
  7703. "/put", 3,
  7704. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7705. sink.os << "PUT";
  7706. return true;
  7707. },
  7708. "text/plain");
  7709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7710. EXPECT_EQ(StatusCode::OK_200, res->status);
  7711. EXPECT_EQ("PUT", res->body);
  7712. }
  7713. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7714. cli_.set_compress(true);
  7715. auto res = cli_.Put(
  7716. "/put",
  7717. [](size_t /*offset*/, DataSink &sink) {
  7718. sink.os << "PUT";
  7719. sink.done();
  7720. return true;
  7721. },
  7722. "text/plain");
  7723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7724. EXPECT_EQ(StatusCode::OK_200, res->status);
  7725. EXPECT_EQ("PUT", res->body);
  7726. }
  7727. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7728. cli_.set_compress(true);
  7729. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7731. EXPECT_EQ(StatusCode::OK_200, res->status);
  7732. EXPECT_EQ(LARGE_DATA, res->body);
  7733. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7734. }
  7735. #endif
  7736. TEST_F(ServerTest, Patch) {
  7737. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7739. EXPECT_EQ(StatusCode::OK_200, res->status);
  7740. EXPECT_EQ("PATCH", res->body);
  7741. }
  7742. TEST_F(ServerTest, Delete) {
  7743. auto res = cli_.Delete("/delete");
  7744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7745. EXPECT_EQ(StatusCode::OK_200, res->status);
  7746. EXPECT_EQ("DELETE", res->body);
  7747. }
  7748. TEST_F(ServerTest, DeleteContentReceiver) {
  7749. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7751. EXPECT_EQ(StatusCode::OK_200, res->status);
  7752. EXPECT_EQ("content", res->body);
  7753. }
  7754. TEST_F(ServerTest, Options) {
  7755. auto res = cli_.Options("*");
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7759. EXPECT_TRUE(res->body.empty());
  7760. }
  7761. TEST_F(ServerTest, URL) {
  7762. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7764. EXPECT_EQ(StatusCode::OK_200, res->status);
  7765. }
  7766. TEST_F(ServerTest, ArrayParam) {
  7767. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. }
  7771. TEST_F(ServerTest, ArrayParamValues) {
  7772. auto res =
  7773. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7775. EXPECT_EQ(StatusCode::OK_200, res->status);
  7776. }
  7777. TEST_F(ServerTest, NoMultipleHeaders) {
  7778. Headers headers = {{"Content-Length", "5"}};
  7779. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7780. "text/plain");
  7781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7782. EXPECT_EQ(StatusCode::OK_200, res->status);
  7783. }
  7784. TEST_F(ServerTest, PostContentReceiver) {
  7785. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7787. ASSERT_EQ(StatusCode::OK_200, res->status);
  7788. ASSERT_EQ("content", res->body);
  7789. }
  7790. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7791. UploadFormDataItems items = {
  7792. {"text1", "text default", "", ""},
  7793. {"text2", "aωb", "", ""},
  7794. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7795. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7796. {"file3", "", "", "application/octet-stream"},
  7797. };
  7798. auto res = cli_.Post("/content_receiver", items);
  7799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7800. EXPECT_EQ(StatusCode::OK_200, res->status);
  7801. }
  7802. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7803. UploadFormDataItems items = {
  7804. {"text1", "text default", "", ""},
  7805. {"text2", "aωb", "", ""},
  7806. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7807. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7808. {"file3", "", "", "application/octet-stream"},
  7809. };
  7810. auto boundary = std::string("+++++");
  7811. std::string body;
  7812. for (const auto &item : items) {
  7813. body += "--" + boundary + "\r\n";
  7814. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7815. if (!item.filename.empty()) {
  7816. body += "; filename=\"" + item.filename + "\"";
  7817. }
  7818. body += "\r\n";
  7819. if (!item.content_type.empty()) {
  7820. body += "Content-Type: " + item.content_type + "\r\n";
  7821. }
  7822. body += "\r\n";
  7823. body += item.content + "\r\n";
  7824. }
  7825. body += "--" + boundary + "--\r\n";
  7826. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7827. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7829. EXPECT_EQ(StatusCode::OK_200, res->status);
  7830. }
  7831. TEST(MultipartFormDataTest, FieldEscaping) {
  7832. Server svr;
  7833. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7834. const ContentReader &content_reader) {
  7835. ASSERT_TRUE(req.is_multipart_form_data());
  7836. std::vector<FormData> received;
  7837. content_reader(
  7838. [&](const FormData &file) {
  7839. received.push_back(file);
  7840. return true;
  7841. },
  7842. [&](const char *data, size_t data_length) {
  7843. received.back().content.append(data, data_length);
  7844. return true;
  7845. });
  7846. // '"', CR and LF in names and filenames are escaped following the
  7847. // WHATWG HTML standard, so each part still parses as a single part
  7848. // with no injected headers. Content types get CR/LF escaped too,
  7849. // while '"' (legal there, e.g. quoted charset) is preserved.
  7850. ASSERT_EQ(4U, received.size());
  7851. EXPECT_EQ("na%22me", received[0].name);
  7852. EXPECT_EQ("quoted name", received[0].content);
  7853. EXPECT_EQ("file", received[1].name);
  7854. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7855. received[1].filename);
  7856. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7857. EXPECT_EQ("injected", received[1].content);
  7858. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7859. EXPECT_EQ("my%22file.txt", received[2].filename);
  7860. EXPECT_EQ("cr lf name", received[2].content);
  7861. EXPECT_EQ("typed", received[3].name);
  7862. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7863. received[3].content_type);
  7864. EXPECT_EQ("typed content", received[3].content);
  7865. });
  7866. auto port = svr.bind_to_any_port("localhost");
  7867. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7868. auto se = detail::scope_exit([&] {
  7869. svr.stop();
  7870. t.join();
  7871. ASSERT_FALSE(svr.is_running());
  7872. });
  7873. svr.wait_until_ready();
  7874. Client cli("localhost", port);
  7875. UploadFormDataItems items = {
  7876. {"na\"me", "quoted name", "", ""},
  7877. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7878. "application/octet-stream"},
  7879. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7880. {"typed", "typed content", "",
  7881. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7882. };
  7883. auto res = cli.Post("/post", items);
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. EXPECT_EQ(StatusCode::OK_200, res->status);
  7886. }
  7887. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7888. const UploadFormDataItems items = {
  7889. {"name1", "Content 1", "", ""},
  7890. {"name2", "Content 2", "file2.txt", "text/plain"},
  7891. };
  7892. Server svr;
  7893. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7894. const ContentReader &content_reader) {
  7895. ASSERT_TRUE(req.is_multipart_form_data());
  7896. std::vector<FormData> received;
  7897. content_reader(
  7898. [&](const FormData &file) {
  7899. received.push_back(file);
  7900. return true;
  7901. },
  7902. [&](const char *data, size_t data_length) {
  7903. received.back().content.append(data, data_length);
  7904. return true;
  7905. });
  7906. ASSERT_EQ(2U, received.size());
  7907. EXPECT_EQ("name1", received[0].name);
  7908. EXPECT_EQ("Content 1", received[0].content);
  7909. EXPECT_EQ("name2", received[1].name);
  7910. EXPECT_EQ("Content 2", received[1].content);
  7911. EXPECT_EQ("file2.txt", received[1].filename);
  7912. EXPECT_EQ("text/plain", received[1].content_type);
  7913. });
  7914. auto port = svr.bind_to_any_port("localhost");
  7915. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7916. auto se = detail::scope_exit([&] {
  7917. svr.stop();
  7918. t.join();
  7919. ASSERT_FALSE(svr.is_running());
  7920. });
  7921. svr.wait_until_ready();
  7922. Client cli("localhost", port);
  7923. // Whole-body serialization with a generated boundary
  7924. {
  7925. MultipartFormDataWriter writer;
  7926. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7927. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7928. writer.content_type());
  7929. auto body = writer.serialize(items);
  7930. EXPECT_EQ(body.size(), writer.content_length(items));
  7931. auto res = cli.Post("/post", body, writer.content_type());
  7932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7933. EXPECT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. // Per-part framing with a custom boundary via a content provider
  7936. {
  7937. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7938. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7939. MultipartFormDataWriter writer("custom-boundary_123");
  7940. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7941. std::string body;
  7942. for (const auto &item : items) {
  7943. body += writer.item_begin(item);
  7944. body += item.content;
  7945. body += MultipartFormDataWriter::item_end();
  7946. }
  7947. body += writer.finish();
  7948. EXPECT_EQ(body.size(), writer.content_length(items));
  7949. auto res = cli.Post(
  7950. "/post", body.size(),
  7951. [&](size_t offset, size_t length, DataSink &sink) {
  7952. sink.write(body.data() + offset, length);
  7953. return true;
  7954. },
  7955. writer.content_type());
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. }
  7959. }
  7960. TEST_F(ServerTest, PostContentReceiverGzip) {
  7961. cli_.set_compress(true);
  7962. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. ASSERT_EQ(StatusCode::OK_200, res->status);
  7965. ASSERT_EQ("content", res->body);
  7966. }
  7967. TEST_F(ServerTest, PutContentReceiver) {
  7968. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7970. ASSERT_EQ(StatusCode::OK_200, res->status);
  7971. ASSERT_EQ("content", res->body);
  7972. }
  7973. TEST_F(ServerTest, PatchContentReceiver) {
  7974. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7976. ASSERT_EQ(StatusCode::OK_200, res->status);
  7977. ASSERT_EQ("content", res->body);
  7978. }
  7979. template <typename ClientType>
  7980. void TestWithHeadersAndContentReceiver(
  7981. ClientType &cli,
  7982. std::function<Result(ClientType &, const std::string &, const Headers &,
  7983. const std::string &, const std::string &,
  7984. ContentReceiver, DownloadProgress)>
  7985. request_func) {
  7986. Headers headers;
  7987. headers.emplace("X-Custom-Header", "test-value");
  7988. std::string received_body;
  7989. auto res = request_func(
  7990. cli, "/content_receiver", headers, "content", "application/json",
  7991. [&](const char *data, size_t data_length) {
  7992. received_body.append(data, data_length);
  7993. return true;
  7994. },
  7995. nullptr);
  7996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7997. EXPECT_EQ(StatusCode::OK_200, res->status);
  7998. EXPECT_EQ("content", received_body);
  7999. }
  8000. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8001. #ifdef CPPHTTPLIB_SSL_ENABLED
  8002. using ClientT = SSLClient;
  8003. #else
  8004. using ClientT = Client;
  8005. #endif
  8006. TestWithHeadersAndContentReceiver<ClientT>(
  8007. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8008. const std::string &body, const std::string &content_type,
  8009. ContentReceiver receiver, DownloadProgress progress) {
  8010. return cli.Post(path, headers, body, content_type, receiver, progress);
  8011. });
  8012. }
  8013. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8014. #ifdef CPPHTTPLIB_SSL_ENABLED
  8015. using ClientT = SSLClient;
  8016. #else
  8017. using ClientT = Client;
  8018. #endif
  8019. TestWithHeadersAndContentReceiver<ClientT>(
  8020. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8021. const std::string &body, const std::string &content_type,
  8022. ContentReceiver receiver, DownloadProgress progress) {
  8023. return cli.Put(path, headers, body, content_type, receiver, progress);
  8024. });
  8025. }
  8026. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8027. #ifdef CPPHTTPLIB_SSL_ENABLED
  8028. using ClientT = SSLClient;
  8029. #else
  8030. using ClientT = Client;
  8031. #endif
  8032. TestWithHeadersAndContentReceiver<ClientT>(
  8033. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8034. const std::string &body, const std::string &content_type,
  8035. ContentReceiver receiver, DownloadProgress progress) {
  8036. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8037. });
  8038. }
  8039. template <typename ClientType>
  8040. void TestWithHeadersAndContentReceiverWithProgress(
  8041. ClientType &cli,
  8042. std::function<Result(ClientType &, const std::string &, const Headers &,
  8043. const std::string &, const std::string &,
  8044. ContentReceiver, DownloadProgress)>
  8045. request_func) {
  8046. Headers headers;
  8047. headers.emplace("X-Test-Header", "progress-test");
  8048. std::string received_body;
  8049. auto progress_called = false;
  8050. auto res = request_func(
  8051. cli, "/content_receiver", headers, "content", "text/plain",
  8052. [&](const char *data, size_t data_length) {
  8053. received_body.append(data, data_length);
  8054. return true;
  8055. },
  8056. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8057. progress_called = true;
  8058. return true;
  8059. });
  8060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. EXPECT_EQ("content", received_body);
  8063. EXPECT_TRUE(progress_called);
  8064. }
  8065. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8066. #ifdef CPPHTTPLIB_SSL_ENABLED
  8067. using ClientT = SSLClient;
  8068. #else
  8069. using ClientT = Client;
  8070. #endif
  8071. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8072. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8073. const std::string &body, const std::string &content_type,
  8074. ContentReceiver receiver, DownloadProgress progress) {
  8075. return cli.Post(path, headers, body, content_type, receiver, progress);
  8076. });
  8077. }
  8078. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. using ClientT = SSLClient;
  8081. #else
  8082. using ClientT = Client;
  8083. #endif
  8084. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8085. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8086. const std::string &body, const std::string &content_type,
  8087. ContentReceiver receiver, DownloadProgress progress) {
  8088. return cli.Put(path, headers, body, content_type, receiver, progress);
  8089. });
  8090. }
  8091. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8092. #ifdef CPPHTTPLIB_SSL_ENABLED
  8093. using ClientT = SSLClient;
  8094. #else
  8095. using ClientT = Client;
  8096. #endif
  8097. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8098. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8099. const std::string &body, const std::string &content_type,
  8100. ContentReceiver receiver, DownloadProgress progress) {
  8101. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8102. });
  8103. }
  8104. template <typename ClientType>
  8105. void TestWithHeadersAndContentReceiverError(
  8106. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8107. const Headers &, const std::string &,
  8108. const std::string &, ContentReceiver)>
  8109. request_func) {
  8110. Headers headers;
  8111. headers.emplace("X-Error-Test", "true");
  8112. std::string received_body;
  8113. auto receiver_failed = false;
  8114. auto res =
  8115. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8116. [&](const char *data, size_t data_length) {
  8117. received_body.append(data, data_length);
  8118. receiver_failed = true;
  8119. return false;
  8120. });
  8121. ASSERT_FALSE(res);
  8122. EXPECT_TRUE(receiver_failed);
  8123. }
  8124. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8125. #ifdef CPPHTTPLIB_SSL_ENABLED
  8126. using ClientT = SSLClient;
  8127. #else
  8128. using ClientT = Client;
  8129. #endif
  8130. TestWithHeadersAndContentReceiverError<ClientT>(
  8131. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8132. const std::string &body, const std::string &content_type,
  8133. ContentReceiver receiver) {
  8134. return cli.Post(path, headers, body, content_type, receiver);
  8135. });
  8136. }
  8137. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8138. #ifdef CPPHTTPLIB_SSL_ENABLED
  8139. using ClientT = SSLClient;
  8140. #else
  8141. using ClientT = Client;
  8142. #endif
  8143. TestWithHeadersAndContentReceiverError<ClientT>(
  8144. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8145. const std::string &body, const std::string &content_type,
  8146. ContentReceiver receiver) {
  8147. return cli.Put(path, headers, body, content_type, receiver);
  8148. });
  8149. }
  8150. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8151. #ifdef CPPHTTPLIB_SSL_ENABLED
  8152. using ClientT = SSLClient;
  8153. #else
  8154. using ClientT = Client;
  8155. #endif
  8156. TestWithHeadersAndContentReceiverError<ClientT>(
  8157. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8158. const std::string &body, const std::string &content_type,
  8159. ContentReceiver receiver) {
  8160. return cli.Patch(path, headers, body, content_type, receiver);
  8161. });
  8162. }
  8163. TEST_F(ServerTest, PostQueryStringAndBody) {
  8164. auto res =
  8165. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. ASSERT_EQ(StatusCode::OK_200, res->status);
  8168. }
  8169. TEST_F(ServerTest, HTTP2Magic) {
  8170. Request req;
  8171. req.method = "PRI";
  8172. req.path = "*";
  8173. req.body = "SM";
  8174. auto res = std::make_shared<Response>();
  8175. auto error = Error::Success;
  8176. auto ret = cli_.send(req, *res, error);
  8177. ASSERT_TRUE(ret);
  8178. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8179. }
  8180. TEST_F(ServerTest, KeepAlive) {
  8181. auto res = cli_.Get("/hi");
  8182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8183. EXPECT_EQ(StatusCode::OK_200, res->status);
  8184. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8185. EXPECT_EQ("Hello World!", res->body);
  8186. res = cli_.Get("/hi");
  8187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8188. EXPECT_EQ(StatusCode::OK_200, res->status);
  8189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8190. EXPECT_EQ("Hello World!", res->body);
  8191. res = cli_.Get("/hi");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8195. EXPECT_EQ("Hello World!", res->body);
  8196. res = cli_.Get("/not-exist");
  8197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8198. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8199. res = cli_.Post("/empty", "", "text/plain");
  8200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8201. EXPECT_EQ(StatusCode::OK_200, res->status);
  8202. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8203. EXPECT_EQ("empty", res->body);
  8204. EXPECT_EQ("close", res->get_header_value("Connection"));
  8205. res = cli_.Post(
  8206. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8207. "text/plain");
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8211. EXPECT_EQ("empty", res->body);
  8212. cli_.set_keep_alive(false);
  8213. res = cli_.Get("/last-request");
  8214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8215. EXPECT_EQ(StatusCode::OK_200, res->status);
  8216. EXPECT_EQ("close", res->get_header_value("Connection"));
  8217. }
  8218. TEST_F(ServerTest, TooManyRedirect) {
  8219. cli_.set_follow_location(true);
  8220. auto res = cli_.Get("/redirect/0");
  8221. ASSERT_TRUE(!res);
  8222. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8223. }
  8224. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8225. Request req;
  8226. req.method = "FOOBAR";
  8227. req.path = "/hi";
  8228. cli_.set_keep_alive(true);
  8229. auto res = cli_.send(req);
  8230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8231. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8232. EXPECT_EQ("close", res->get_header_value("Connection"));
  8233. EXPECT_FALSE(cli_.is_socket_open());
  8234. }
  8235. TEST_F(ServerTest, CustomRouteReadsBody) {
  8236. const std::string xml =
  8237. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8238. Request req;
  8239. req.method = "PROPFIND";
  8240. req.path = "/dav/dir";
  8241. req.set_header("Depth", "1");
  8242. req.body = xml;
  8243. auto res = cli_.send(req);
  8244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8245. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8246. EXPECT_EQ(xml, res->body);
  8247. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8248. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8249. }
  8250. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8251. Request req;
  8252. req.method = "PROPFIND";
  8253. req.path = "/dav/42";
  8254. auto res = cli_.send(req);
  8255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8256. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8257. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8258. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8259. }
  8260. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8261. Request req;
  8262. req.method = "PROPFIND";
  8263. req.path = "/dav-re/123";
  8264. auto res = cli_.send(req);
  8265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8266. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8267. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8268. }
  8269. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8270. Request req;
  8271. req.method = "MKCOL";
  8272. req.path = "/dav-mkcol";
  8273. auto res = cli_.send(req);
  8274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8275. EXPECT_EQ(StatusCode::Created_201, res->status);
  8276. }
  8277. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8278. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8279. Request req;
  8280. req.method = "REPORT";
  8281. req.path = "/dav-report";
  8282. req.body = xml;
  8283. auto res = cli_.send(req);
  8284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8285. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8286. EXPECT_EQ(xml, res->body);
  8287. }
  8288. // A content reader route must fire even when the request carries no body,
  8289. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8290. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8291. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8292. Request req;
  8293. req.method = "REPORT";
  8294. req.path = "/dav-report";
  8295. auto res = cli_.send(req);
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8298. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8299. }
  8300. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8301. Request req;
  8302. req.method = "PROPFIND";
  8303. req.path = "/not-dav";
  8304. auto res = cli_.send(req);
  8305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8307. }
  8308. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8309. Request req;
  8310. req.method = "UNLOCK";
  8311. req.path = "/dav/dir";
  8312. cli_.set_keep_alive(true);
  8313. auto res = cli_.send(req);
  8314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8315. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8316. EXPECT_EQ("close", res->get_header_value("Connection"));
  8317. EXPECT_FALSE(cli_.is_socket_open());
  8318. }
  8319. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8320. // The mount point serves this path, but only for GET and HEAD.
  8321. auto get_res = cli_.Get("/dir/index.html");
  8322. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8323. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8324. Request req;
  8325. req.method = "PROPFIND";
  8326. req.path = "/dir/index.html";
  8327. auto res = cli_.send(req);
  8328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8329. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8330. }
  8331. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8332. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8333. cli_.set_keep_alive(true);
  8334. for (auto i = 0; i < 2; i++) {
  8335. Request req;
  8336. req.method = "PROPFIND";
  8337. req.path = "/dav/dir";
  8338. req.body = xml;
  8339. auto res = cli_.send(req);
  8340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8341. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8342. EXPECT_EQ(xml, res->body);
  8343. EXPECT_TRUE(cli_.is_socket_open());
  8344. }
  8345. // A built-in method must still be served on the same connection.
  8346. cli_.set_keep_alive(false);
  8347. auto res = cli_.Get("/hi");
  8348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8349. EXPECT_EQ(StatusCode::OK_200, res->status);
  8350. EXPECT_EQ("close", res->get_header_value("Connection"));
  8351. }
  8352. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8353. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8354. Request req;
  8355. req.method = "PROPFIND";
  8356. req.path = "/dav/dir";
  8357. req.set_header("Expect", "100-continue");
  8358. req.body = xml;
  8359. auto res = cli_.send(req);
  8360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8361. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8362. EXPECT_EQ(xml, res->body);
  8363. }
  8364. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8365. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8366. TEST_F(ServerTest, Gzip) {
  8367. Headers headers;
  8368. headers.emplace("Accept-Encoding", "gzip, deflate");
  8369. auto res = cli_.Get("/compress", headers);
  8370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8371. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8372. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8373. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8374. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8375. "7890123456789012345678901234567890",
  8376. res->body);
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "gzip, deflate");
  8382. auto res = cli_.Get("/compress-with-charset", headers);
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8385. EXPECT_EQ("application/json; charset=utf-8",
  8386. res->get_header_value("Content-Type"));
  8387. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8388. "7890123456789012345678901234567890",
  8389. res->body);
  8390. EXPECT_EQ(StatusCode::OK_200, res->status);
  8391. }
  8392. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8393. Headers headers;
  8394. headers.emplace("Accept-Encoding", "");
  8395. auto res = cli_.Get("/compress", headers);
  8396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8397. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8399. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8400. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8401. "7890123456789012345678901234567890",
  8402. res->body);
  8403. EXPECT_EQ(StatusCode::OK_200, res->status);
  8404. }
  8405. TEST_F(ServerTest, GzipWithContentReceiver) {
  8406. Headers headers;
  8407. headers.emplace("Accept-Encoding", "gzip, deflate");
  8408. std::string body;
  8409. auto res =
  8410. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8411. EXPECT_EQ(100U, data_length);
  8412. body.append(data, data_length);
  8413. return true;
  8414. });
  8415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8416. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8417. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8418. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8419. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8420. "7890123456789012345678901234567890",
  8421. body);
  8422. EXPECT_EQ(StatusCode::OK_200, res->status);
  8423. }
  8424. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8425. Headers headers;
  8426. headers.emplace("Accept-Encoding", "gzip, deflate");
  8427. cli_.set_decompress(false);
  8428. auto res = cli_.Get("/compress", headers);
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8431. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8432. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8433. EXPECT_EQ(33U, res->body.size());
  8434. EXPECT_EQ(StatusCode::OK_200, res->status);
  8435. }
  8436. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8437. Headers headers;
  8438. headers.emplace("Accept-Encoding", "");
  8439. std::string body;
  8440. auto res =
  8441. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8442. EXPECT_EQ(100U, data_length);
  8443. body.append(data, data_length);
  8444. return true;
  8445. });
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8448. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8449. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8450. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8451. "7890123456789012345678901234567890",
  8452. body);
  8453. EXPECT_EQ(StatusCode::OK_200, res->status);
  8454. }
  8455. TEST_F(ServerTest, NoGzip) {
  8456. Headers headers;
  8457. headers.emplace("Accept-Encoding", "gzip, deflate");
  8458. auto res = cli_.Get("/nocompress", headers);
  8459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8460. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8461. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8462. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8463. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8464. "7890123456789012345678901234567890",
  8465. res->body);
  8466. EXPECT_EQ(StatusCode::OK_200, res->status);
  8467. }
  8468. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8469. Headers headers;
  8470. headers.emplace("Accept-Encoding", "gzip, deflate");
  8471. std::string body;
  8472. auto res = cli_.Get("/nocompress", headers,
  8473. [&](const char *data, size_t data_length) {
  8474. EXPECT_EQ(100U, data_length);
  8475. body.append(data, data_length);
  8476. return true;
  8477. });
  8478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8479. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8480. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8481. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8482. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8483. "7890123456789012345678901234567890",
  8484. body);
  8485. EXPECT_EQ(StatusCode::OK_200, res->status);
  8486. }
  8487. TEST_F(ServerTest, MultipartFormDataGzip) {
  8488. UploadFormDataItems items = {
  8489. {"key1", "test", "", ""},
  8490. {"key2", "--abcdefg123", "", ""},
  8491. };
  8492. cli_.set_compress(true);
  8493. auto res = cli_.Post("/compress-multipart", items);
  8494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8495. EXPECT_EQ(StatusCode::OK_200, res->status);
  8496. }
  8497. #endif
  8498. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8499. // Static file compression is opt-in, so these run their own server rather than
  8500. // flipping it on for the shared ServerTest fixture, which would silently
  8501. // rewrite what every other static file test is asserting.
  8502. class StaticFileCompressionTest : public ::testing::Test {
  8503. protected:
  8504. void TearDown() override {
  8505. if (t_.joinable()) {
  8506. svr_.stop();
  8507. t_.join();
  8508. }
  8509. }
  8510. int start(const std::function<void(Server &)> &configure = nullptr) {
  8511. // Serves the same tree as a directory of build-time compressed assets
  8512. // would be served: the mount point names the coding the files are already
  8513. // stored in. Registered before "/" so it is the one that matches.
  8514. svr_.set_mount_point("/pre-encoded", "./www",
  8515. {{"Content-Encoding", "gzip"}});
  8516. svr_.set_mount_point("/", "./www");
  8517. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8518. res.set_file_content("./www/dir/index.html", "text/html");
  8519. });
  8520. svr_.Get("/pre-encoded-file-content",
  8521. [](const Request & /*req*/, Response &res) {
  8522. res.set_header("Content-Encoding", "gzip");
  8523. res.set_file_content("./www/dir/index.html", "text/html");
  8524. });
  8525. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8526. res.set_content_provider(
  8527. 6, "text/plain",
  8528. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8529. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8530. return true;
  8531. });
  8532. });
  8533. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8534. res.set_content_provider(
  8535. 1000, "text/plain",
  8536. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8537. if (offset < 100) {
  8538. std::string data(100, 'A');
  8539. sink.write(data.data(), data.size());
  8540. return true;
  8541. }
  8542. std::this_thread::sleep_for(std::chrono::seconds(2));
  8543. std::string data(900, 'B');
  8544. sink.write(data.data(), data.size());
  8545. return true;
  8546. });
  8547. });
  8548. if (configure) { configure(svr_); }
  8549. auto port = svr_.bind_to_any_port(HOST);
  8550. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8551. svr_.wait_until_ready();
  8552. return port;
  8553. }
  8554. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8555. // Every file under ./www except 1MB.txt is smaller than the default
  8556. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8557. // it out of the way.
  8558. static void enable_without_floor(Server &svr) {
  8559. svr.set_static_file_compression(true);
  8560. svr.set_static_file_compression_min_length(0);
  8561. }
  8562. Server svr_;
  8563. std::thread t_;
  8564. };
  8565. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8566. auto port = start();
  8567. Client cli(HOST, port);
  8568. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8570. EXPECT_EQ(StatusCode::OK_200, res->status);
  8571. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8572. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8573. EXPECT_EQ(1048576U, res->body.size());
  8574. }
  8575. TEST_F(StaticFileCompressionTest, MountPoint) {
  8576. auto port = start(enable);
  8577. Client cli(HOST, port);
  8578. cli.set_decompress(false);
  8579. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8581. EXPECT_EQ(StatusCode::OK_200, res->status);
  8582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8583. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8584. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8585. // The response stays self-delimiting: a length, not a chunked body.
  8586. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8587. EXPECT_EQ(std::to_string(res->body.size()),
  8588. res->get_header_value("Content-Length"));
  8589. EXPECT_LT(res->body.size(), 1048576U);
  8590. EXPECT_FALSE(res->body.empty());
  8591. }
  8592. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8593. auto port = start(enable);
  8594. Client cli(HOST, port);
  8595. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8597. EXPECT_EQ(StatusCode::OK_200, res->status);
  8598. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8599. EXPECT_EQ(1048576U, res->body.size());
  8600. }
  8601. TEST_F(StaticFileCompressionTest, FileContent) {
  8602. auto port = start(enable_without_floor);
  8603. Client cli(HOST, port);
  8604. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8606. EXPECT_EQ(StatusCode::OK_200, res->status);
  8607. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8608. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8609. EXPECT_EQ(104U, res->body.size());
  8610. }
  8611. // A handler that serves an already-encoded file names the coding itself. The
  8612. // file-backed path decided its coding from Accept-Encoding and the content
  8613. // type alone, so it compressed the stored bytes a second time and appended a
  8614. // second Content-Encoding field line.
  8615. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8616. auto port = start(enable_without_floor);
  8617. Client cli(HOST, port);
  8618. cli.set_decompress(false);
  8619. auto res = cli.Get("/pre-encoded-file-content",
  8620. Headers{{"Accept-Encoding", "gzip"}});
  8621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8622. EXPECT_EQ(StatusCode::OK_200, res->status);
  8623. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8624. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8625. // Vary belongs to a coding the server chose, and it chose none here.
  8626. EXPECT_FALSE(res->has_header("Vary"));
  8627. // The file travels exactly as it is stored on disk.
  8628. EXPECT_EQ(104U, res->body.size());
  8629. }
  8630. // The 1MB file clears the default floor, so this one runs the configuration a
  8631. // deployment would actually have.
  8632. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8633. auto port = start(enable);
  8634. Client cli(HOST, port);
  8635. cli.set_decompress(false);
  8636. auto res =
  8637. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_EQ(StatusCode::OK_200, res->status);
  8640. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8641. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8642. EXPECT_FALSE(res->has_header("Vary"));
  8643. EXPECT_EQ(1048576U, res->body.size());
  8644. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8645. }
  8646. TEST_F(StaticFileCompressionTest, Head) {
  8647. auto port = start(enable);
  8648. Client cli(HOST, port);
  8649. cli.set_decompress(false);
  8650. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8651. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8652. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8654. EXPECT_EQ(StatusCode::OK_200, res->status);
  8655. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8656. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8657. // HEAD still reports the size a GET would return.
  8658. EXPECT_EQ(get->get_header_value("Content-Length"),
  8659. res->get_header_value("Content-Length"));
  8660. EXPECT_TRUE(res->body.empty());
  8661. }
  8662. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8663. auto port = start(enable);
  8664. Client cli(HOST, port);
  8665. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8666. {"Accept-Encoding", "gzip"}});
  8667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8668. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8669. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8670. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8671. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8672. EXPECT_EQ("cd", res->body);
  8673. }
  8674. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8675. auto port = start(enable);
  8676. Client cli(HOST, port);
  8677. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8679. EXPECT_EQ(StatusCode::OK_200, res->status);
  8680. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8681. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8682. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8683. }
  8684. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8685. auto port = start(enable);
  8686. Client cli(HOST, port);
  8687. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8689. EXPECT_EQ(StatusCode::OK_200, res->status);
  8690. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8691. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8692. EXPECT_TRUE(res->body.empty());
  8693. }
  8694. TEST_F(StaticFileCompressionTest, MinLength) {
  8695. auto port = start(enable);
  8696. Client cli(HOST, port);
  8697. // 104 bytes, well under the default floor. Compressing it would add the
  8698. // gzip header and trailer to a body that already fits in one packet.
  8699. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8701. EXPECT_EQ(StatusCode::OK_200, res->status);
  8702. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8703. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8704. }
  8705. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8706. auto port = start([](Server &svr) {
  8707. svr.set_static_file_compression(true);
  8708. svr.set_static_file_compression_min_length(1);
  8709. });
  8710. Client cli(HOST, port);
  8711. cli.set_decompress(false);
  8712. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8714. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8715. // A 9-byte file comes back larger than it went in, because gzip's header and
  8716. // trailer outweigh anything deflate can save. That is the end of the range
  8717. // the floor exists to keep out.
  8718. EXPECT_GT(res->body.size(), 9U);
  8719. }
  8720. TEST_F(StaticFileCompressionTest, MaxLength) {
  8721. auto port = start([](Server &svr) {
  8722. svr.set_static_file_compression(true);
  8723. svr.set_static_file_compression_min_length(0);
  8724. svr.set_static_file_compression_max_length(1024);
  8725. });
  8726. Client cli(HOST, port);
  8727. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8728. // defines `small` as a macro on Windows.
  8729. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8730. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8731. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8732. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8733. // Under it: compressed.
  8734. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8735. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8736. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8737. }
  8738. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8739. auto port = start(enable_without_floor);
  8740. Client cli(HOST, port);
  8741. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8742. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8743. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8744. auto identity_etag = identity->get_header_value("ETag");
  8745. ASSERT_FALSE(identity_etag.empty());
  8746. auto gzipped =
  8747. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8748. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8749. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8750. auto gzip_etag = gzipped->get_header_value("ETag");
  8751. ASSERT_FALSE(gzip_etag.empty());
  8752. // Two representations, two validators.
  8753. EXPECT_NE(identity_etag, gzip_etag);
  8754. // Each one revalidates against the request that would produce it...
  8755. auto fresh =
  8756. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8757. {"If-None-Match", gzip_etag}});
  8758. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8759. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8760. auto fresh_identity =
  8761. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8762. {"If-None-Match", identity_etag}});
  8763. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8764. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8765. // ...and not against the other representation.
  8766. auto crossed =
  8767. cli.Get("/dir/index.html",
  8768. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8769. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8770. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8771. }
  8772. // The opt-in covers responses the server reads off disk itself. A caller's own
  8773. // known-length provider keeps its Content-Length and, more importantly, keeps
  8774. // delivering incrementally: routing it through a compressor would hold every
  8775. // write back until zlib's window filled.
  8776. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8777. auto port = start(enable);
  8778. Client cli(HOST, port);
  8779. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8781. EXPECT_EQ(StatusCode::OK_200, res->status);
  8782. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8783. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8784. EXPECT_EQ("aaabbb", res->body);
  8785. }
  8786. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8787. auto port = start(enable);
  8788. Client cli(HOST, port);
  8789. cli.set_read_timeout(1, 0);
  8790. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8791. Headers{{"Accept-Encoding", "gzip"}});
  8792. ASSERT_TRUE(handle.is_valid());
  8793. // The provider writes 100 bytes and then stalls for longer than the read
  8794. // timeout. Those first bytes have to arrive anyway: run the response through
  8795. // a compressor and zlib holds them until its window fills, so the read would
  8796. // come back empty instead.
  8797. char buf[256];
  8798. auto n = handle.read(buf, sizeof(buf));
  8799. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8800. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8801. }
  8802. #endif
  8803. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8804. TEST_F(ServerTest, Brotli) {
  8805. Headers headers;
  8806. headers.emplace("Accept-Encoding", "br");
  8807. auto res = cli_.Get("/compress", headers);
  8808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8809. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8810. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8811. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8812. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8813. "7890123456789012345678901234567890",
  8814. res->body);
  8815. EXPECT_EQ(StatusCode::OK_200, res->status);
  8816. }
  8817. #endif
  8818. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8819. TEST_F(ServerTest, Zstd) {
  8820. Headers headers;
  8821. headers.emplace("Accept-Encoding", "zstd");
  8822. auto res = cli_.Get("/compress", headers);
  8823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8824. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8826. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8827. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8828. "7890123456789012345678901234567890",
  8829. res->body);
  8830. EXPECT_EQ(StatusCode::OK_200, res->status);
  8831. }
  8832. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8833. Headers headers;
  8834. headers.emplace("Accept-Encoding", "");
  8835. auto res = cli_.Get("/compress", headers);
  8836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8837. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8838. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8839. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8840. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8841. "7890123456789012345678901234567890",
  8842. res->body);
  8843. EXPECT_EQ(StatusCode::OK_200, res->status);
  8844. }
  8845. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8846. Headers headers;
  8847. headers.emplace("Accept-Encoding", "zstd");
  8848. std::string body;
  8849. auto res =
  8850. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8851. EXPECT_EQ(100U, data_length);
  8852. body.append(data, data_length);
  8853. return true;
  8854. });
  8855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8856. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8857. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8858. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8859. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8860. "7890123456789012345678901234567890",
  8861. body);
  8862. EXPECT_EQ(StatusCode::OK_200, res->status);
  8863. }
  8864. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8865. Headers headers;
  8866. headers.emplace("Accept-Encoding", "zstd");
  8867. cli_.set_decompress(false);
  8868. auto res = cli_.Get("/compress", headers);
  8869. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8870. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8871. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8872. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8874. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8875. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8876. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8877. EXPECT_EQ(StatusCode::OK_200, res->status);
  8878. ASSERT_EQ(26U, res->body.size());
  8879. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8880. 0);
  8881. }
  8882. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8883. Headers headers;
  8884. headers.emplace("Accept-Encoding", "");
  8885. std::string body;
  8886. auto res =
  8887. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8888. EXPECT_EQ(100U, data_length);
  8889. body.append(data, data_length);
  8890. return true;
  8891. });
  8892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8893. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8894. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8895. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8896. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8897. "7890123456789012345678901234567890",
  8898. body);
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(ServerTest, NoZstd) {
  8902. Headers headers;
  8903. headers.emplace("Accept-Encoding", "zstd");
  8904. auto res = cli_.Get("/nocompress", headers);
  8905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8906. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8907. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8908. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8909. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8910. "7890123456789012345678901234567890",
  8911. res->body);
  8912. EXPECT_EQ(StatusCode::OK_200, res->status);
  8913. }
  8914. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8915. Headers headers;
  8916. headers.emplace("Accept-Encoding", "zstd");
  8917. std::string body;
  8918. auto res = cli_.Get("/nocompress", headers,
  8919. [&](const char *data, size_t data_length) {
  8920. EXPECT_EQ(100U, data_length);
  8921. body.append(data, data_length);
  8922. return true;
  8923. });
  8924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8925. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8926. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8927. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8928. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8929. "7890123456789012345678901234567890",
  8930. body);
  8931. EXPECT_EQ(StatusCode::OK_200, res->status);
  8932. }
  8933. // TODO: How to enable zstd ??
  8934. TEST_F(ServerTest, MultipartFormDataZstd) {
  8935. UploadFormDataItems items = {
  8936. {"key1", "test", "", ""},
  8937. {"key2", "--abcdefg123", "", ""},
  8938. };
  8939. Headers headers;
  8940. headers.emplace("Accept-Encoding", "zstd");
  8941. cli_.set_compress(true);
  8942. auto res = cli_.Post("/compress-multipart", headers, items);
  8943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8944. EXPECT_EQ(StatusCode::OK_200, res->status);
  8945. }
  8946. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8947. Headers headers;
  8948. headers.emplace("Accept-Encoding", "zstd");
  8949. cli_.set_compress(true);
  8950. auto res = cli_.Put(
  8951. "/put", headers, 3,
  8952. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8953. sink.os << "PUT";
  8954. return true;
  8955. },
  8956. "text/plain");
  8957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8958. EXPECT_EQ(StatusCode::OK_200, res->status);
  8959. EXPECT_EQ("PUT", res->body);
  8960. }
  8961. // Pre-compression logging tests
  8962. TEST_F(ServerTest, PreCompressionLogging) {
  8963. // Test data for compression (matches the actual /compress endpoint content)
  8964. const std::string test_content =
  8965. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8966. "3456789012345678901234567890";
  8967. // Variables to capture logging data
  8968. std::string pre_compression_body;
  8969. std::string pre_compression_content_type;
  8970. std::string pre_compression_content_encoding;
  8971. std::string post_compression_body;
  8972. std::string post_compression_content_type;
  8973. std::string post_compression_content_encoding;
  8974. // Set up pre-compression logger
  8975. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8976. const Response &res) {
  8977. pre_compression_body = res.body;
  8978. pre_compression_content_type = res.get_header_value("Content-Type");
  8979. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8980. });
  8981. // Set up post-compression logger
  8982. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8983. post_compression_body = res.body;
  8984. post_compression_content_type = res.get_header_value("Content-Type");
  8985. post_compression_content_encoding =
  8986. res.get_header_value("Content-Encoding");
  8987. });
  8988. // Test with gzip compression
  8989. Headers headers;
  8990. headers.emplace("Accept-Encoding", "gzip");
  8991. auto res = cli_.Get("/compress", headers);
  8992. // Verify response was compressed
  8993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8994. EXPECT_EQ(StatusCode::OK_200, res->status);
  8995. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8996. // Verify pre-compression logger captured uncompressed content
  8997. EXPECT_EQ(test_content, pre_compression_body);
  8998. EXPECT_EQ("text/plain", pre_compression_content_type);
  8999. EXPECT_TRUE(pre_compression_content_encoding
  9000. .empty()); // No encoding header before compression
  9001. // Verify post-compression logger captured compressed content
  9002. EXPECT_NE(test_content,
  9003. post_compression_body); // Should be different after compression
  9004. EXPECT_EQ("text/plain", post_compression_content_type);
  9005. EXPECT_EQ("gzip", post_compression_content_encoding);
  9006. // Verify compressed content is smaller
  9007. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9008. }
  9009. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9010. const std::string test_content =
  9011. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9012. "3456789012345678901234567890";
  9013. std::string pre_compression_body;
  9014. std::string post_compression_body;
  9015. svr_.set_pre_compression_logger(
  9016. [&](const Request & /*req*/, const Response &res) {
  9017. pre_compression_body = res.body;
  9018. });
  9019. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9020. post_compression_body = res.body;
  9021. });
  9022. Headers headers;
  9023. headers.emplace("Accept-Encoding", "br");
  9024. auto res = cli_.Get("/compress", headers);
  9025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9026. EXPECT_EQ(StatusCode::OK_200, res->status);
  9027. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9028. // Verify pre-compression content is uncompressed
  9029. EXPECT_EQ(test_content, pre_compression_body);
  9030. // Verify post-compression content is compressed
  9031. EXPECT_NE(test_content, post_compression_body);
  9032. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9033. }
  9034. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9035. const std::string test_content =
  9036. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9037. "3456789012345678901234567890";
  9038. std::string pre_compression_body;
  9039. std::string post_compression_body;
  9040. svr_.set_pre_compression_logger(
  9041. [&](const Request & /*req*/, const Response &res) {
  9042. pre_compression_body = res.body;
  9043. });
  9044. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9045. post_compression_body = res.body;
  9046. });
  9047. // Request without compression (use /nocompress endpoint)
  9048. Headers headers;
  9049. auto res = cli_.Get("/nocompress", headers);
  9050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9051. EXPECT_EQ(StatusCode::OK_200, res->status);
  9052. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9053. // Pre-compression logger should not be called when no compression is applied
  9054. EXPECT_TRUE(
  9055. pre_compression_body.empty()); // Pre-compression logger not called
  9056. EXPECT_EQ(
  9057. test_content,
  9058. post_compression_body); // Post-compression logger captures final content
  9059. }
  9060. TEST_F(ServerTest, LoggerSeesContentLength) {
  9061. size_t logged_content_length = 0;
  9062. std::string logged_content_length_header;
  9063. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9064. logged_content_length = res.content_length_;
  9065. logged_content_length_header = res.get_header_value("Content-Length");
  9066. });
  9067. auto res = cli_.Get("/nocompress");
  9068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9069. EXPECT_EQ(StatusCode::OK_200, res->status);
  9070. EXPECT_EQ(res->body.size(), logged_content_length);
  9071. EXPECT_EQ(std::to_string(logged_content_length),
  9072. logged_content_length_header);
  9073. }
  9074. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9075. const std::string test_content =
  9076. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9077. "3456789012345678901234567890";
  9078. std::string pre_compression_body;
  9079. bool pre_logger_called = false;
  9080. // Set only pre-compression logger
  9081. svr_.set_pre_compression_logger(
  9082. [&](const Request & /*req*/, const Response &res) {
  9083. pre_compression_body = res.body;
  9084. pre_logger_called = true;
  9085. });
  9086. Headers headers;
  9087. headers.emplace("Accept-Encoding", "gzip");
  9088. auto res = cli_.Get("/compress", headers);
  9089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9090. EXPECT_EQ(StatusCode::OK_200, res->status);
  9091. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9092. // Verify pre-compression logger was called
  9093. EXPECT_TRUE(pre_logger_called);
  9094. EXPECT_EQ(test_content, pre_compression_body);
  9095. }
  9096. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9097. {
  9098. // Test with Expect: 100-continue header - success case
  9099. // Server returns 100 Continue, client sends body, server returns 200 OK
  9100. Request req;
  9101. req.method = "POST";
  9102. req.path = "/post-large";
  9103. req.set_header("Expect", "100-continue");
  9104. req.body = LARGE_DATA;
  9105. Response res;
  9106. auto error = Error::Success;
  9107. cli_.set_keep_alive(true);
  9108. auto ret = cli_.send(req, res, error);
  9109. EXPECT_TRUE(ret);
  9110. EXPECT_EQ(StatusCode::OK_200, res.status);
  9111. EXPECT_EQ(LARGE_DATA, res.body);
  9112. }
  9113. {
  9114. // Test with Expect: 100-continue header - error case
  9115. // Client should not send the body when server returns an error
  9116. Request req;
  9117. req.method = "POST";
  9118. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9119. req.set_header("Expect", "100-continue");
  9120. req.body = LARGE_DATA;
  9121. Response res;
  9122. auto error = Error::Success;
  9123. auto start = std::chrono::high_resolution_clock::now();
  9124. cli_.set_keep_alive(true);
  9125. auto ret = cli_.send(req, res, error);
  9126. auto end = std::chrono::high_resolution_clock::now();
  9127. auto elapsed =
  9128. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9129. .count();
  9130. // With Expect: 100-continue, request completes successfully but with error
  9131. EXPECT_TRUE(ret);
  9132. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9133. EXPECT_EQ("close", res.get_header_value("Connection"));
  9134. EXPECT_FALSE(cli_.is_socket_open());
  9135. EXPECT_LE(elapsed, 2000);
  9136. }
  9137. {
  9138. // Send an extra GET request to ensure error recovery without hanging
  9139. Request req;
  9140. req.method = "GET";
  9141. req.path = "/hi";
  9142. auto start = std::chrono::high_resolution_clock::now();
  9143. auto res = cli_.send(req);
  9144. auto end = std::chrono::high_resolution_clock::now();
  9145. auto elapsed =
  9146. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9147. .count();
  9148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9149. EXPECT_EQ(StatusCode::OK_200, res->status);
  9150. EXPECT_EQ("Hello World!", res->body);
  9151. EXPECT_LE(elapsed, 500);
  9152. }
  9153. }
  9154. TEST(ZstdDecompressor, ChunkedDecompression) {
  9155. std::string data;
  9156. for (size_t i = 0; i < 32 * 1024; ++i) {
  9157. data.push_back(static_cast<char>('a' + i % 26));
  9158. }
  9159. std::string compressed_data;
  9160. {
  9161. httplib::detail::zstd_compressor compressor;
  9162. bool result = compressor.compress(
  9163. data.data(), data.size(),
  9164. /*last=*/true,
  9165. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9166. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9167. compressed_data_size);
  9168. return true;
  9169. });
  9170. ASSERT_TRUE(result);
  9171. }
  9172. std::string decompressed_data;
  9173. {
  9174. httplib::detail::zstd_decompressor decompressor;
  9175. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9176. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9177. size_t chunk_size = 130;
  9178. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9179. chunk_begin += chunk_size) {
  9180. size_t current_chunk_size =
  9181. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9182. bool result = decompressor.decompress(
  9183. compressed_data.data() + chunk_begin, current_chunk_size,
  9184. [&](const char *decompressed_data_chunk,
  9185. size_t decompressed_data_chunk_size) {
  9186. decompressed_data.insert(decompressed_data.size(),
  9187. decompressed_data_chunk,
  9188. decompressed_data_chunk_size);
  9189. return true;
  9190. });
  9191. ASSERT_TRUE(result);
  9192. }
  9193. }
  9194. ASSERT_EQ(data, decompressed_data);
  9195. }
  9196. TEST(ZstdDecompressor, Decompress) {
  9197. std::string original_text = "Compressed with ZSTD";
  9198. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9199. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9200. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9201. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9202. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9203. std::string decompressed_data;
  9204. {
  9205. httplib::detail::zstd_decompressor decompressor;
  9206. bool result = decompressor.decompress(
  9207. compressed_data.data(), compressed_data.size(),
  9208. [&](const char *decompressed_data_chunk,
  9209. size_t decompressed_data_chunk_size) {
  9210. decompressed_data.insert(decompressed_data.size(),
  9211. decompressed_data_chunk,
  9212. decompressed_data_chunk_size);
  9213. return true;
  9214. });
  9215. ASSERT_TRUE(result);
  9216. }
  9217. ASSERT_EQ(original_text, decompressed_data);
  9218. }
  9219. #endif
  9220. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9221. // separate chunks so that the server sees each part in its own read(). Used to
  9222. // place a read boundary at a specific offset of a request body.
  9223. static bool send_request_in_parts(time_t read_timeout_sec,
  9224. const std::vector<std::string> &parts,
  9225. std::string *resp = nullptr,
  9226. int port = PORT) {
  9227. auto error = Error::Success;
  9228. auto client_sock = detail::create_client_socket(
  9229. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9230. /*connection_timeout_sec=*/5, 0,
  9231. /*read_timeout_sec=*/5, 0,
  9232. /*write_timeout_sec=*/5, 0, std::string(), error);
  9233. if (client_sock == INVALID_SOCKET) { return false; }
  9234. auto ret = detail::process_client_socket(
  9235. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9236. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9237. for (size_t i = 0; i < parts.size(); i++) {
  9238. const auto &part = parts[i];
  9239. if (part.size() !=
  9240. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9241. return false;
  9242. }
  9243. if (i + 1 < parts.size()) {
  9244. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9245. }
  9246. }
  9247. char buf[512];
  9248. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9249. while (line_reader.getline()) {
  9250. if (resp) { *resp += line_reader.ptr(); }
  9251. }
  9252. return true;
  9253. });
  9254. detail::close_socket(client_sock);
  9255. return ret;
  9256. }
  9257. // Sends a raw request to a server listening at HOST:PORT.
  9258. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9259. std::string *resp = nullptr, int port = PORT) {
  9260. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9261. }
  9262. #ifdef CPPHTTPLIB_SSL_ENABLED
  9263. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9265. ASSERT_TRUE(svr.is_valid());
  9266. svr.set_read_timeout(1, 0);
  9267. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9268. auto se = detail::scope_exit([&] {
  9269. svr.stop();
  9270. t.join();
  9271. ASSERT_FALSE(svr.is_running());
  9272. });
  9273. svr.wait_until_ready();
  9274. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9275. // keeps each wait well within the read timeout. The server gives up a
  9276. // second in, so the bytes sent after that fail.
  9277. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9278. parts.resize(26, std::string(1, '\0'));
  9279. EXPECT_FALSE(send_request_in_parts(5, parts));
  9280. }
  9281. #endif
  9282. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9283. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9284. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9285. const std::vector<std::string> &parts,
  9286. std::string *resp = nullptr,
  9287. int port = PORT) {
  9288. auto error = Error::Success;
  9289. auto sock = detail::create_client_socket(
  9290. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9291. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9292. /*write_timeout_sec=*/5, 0, std::string(), error);
  9293. if (sock == INVALID_SOCKET) { return false; }
  9294. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9295. auto ctx = SSL_CTX_new(TLS_client_method());
  9296. auto ssl = SSL_new(ctx);
  9297. auto ssl_se = detail::scope_exit([&] {
  9298. SSL_free(ssl);
  9299. SSL_CTX_free(ctx);
  9300. });
  9301. SSL_set_fd(ssl, static_cast<int>(sock));
  9302. if (SSL_connect(ssl) != 1) { return false; }
  9303. for (size_t i = 0; i < parts.size(); i++) {
  9304. const auto &part = parts[i];
  9305. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9306. static_cast<int>(part.size())) {
  9307. return false;
  9308. }
  9309. if (i + 1 < parts.size()) {
  9310. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9311. }
  9312. }
  9313. char buf[512];
  9314. int n;
  9315. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9316. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9317. }
  9318. return true;
  9319. }
  9320. #endif
  9321. // The request line, then a header value a byte at a time.
  9322. static std::vector<std::string> slow_request_head_parts() {
  9323. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9324. parts.resize(26, "a");
  9325. parts.emplace_back("\r\n\r\n");
  9326. return parts;
  9327. }
  9328. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9329. // within the one-second read timeout. The server gives up a second in, before
  9330. // the head is complete.
  9331. static void
  9332. expect_slow_request_head_dropped(Server &svr,
  9333. const std::function<std::string()> &send) {
  9334. std::atomic<bool> handled(false);
  9335. svr.Get("/", [&](const Request &, Response &res) {
  9336. handled = true;
  9337. res.set_content("ok", "text/plain");
  9338. });
  9339. svr.set_read_timeout(1, 0);
  9340. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9341. auto se = detail::scope_exit([&] {
  9342. svr.stop();
  9343. t.join();
  9344. ASSERT_FALSE(svr.is_running());
  9345. });
  9346. svr.wait_until_ready();
  9347. auto resp = send();
  9348. EXPECT_FALSE(handled);
  9349. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9350. }
  9351. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9352. Server svr;
  9353. expect_slow_request_head_dropped(svr, [] {
  9354. std::string resp;
  9355. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9356. return resp;
  9357. });
  9358. }
  9359. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9360. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9362. ASSERT_TRUE(svr.is_valid());
  9363. expect_slow_request_head_dropped(svr, [] {
  9364. std::string resp;
  9365. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9366. return resp;
  9367. });
  9368. }
  9369. #endif
  9370. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9371. Server svr;
  9372. std::string header_value;
  9373. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9374. header_value = req.get_header_value("foo");
  9375. res.set_content("ok", "text/plain");
  9376. });
  9377. thread t = thread([&] { svr.listen(HOST, PORT); });
  9378. auto se = detail::scope_exit([&] {
  9379. svr.stop();
  9380. t.join();
  9381. ASSERT_FALSE(svr.is_running());
  9382. });
  9383. svr.wait_until_ready();
  9384. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9385. // like characters are not treated the same - use vertical tab and escape.
  9386. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9387. "foo: \t \v bar \x1B\t \r\n"
  9388. "Connection: close\r\n"
  9389. "\r\n";
  9390. std::string res;
  9391. ASSERT_TRUE(send_request(5, req, &res));
  9392. EXPECT_EQ(header_value, "");
  9393. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9394. }
  9395. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9396. Server svr;
  9397. std::string received;
  9398. svr.Get("/order", [&](const Request &req, Response &res) {
  9399. received = entries_to_string(req.headers);
  9400. res.set_content("ok", "text/plain");
  9401. });
  9402. auto port = svr.bind_to_any_port(HOST);
  9403. thread t = thread([&] { svr.listen_after_bind(); });
  9404. auto se = detail::scope_exit([&] {
  9405. svr.stop();
  9406. t.join();
  9407. ASSERT_FALSE(svr.is_running());
  9408. });
  9409. svr.wait_until_ready();
  9410. const std::string req = "GET /order HTTP/1.1\r\n"
  9411. "Host: localhost\r\n"
  9412. "X-First: 1\r\n"
  9413. "X-Dup: a\r\n"
  9414. "X-Second: 2\r\n"
  9415. "X-Dup: b\r\n"
  9416. "Connection: close\r\n"
  9417. "\r\n";
  9418. std::string res;
  9419. ASSERT_TRUE(send_request(5, req, &res, port));
  9420. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9421. EXPECT_EQ(
  9422. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9423. received);
  9424. }
  9425. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9426. Server svr;
  9427. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9428. res.set_header("Set-Cookie", "first=1");
  9429. res.set_header("X-Between", "y");
  9430. res.set_header("Set-Cookie", "second=2");
  9431. res.set_content("ok", "text/plain");
  9432. });
  9433. auto port = svr.bind_to_any_port(HOST);
  9434. thread t = thread([&] { svr.listen_after_bind(); });
  9435. auto se = detail::scope_exit([&] {
  9436. svr.stop();
  9437. t.join();
  9438. ASSERT_FALSE(svr.is_running());
  9439. });
  9440. svr.wait_until_ready();
  9441. Client cli(HOST, port);
  9442. auto res = cli.Get("/cookies");
  9443. ASSERT_TRUE(res);
  9444. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9445. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9446. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9447. }
  9448. // A stream may send a byte at a time with a small extension on each chunk,
  9449. // however long it runs
  9450. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9451. Server svr;
  9452. svr.Post("/count", [](const Request &req, Response &res) {
  9453. res.set_content(std::to_string(req.body.size()), "text/plain");
  9454. });
  9455. auto port = svr.bind_to_any_port(HOST);
  9456. ASSERT_LT(0, port);
  9457. thread t = thread([&] { svr.listen_after_bind(); });
  9458. auto se = detail::scope_exit([&] {
  9459. svr.stop();
  9460. t.join();
  9461. ASSERT_FALSE(svr.is_running());
  9462. });
  9463. svr.wait_until_ready();
  9464. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9465. "\r\nTransfer-Encoding: chunked\r\n"
  9466. "Connection: close\r\n\r\n";
  9467. for (auto i = 0; i < 4096; i++) {
  9468. req += "1;a=b\r\nx\r\n";
  9469. }
  9470. req += "0\r\n\r\n";
  9471. std::string res;
  9472. ASSERT_TRUE(send_request(5, req, &res, port));
  9473. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9474. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9475. }
  9476. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9477. Server svr;
  9478. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9479. auto i = new int(0);
  9480. res.set_header("Trailer", "X-Safe, X-Reflected");
  9481. res.set_chunked_content_provider(
  9482. "text/plain",
  9483. [i](size_t /*offset*/, DataSink &sink) {
  9484. if (*i == 0) {
  9485. sink.os << "body";
  9486. } else {
  9487. Headers trailer;
  9488. // A valid trailer that must survive.
  9489. trailer.emplace("X-Safe", "safe");
  9490. // Attacker-controlled value carrying CR/LF (response splitting).
  9491. trailer.emplace("X-Reflected",
  9492. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9493. // Attacker-controlled name carrying CR/LF.
  9494. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9495. sink.done_with_trailer(trailer);
  9496. }
  9497. (*i)++;
  9498. return true;
  9499. },
  9500. [i](bool /*success*/) { delete i; });
  9501. });
  9502. thread t = thread([&] { svr.listen(HOST, PORT); });
  9503. auto se = detail::scope_exit([&] {
  9504. svr.stop();
  9505. t.join();
  9506. ASSERT_FALSE(svr.is_running());
  9507. });
  9508. svr.wait_until_ready();
  9509. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9510. "Host: " + HOST +
  9511. "\r\n"
  9512. "Connection: close\r\n"
  9513. "\r\n";
  9514. std::string res;
  9515. ASSERT_TRUE(send_request(5, req, &res));
  9516. // The injected fields must not appear anywhere in the raw response.
  9517. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9518. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9519. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9520. // Invalid trailers are dropped entirely, matching set_header().
  9521. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9522. // The valid trailer still passes through.
  9523. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9524. }
  9525. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9526. // A custom header writer gets only the fields the default one writes
  9527. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9528. std::string s;
  9529. for (const auto &h : hdrs) {
  9530. s += h.first + ": " + h.second + "\r\n";
  9531. }
  9532. s += "\r\n";
  9533. return strm.write(s.data(), s.size());
  9534. };
  9535. for (auto custom_writer : {false, true}) {
  9536. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9537. Server svr;
  9538. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9539. svr.set_post_routing_handler([](const Request &, Response &res) {
  9540. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9541. });
  9542. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9543. // res.headers is a public field an application can populate directly,
  9544. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9545. // A valid header that must survive.
  9546. res.headers.emplace("X-Safe", "safe");
  9547. // Attacker-controlled value carrying CR/LF (response splitting).
  9548. res.headers.emplace("X-Reflected",
  9549. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9550. // Attacker-controlled name carrying CR/LF.
  9551. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9552. res.set_content("body", "text/plain");
  9553. });
  9554. thread t = thread([&] { svr.listen(HOST, PORT); });
  9555. auto se = detail::scope_exit([&] {
  9556. svr.stop();
  9557. t.join();
  9558. ASSERT_FALSE(svr.is_running());
  9559. });
  9560. svr.wait_until_ready();
  9561. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9562. "Host: " + HOST +
  9563. "\r\n"
  9564. "Connection: close\r\n"
  9565. "\r\n";
  9566. std::string res;
  9567. ASSERT_TRUE(send_request(5, req, &res));
  9568. // The injected fields must not appear anywhere in the raw response.
  9569. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9570. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9571. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9572. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9573. // Invalid headers are dropped entirely, matching set_header().
  9574. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9575. // The valid header still passes through.
  9576. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9577. }
  9578. }
  9579. // Forward declaration: in split builds split.py strips `inline` and moves the
  9580. // definition into httplib.cc, so detail::write_request_line is not visible from
  9581. // the public httplib.h. Re-declaring it here lets the tests link against the
  9582. // symbol in both header-only and split builds.
  9583. namespace httplib {
  9584. namespace detail {
  9585. ssize_t write_request_line(Stream &strm, const std::string &method,
  9586. const std::string &path);
  9587. } // namespace detail
  9588. } // namespace httplib
  9589. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9590. // A well-formed target is written verbatim.
  9591. {
  9592. detail::BufferStream strm;
  9593. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9594. EXPECT_GT(n, 0);
  9595. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9596. }
  9597. // A target carrying CR/LF, SP or other control octets must be rejected
  9598. // before anything reaches the wire, otherwise it splits the request line and
  9599. // injects a header or a whole request.
  9600. const std::string evil_targets[] = {
  9601. "/a\r\nInjected: pwned",
  9602. "/a\rInjected",
  9603. "/a\nInjected",
  9604. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9605. "/a b",
  9606. "/a\tb",
  9607. "/a\x7f",
  9608. };
  9609. for (const auto &evil : evil_targets) {
  9610. detail::BufferStream strm;
  9611. auto n = detail::write_request_line(strm, "GET", evil);
  9612. EXPECT_LT(n, 0);
  9613. EXPECT_TRUE(strm.get_buffer().empty());
  9614. }
  9615. }
  9616. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9617. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9618. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9619. // target reaches write_request. The client must fail cleanly with
  9620. // Error::Write instead of putting a request-line-less, header-injecting
  9621. // request on the wire.
  9622. Server svr;
  9623. svr.Get("/a", [](const Request &, Response &res) {
  9624. res.set_content("ok", "text/plain");
  9625. });
  9626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9627. auto se = detail::scope_exit([&] {
  9628. svr.stop();
  9629. thread.join();
  9630. ASSERT_FALSE(svr.is_running());
  9631. });
  9632. svr.wait_until_ready();
  9633. {
  9634. Client cli(HOST, PORT);
  9635. cli.set_path_encode(false);
  9636. // The request is rejected before anything is written, so the connection
  9637. // stays silent and the subsequent response read would otherwise block for
  9638. // the full default read timeout. Shorten it -- the assertion is on the
  9639. // error, not the timeout.
  9640. cli.set_read_timeout(1, 0);
  9641. auto res = cli.Get("/a\r\nInjected: pwned");
  9642. EXPECT_FALSE(res);
  9643. EXPECT_EQ(Error::Write, res.error());
  9644. }
  9645. }
  9646. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9647. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9648. // including extension methods.
  9649. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9650. for (const auto &method : good_methods) {
  9651. detail::BufferStream strm;
  9652. auto n = detail::write_request_line(strm, method, "/");
  9653. EXPECT_GT(n, 0);
  9654. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9655. }
  9656. // A method carrying CR/LF would split the request line and smuggle a whole
  9657. // request ahead of the real one. A space or an empty method corrupts the
  9658. // request line. All must be rejected before anything reaches the wire.
  9659. const std::string evil_methods[] = {
  9660. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9661. "GET\r\nInjected: pwned",
  9662. "GET\r",
  9663. "GET\n",
  9664. "GE T",
  9665. "",
  9666. };
  9667. for (const auto &evil : evil_methods) {
  9668. detail::BufferStream strm;
  9669. auto n = detail::write_request_line(strm, evil, "/");
  9670. EXPECT_LT(n, 0);
  9671. EXPECT_TRUE(strm.get_buffer().empty());
  9672. }
  9673. }
  9674. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9675. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9676. // through Client::send must fail with Error::Write and no request, neither
  9677. // the smuggled one nor the real one, may reach the server.
  9678. Server svr;
  9679. std::atomic<int> request_count(0);
  9680. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9681. request_count++;
  9682. res.status = StatusCode::OK_200;
  9683. return Server::HandlerResponse::Handled;
  9684. });
  9685. auto port = svr.bind_to_any_port(HOST);
  9686. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9687. auto se = detail::scope_exit([&] {
  9688. svr.stop();
  9689. thread.join();
  9690. ASSERT_FALSE(svr.is_running());
  9691. });
  9692. svr.wait_until_ready();
  9693. {
  9694. Client cli(HOST, port);
  9695. const std::string evil_methods[] = {
  9696. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9697. "GE T",
  9698. "",
  9699. };
  9700. for (const auto &evil : evil_methods) {
  9701. Request req;
  9702. req.method = evil;
  9703. req.path = "/";
  9704. auto res = cli.send(req);
  9705. EXPECT_FALSE(res);
  9706. EXPECT_EQ(Error::Write, res.error());
  9707. }
  9708. auto handle =
  9709. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9710. EXPECT_FALSE(handle.is_valid());
  9711. EXPECT_EQ(Error::Write, handle.error);
  9712. // A valid request on the same client still goes through.
  9713. auto res = cli.Get("/");
  9714. ASSERT_TRUE(res);
  9715. EXPECT_EQ(StatusCode::OK_200, res->status);
  9716. }
  9717. EXPECT_EQ(1, request_count.load());
  9718. }
  9719. // Sends a raw request and verifies that there isn't a crash or exception.
  9720. static void test_raw_request(const std::string &req,
  9721. std::string *out = nullptr) {
  9722. Server svr;
  9723. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9724. res.set_content("ok", "text/plain");
  9725. });
  9726. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9727. res.set_content("ok", "text/plain");
  9728. });
  9729. svr.Get("/header_field_value_check",
  9730. [&](const Request & /*req*/, Response &res) {
  9731. res.set_content("ok", "text/plain");
  9732. });
  9733. svr.CustomRoute("PROPFIND", "/dav",
  9734. [&](const Request & /*req*/, Response &res) {
  9735. res.status = StatusCode::MultiStatus_207;
  9736. });
  9737. // Server read timeout must be longer than the client read timeout for the
  9738. // bug to reproduce, probably to force the server to process a request
  9739. // without a trailing blank line.
  9740. const time_t client_read_timeout_sec = 1;
  9741. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9742. bool listen_thread_ok = false;
  9743. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9744. auto se = detail::scope_exit([&] {
  9745. svr.stop();
  9746. t.join();
  9747. ASSERT_FALSE(svr.is_running());
  9748. EXPECT_TRUE(listen_thread_ok);
  9749. });
  9750. svr.wait_until_ready();
  9751. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9752. }
  9753. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9754. // A certain header line causes an exception if the header property is parsed
  9755. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9756. test_raw_request(
  9757. "GET /hi HTTP/1.1\r\n"
  9758. " : "
  9759. " "
  9760. " ");
  9761. }
  9762. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9763. // A certain header line causes an exception if the header property *name* is
  9764. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9765. // greedy matcher and requires backtracking when there are a lot of ":"
  9766. // characters.
  9767. // This occurs with libc++ but not libstdc++.
  9768. test_raw_request(
  9769. "GET /hi HTTP/1.1\r\n"
  9770. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9771. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9772. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9773. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9774. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9775. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9776. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9777. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9778. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9779. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9780. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9781. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9782. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9783. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9784. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9785. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9786. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9787. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9788. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9789. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9790. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9791. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9792. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9793. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9794. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9795. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9796. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9797. "&&&%%%");
  9798. }
  9799. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9800. // Make sure this doesn't crash the server.
  9801. // In a previous version of the header line regex, the "\r" rendered the line
  9802. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9803. // a new position where the leading white space ended and the field value
  9804. // began.
  9805. // The crash occurs with libc++ but not libstdc++.
  9806. test_raw_request("GET /hi HTTP/1.1\r\n"
  9807. "a:" +
  9808. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9809. "\r\n"
  9810. "\r\n");
  9811. }
  9812. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9813. const char *rejected[] = {
  9814. // RFC 9112 §3: one SP between the parts, and nothing else
  9815. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9816. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9817. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9818. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9819. // A request-target has no fragment
  9820. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9821. // An HTTP/1.1 request needs a Host
  9822. "GET /hi HTTP/1.1\r\n\r\n",
  9823. };
  9824. for (auto request : rejected) {
  9825. std::string out;
  9826. test_raw_request(request, &out);
  9827. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9828. }
  9829. std::string out;
  9830. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9831. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9832. }
  9833. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9834. // RFC 9112 §6.1
  9835. const char *requests[] = {
  9836. "PUT /put_hi HTTP/1.1\r\n"
  9837. "Host: localhost\r\n"
  9838. "Content-Length: 0\r\n"
  9839. "Transfer-Encoding: chunked\r\n"
  9840. "\r\n"
  9841. "0\r\n\r\n",
  9842. "PUT /put_hi HTTP/1.0\r\n"
  9843. "Connection: keep-alive\r\n"
  9844. "Transfer-Encoding: chunked\r\n"
  9845. "\r\n"
  9846. "0\r\n\r\n",
  9847. };
  9848. for (auto request : requests) {
  9849. std::string out;
  9850. test_raw_request(request, &out);
  9851. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9852. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9853. }
  9854. }
  9855. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9856. std::string out;
  9857. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9858. "Content-Type: text/plain\r\n"
  9859. "Transfer-Encoding: chunked\r\n"
  9860. "\r\n"
  9861. "nothex\r\n",
  9862. &out);
  9863. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9864. }
  9865. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9866. std::string out;
  9867. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9868. "Content-Type: text/plain\r\n"
  9869. "Transfer-Encoding: chunked\r\n"
  9870. "\r\n"
  9871. "3\r\n"
  9872. "xyz\r\n"
  9873. "NaN\r\n",
  9874. &out);
  9875. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9876. }
  9877. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9878. std::string out;
  9879. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9880. "Content-Type: text/plain\r\n"
  9881. "Transfer-Encoding: chunked\r\n"
  9882. "\r\n"
  9883. // Length is too large for 64 bits.
  9884. "1ffffffffffffffff\r\n"
  9885. "xyz\r\n",
  9886. &out);
  9887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9888. }
  9889. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9890. test_raw_request("GET /hi HTTP/1.1\r\n"
  9891. "Content-Type: text/plain\r\n\r");
  9892. }
  9893. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9894. std::string out;
  9895. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9896. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9897. }
  9898. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9899. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9900. std::string out;
  9901. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9902. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9903. }
  9904. }
  9905. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9906. std::string out;
  9907. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9908. "Host: localhost\r\n"
  9909. "Connection: close\r\n\r\n",
  9910. &out);
  9911. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9912. }
  9913. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9914. Server svr;
  9915. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9916. EXPECT_TRUE(!req.remote_addr.empty());
  9917. });
  9918. thread t = thread([&] { svr.listen(HOST, PORT); });
  9919. auto se = detail::scope_exit([&] {
  9920. svr.stop();
  9921. t.join();
  9922. ASSERT_FALSE(svr.is_running());
  9923. });
  9924. svr.wait_until_ready();
  9925. // Send an invalid request line to trigger Bad Request
  9926. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9927. std::string out;
  9928. ASSERT_TRUE(send_request(5, bad_req, &out));
  9929. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9930. }
  9931. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9932. // answered right away rather than blocking on a read that waits for EOF.
  9933. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9934. std::string out;
  9935. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9936. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9937. }
  9938. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9939. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9940. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9941. for (const auto *method : methods) {
  9942. Server svr;
  9943. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9944. EXPECT_FALSE(svr.is_valid()) << method;
  9945. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9946. }
  9947. }
  9948. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9949. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9950. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9951. for (const auto *method : methods) {
  9952. Server svr;
  9953. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9954. EXPECT_FALSE(svr.is_valid()) << method;
  9955. }
  9956. }
  9957. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9958. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9959. "COPY", "MOVE", "LOCK",
  9960. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9961. Server svr;
  9962. for (const auto *method : methods) {
  9963. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9964. }
  9965. EXPECT_TRUE(svr.is_valid());
  9966. }
  9967. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9968. Server svr;
  9969. svr.CustomRoute("POST", "/x",
  9970. [](const Request &, Response &, const ContentReader &) {});
  9971. EXPECT_FALSE(svr.is_valid());
  9972. }
  9973. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9974. Server svr;
  9975. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9976. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9977. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9978. EXPECT_FALSE(svr.is_valid());
  9979. }
  9980. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9981. Server svr;
  9982. auto captured = Error::Success;
  9983. svr.set_error_logger(
  9984. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9985. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9986. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9987. }
  9988. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9989. std::string out;
  9990. std::string request(
  9991. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9992. test_raw_request(request, &out);
  9993. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9994. }
  9995. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9996. std::string out;
  9997. std::string request(
  9998. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9999. test_raw_request(request, &out);
  10000. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10001. }
  10002. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10003. std::string out;
  10004. std::string request(
  10005. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10006. test_raw_request(request, &out);
  10007. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10008. }
  10009. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10010. std::string out;
  10011. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10012. "Host: localhost\r\n"
  10013. "Test: \r\n\r\n",
  10014. &out);
  10015. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10016. }
  10017. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10018. Server svr;
  10019. std::string x_custom;
  10020. std::string cookie;
  10021. std::string xff;
  10022. std::string x_unicode;
  10023. std::string x_iis;
  10024. svr.Get("/check", [&](const Request &req, Response &res) {
  10025. x_custom = req.get_header_value("X-Custom");
  10026. cookie = req.get_header_value("Cookie");
  10027. xff = req.get_header_value("X-Forwarded-For");
  10028. x_unicode = req.get_header_value("X-Unicode");
  10029. x_iis = req.get_header_value("X-IIS");
  10030. res.set_content("ok", "text/plain");
  10031. });
  10032. thread t = thread([&] { svr.listen(HOST, PORT); });
  10033. auto se = detail::scope_exit([&] {
  10034. svr.stop();
  10035. t.join();
  10036. ASSERT_FALSE(svr.is_running());
  10037. });
  10038. svr.wait_until_ready();
  10039. const std::string req = "GET /check HTTP/1.1\r\n"
  10040. "Host: localhost\r\n"
  10041. "X-Custom: a%0D%0AInjected: b\r\n"
  10042. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10043. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10044. "X-Unicode: %E3%81%82\r\n"
  10045. "X-IIS: %u00E9\r\n"
  10046. "Connection: close\r\n"
  10047. "\r\n";
  10048. std::string res;
  10049. ASSERT_TRUE(send_request(5, req, &res));
  10050. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10051. // Every value must be returned verbatim (wire form), with no decoding.
  10052. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10053. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10054. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10055. EXPECT_EQ("%E3%81%82", x_unicode);
  10056. EXPECT_EQ("%u00E9", x_iis);
  10057. }
  10058. // Applications that previously relied on automatic percent-decoding can
  10059. // reproduce the old behavior by explicitly calling decode_path_component()
  10060. // or, for RFC 3986 conformance, decode_uri_component().
  10061. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10062. Server svr;
  10063. std::string decoded;
  10064. svr.Get("/check", [&](const Request &req, Response &res) {
  10065. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10066. res.set_content("ok", "text/plain");
  10067. });
  10068. thread t = thread([&] { svr.listen(HOST, PORT); });
  10069. auto se = detail::scope_exit([&] {
  10070. svr.stop();
  10071. t.join();
  10072. ASSERT_FALSE(svr.is_running());
  10073. });
  10074. svr.wait_until_ready();
  10075. const std::string req = "GET /check HTTP/1.1\r\n"
  10076. "Host: localhost\r\n"
  10077. "X-Custom: hello%20world\r\n"
  10078. "Connection: close\r\n"
  10079. "\r\n";
  10080. std::string res;
  10081. ASSERT_TRUE(send_request(5, req, &res));
  10082. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10083. EXPECT_EQ("hello world", decoded);
  10084. }
  10085. // Regression test for #2033. Browsers send Referer values that include
  10086. // percent-encoded characters such as %0A inside the URL. Decoding the
  10087. // header value would either trip the post-decode CR/LF/NUL guard (the
  10088. // original bug, returning 400) or, after that guard was relaxed, silently
  10089. // store a literal LF — both unacceptable. The wire form must round-trip.
  10090. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10091. Server svr;
  10092. std::string referer;
  10093. svr.Get("/check", [&](const Request &req, Response &res) {
  10094. referer = req.get_header_value("Referer");
  10095. res.set_content("ok", "text/plain");
  10096. });
  10097. thread t = thread([&] { svr.listen(HOST, PORT); });
  10098. auto se = detail::scope_exit([&] {
  10099. svr.stop();
  10100. t.join();
  10101. ASSERT_FALSE(svr.is_running());
  10102. });
  10103. svr.wait_until_ready();
  10104. const std::string req = "GET /check HTTP/1.1\r\n"
  10105. "Host: localhost\r\n"
  10106. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10107. "Connection: close\r\n"
  10108. "\r\n";
  10109. std::string res;
  10110. ASSERT_TRUE(send_request(5, req, &res));
  10111. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10112. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10113. }
  10114. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10115. Server svr;
  10116. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10117. res.set_header("Cache-Control", "no-cache");
  10118. res.set_chunked_content_provider(
  10119. "text/event-stream", [](size_t offset, DataSink &sink) {
  10120. std::string s = "data:";
  10121. s += std::to_string(offset);
  10122. s += "\n\n";
  10123. auto ret = sink.write(s.data(), s.size());
  10124. EXPECT_TRUE(ret);
  10125. std::this_thread::sleep_for(std::chrono::seconds(1));
  10126. return true;
  10127. });
  10128. });
  10129. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10130. svr.wait_until_ready();
  10131. Client client(HOST, PORT);
  10132. const Headers headers = {{"Accept", "text/event-stream"}};
  10133. auto get_thread = std::thread([&client, &headers]() {
  10134. auto res = client.Get(
  10135. "/events", headers,
  10136. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10137. });
  10138. auto se = detail::scope_exit([&] {
  10139. svr.stop();
  10140. get_thread.join();
  10141. listen_thread.join();
  10142. ASSERT_FALSE(svr.is_running());
  10143. });
  10144. // Give GET time to get a few messages.
  10145. std::this_thread::sleep_for(std::chrono::seconds(2));
  10146. }
  10147. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10148. httplib::Server svr;
  10149. svr.Post("/hi",
  10150. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10151. res.status = StatusCode::OK_200;
  10152. });
  10153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10154. svr.wait_until_ready();
  10155. Client cli(HOST, PORT);
  10156. auto res = cli.Post("/hi", "data", "text/plain");
  10157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10158. EXPECT_EQ(StatusCode::OK_200, res->status);
  10159. svr.stop();
  10160. thread.join();
  10161. ASSERT_FALSE(svr.is_running());
  10162. res = cli.Post("/hi", "data", "text/plain");
  10163. ASSERT_FALSE(res);
  10164. }
  10165. TEST(ServerStopTest, ListenFailure) {
  10166. Server svr;
  10167. auto t = thread([&]() {
  10168. auto ret = svr.listen("????", PORT);
  10169. EXPECT_FALSE(ret);
  10170. });
  10171. svr.wait_until_ready();
  10172. svr.stop();
  10173. t.join();
  10174. }
  10175. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10176. TEST(ServerStopTest, Decommision) {
  10177. Server svr;
  10178. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10179. for (int i = 0; i < 4; i++) {
  10180. auto is_even = !(i % 2);
  10181. std::thread t{[&] {
  10182. try {
  10183. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10184. if (is_even) {
  10185. throw std::runtime_error("Some thing that happens to go wrong.");
  10186. }
  10187. svr.listen(HOST, PORT);
  10188. } catch (...) { svr.decommission(); }
  10189. }};
  10190. svr.wait_until_ready();
  10191. // Server is up
  10192. {
  10193. Client cli(HOST, PORT);
  10194. auto res = cli.Get("/hi");
  10195. if (is_even) {
  10196. EXPECT_FALSE(res);
  10197. } else {
  10198. EXPECT_TRUE(res);
  10199. EXPECT_EQ("hi...", res->body);
  10200. }
  10201. }
  10202. svr.stop();
  10203. t.join();
  10204. // Server is down...
  10205. {
  10206. Client cli(HOST, PORT);
  10207. auto res = cli.Get("/hi");
  10208. EXPECT_FALSE(res);
  10209. }
  10210. }
  10211. }
  10212. #endif
  10213. // Helper function for string body upload progress tests
  10214. template <typename SetupHandler, typename ClientCall>
  10215. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10216. ClientCall &&client_call,
  10217. const string &body) {
  10218. Server svr;
  10219. setup_handler(svr);
  10220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10221. auto se = detail::scope_exit([&] {
  10222. svr.stop();
  10223. t.join();
  10224. });
  10225. svr.wait_until_ready();
  10226. Client cli(HOST, PORT);
  10227. vector<uint64_t> progress_values;
  10228. bool progress_called = false;
  10229. auto res =
  10230. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10231. progress_values.push_back(current);
  10232. progress_called = true;
  10233. return true;
  10234. });
  10235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10236. EXPECT_EQ(200, res->status);
  10237. EXPECT_TRUE(progress_called);
  10238. }
  10239. TEST(UploadProgressTest, PostStringBodyBasic) {
  10240. TestStringBodyUploadProgress(
  10241. [](Server &svr) {
  10242. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10243. res.set_content("received", "text/plain");
  10244. });
  10245. },
  10246. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10247. return cli.Post("/test", body, "text/plain", progress_callback);
  10248. },
  10249. "test data for upload progress");
  10250. }
  10251. TEST(UploadProgressTest, PutStringBodyBasic) {
  10252. TestStringBodyUploadProgress(
  10253. [](Server &svr) {
  10254. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10255. res.set_content("put received", "text/plain");
  10256. });
  10257. },
  10258. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10259. return cli.Put("/test", body, "text/plain", progress_callback);
  10260. },
  10261. "put test data for upload progress");
  10262. }
  10263. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10264. TestStringBodyUploadProgress(
  10265. [](Server &svr) {
  10266. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10267. res.set_content("patch received", "text/plain");
  10268. });
  10269. },
  10270. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10271. return cli.Patch("/test", body, "text/plain", progress_callback);
  10272. },
  10273. "patch test data for upload progress");
  10274. }
  10275. // Helper function for content provider upload progress tests
  10276. template <typename SetupHandler, typename ClientCall>
  10277. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10278. ClientCall &&client_call) {
  10279. Server svr;
  10280. setup_handler(svr);
  10281. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10282. auto se = detail::scope_exit([&] {
  10283. svr.stop();
  10284. t.join();
  10285. });
  10286. svr.wait_until_ready();
  10287. Client cli(HOST, PORT);
  10288. vector<uint64_t> progress_values;
  10289. auto res =
  10290. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10291. progress_values.push_back(current);
  10292. return true;
  10293. });
  10294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10295. EXPECT_EQ(200, res->status);
  10296. EXPECT_FALSE(progress_values.empty());
  10297. }
  10298. TEST(UploadProgressTest, PostContentProviderProgress) {
  10299. TestContentProviderUploadProgress(
  10300. [](Server &svr) {
  10301. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10302. res.set_content("provider received", "text/plain");
  10303. });
  10304. },
  10305. [](Client &cli, UploadProgress progress_callback) {
  10306. return cli.Post(
  10307. "/test", 9,
  10308. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10309. sink.os << "test data";
  10310. return true;
  10311. },
  10312. "text/plain", progress_callback);
  10313. });
  10314. }
  10315. // Helper function for multipart upload progress tests
  10316. template <typename SetupHandler, typename ClientCall>
  10317. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10318. ClientCall &&client_call,
  10319. const string &endpoint) {
  10320. Server svr;
  10321. setup_handler(svr);
  10322. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10323. auto se = detail::scope_exit([&] {
  10324. svr.stop();
  10325. t.join();
  10326. });
  10327. svr.wait_until_ready();
  10328. Client cli(HOST, PORT);
  10329. vector<uint64_t> progress_values;
  10330. UploadFormDataItems items = {
  10331. {"field1", "value1", "", ""},
  10332. {"field2", "longer value for progress tracking test", "", ""},
  10333. {"file1", "file content data for upload progress", "test.txt",
  10334. "text/plain"}};
  10335. auto res = client_call(cli, endpoint, items,
  10336. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10337. progress_values.push_back(current);
  10338. return true;
  10339. });
  10340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10341. EXPECT_EQ(200, res->status);
  10342. EXPECT_FALSE(progress_values.empty());
  10343. }
  10344. TEST(UploadProgressTest, PostMultipartProgress) {
  10345. TestMultipartUploadProgress(
  10346. [](Server &svr) {
  10347. svr.Post("/multipart", [](const Request &req, Response &res) {
  10348. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10349. res.set_content("multipart received", "text/plain");
  10350. });
  10351. },
  10352. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10353. UploadProgress progress_callback) {
  10354. return cli.Post(endpoint, items, progress_callback);
  10355. },
  10356. "/multipart");
  10357. }
  10358. // Helper function for basic download progress tests
  10359. template <typename SetupHandler, typename ClientCall>
  10360. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10361. ClientCall &&client_call, const string &endpoint,
  10362. size_t expected_content_size) {
  10363. Server svr;
  10364. setup_handler(svr);
  10365. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10366. auto se = detail::scope_exit([&] {
  10367. svr.stop();
  10368. t.join();
  10369. });
  10370. svr.wait_until_ready();
  10371. Client cli(HOST, PORT);
  10372. vector<uint64_t> progress_values;
  10373. auto res = client_call(cli, endpoint,
  10374. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10375. progress_values.push_back(current);
  10376. return true;
  10377. });
  10378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10379. EXPECT_EQ(200, res->status);
  10380. EXPECT_FALSE(progress_values.empty());
  10381. EXPECT_EQ(expected_content_size, res->body.size());
  10382. }
  10383. TEST(DownloadProgressTest, GetBasic) {
  10384. TestBasicDownloadProgress(
  10385. [](Server &svr) {
  10386. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10387. string content(1000, 'D');
  10388. res.set_content(content, "text/plain");
  10389. });
  10390. },
  10391. [](Client &cli, const string &endpoint,
  10392. DownloadProgress progress_callback) {
  10393. return cli.Get(endpoint, progress_callback);
  10394. },
  10395. "/download", 1000u);
  10396. }
  10397. // Helper function for content receiver download progress tests
  10398. template <typename SetupHandler, typename ClientCall>
  10399. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10400. ClientCall &&client_call,
  10401. const string &endpoint,
  10402. size_t expected_content_size) {
  10403. Server svr;
  10404. setup_handler(svr);
  10405. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10406. auto se = detail::scope_exit([&] {
  10407. svr.stop();
  10408. t.join();
  10409. });
  10410. svr.wait_until_ready();
  10411. Client cli(HOST, PORT);
  10412. vector<uint64_t> progress_values;
  10413. string received_body;
  10414. auto res = client_call(
  10415. cli, endpoint,
  10416. [&](const char *data, size_t data_length) -> bool {
  10417. received_body.append(data, data_length);
  10418. return true;
  10419. },
  10420. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10421. progress_values.push_back(current);
  10422. return true;
  10423. });
  10424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10425. EXPECT_EQ(200, res->status);
  10426. EXPECT_FALSE(progress_values.empty());
  10427. EXPECT_EQ(expected_content_size, received_body.size());
  10428. EXPECT_TRUE(res->body.empty());
  10429. }
  10430. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10431. TestContentReceiverDownloadProgress(
  10432. [](Server &svr) {
  10433. svr.Get("/download-receiver",
  10434. [](const Request & /*req*/, Response &res) {
  10435. string content(2000, 'R');
  10436. res.set_content(content, "text/plain");
  10437. });
  10438. },
  10439. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10440. DownloadProgress progress_callback) {
  10441. return cli.Get(endpoint, content_receiver, progress_callback);
  10442. },
  10443. "/download-receiver", 2000u);
  10444. }
  10445. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10446. // A provider reaching a pass with nothing to hand over - an empty buffer
  10447. // popped off a queue, say - must not be taken to mean the body is finished.
  10448. // It used to end the loop with the terminating chunk unwritten while the
  10449. // server still considered the response complete, so the peer waited for an
  10450. // end that never arrived.
  10451. Server svr;
  10452. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10453. auto step = std::make_shared<int>(0);
  10454. res.set_chunked_content_provider("text/plain",
  10455. [step](size_t /*offset*/, DataSink &sink) {
  10456. switch ((*step)++) {
  10457. case 0: sink.write("", 0); break;
  10458. case 1: sink.write("hello", 5); break;
  10459. default: sink.done(); break;
  10460. }
  10461. return true;
  10462. });
  10463. });
  10464. auto port = svr.bind_to_any_port(HOST);
  10465. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10466. auto listen_se = detail::scope_exit([&] {
  10467. svr.stop();
  10468. listen_thread.join();
  10469. ASSERT_FALSE(svr.is_running());
  10470. });
  10471. svr.wait_until_ready();
  10472. Client cli(HOST, port);
  10473. // Without the fix the body is never terminated, so bound the wait rather
  10474. // than letting the test hang on the default read timeout.
  10475. cli.set_read_timeout(5, 0);
  10476. auto res = cli.Get("/stream");
  10477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10478. EXPECT_EQ(StatusCode::OK_200, res->status);
  10479. EXPECT_EQ("hello", res->body);
  10480. }
  10481. TEST(StreamingTest, NoContentLengthStreaming) {
  10482. Server svr;
  10483. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10484. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10485. if (offset < 6) {
  10486. sink.os << (offset < 3 ? "a" : "b");
  10487. } else {
  10488. sink.done();
  10489. }
  10490. return true;
  10491. });
  10492. });
  10493. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10494. auto listen_se = detail::scope_exit([&] {
  10495. svr.stop();
  10496. listen_thread.join();
  10497. ASSERT_FALSE(svr.is_running());
  10498. });
  10499. svr.wait_until_ready();
  10500. Client client(HOST, PORT);
  10501. auto get_thread = std::thread([&client]() {
  10502. std::string s;
  10503. auto res =
  10504. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10505. s += std::string(data, len);
  10506. return true;
  10507. });
  10508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10509. EXPECT_EQ(StatusCode::OK_200, res->status);
  10510. EXPECT_EQ("aaabbb", s);
  10511. });
  10512. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10513. // Give GET time to get a few messages.
  10514. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10515. }
  10516. TEST(MountTest, Unmount) {
  10517. Server svr;
  10518. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10519. auto se = detail::scope_exit([&] {
  10520. svr.stop();
  10521. listen_thread.join();
  10522. ASSERT_FALSE(svr.is_running());
  10523. });
  10524. svr.wait_until_ready();
  10525. Client cli("localhost", PORT);
  10526. svr.set_mount_point("/mount2", "./www2");
  10527. auto res = cli.Get("/");
  10528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10530. res = cli.Get("/mount2/dir/test.html");
  10531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10532. EXPECT_EQ(StatusCode::OK_200, res->status);
  10533. svr.set_mount_point("/", "./www");
  10534. res = cli.Get("/dir/");
  10535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10536. EXPECT_EQ(StatusCode::OK_200, res->status);
  10537. svr.remove_mount_point("/");
  10538. res = cli.Get("/dir/");
  10539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10540. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10541. svr.remove_mount_point("/mount2");
  10542. res = cli.Get("/mount2/dir/test.html");
  10543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10544. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10545. }
  10546. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10547. Server svr;
  10548. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10549. svr.Get("/api/hello", [](const Request &, Response &res) {
  10550. res.set_content("api", "text/plain");
  10551. });
  10552. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10553. auto se = detail::scope_exit([&] {
  10554. svr.stop();
  10555. listen_thread.join();
  10556. ASSERT_FALSE(svr.is_running());
  10557. });
  10558. svr.wait_until_ready();
  10559. Client cli(HOST, PORT);
  10560. auto res = cli.Get("/dir/test.html");
  10561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10562. EXPECT_EQ(StatusCode::OK_200, res->status);
  10563. res = cli.Get("/api/hello");
  10564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10565. EXPECT_EQ(StatusCode::OK_200, res->status);
  10566. EXPECT_EQ("api", res->body);
  10567. }
  10568. TEST(MountTest, PathSegmentBoundary) {
  10569. Server svr;
  10570. svr.set_mount_point("/mount2", "./www2");
  10571. svr.set_mount_point("/", "./www");
  10572. auto port = svr.bind_to_any_port(HOST);
  10573. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10574. auto se = detail::scope_exit([&] {
  10575. svr.stop();
  10576. listen_thread.join();
  10577. ASSERT_FALSE(svr.is_running());
  10578. });
  10579. svr.wait_until_ready();
  10580. Client cli(HOST, port);
  10581. auto res = cli.Get("/mount2/dir/test.html");
  10582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10583. EXPECT_EQ(StatusCode::OK_200, res->status);
  10584. // "/mount2" must not match part-way through a path segment.
  10585. res = cli.Get("/mount2dir/test.html");
  10586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10588. // A mount point ending in '/' keeps matching every path below it.
  10589. res = cli.Get("/dir/test.html");
  10590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10591. EXPECT_EQ(StatusCode::OK_200, res->status);
  10592. }
  10593. TEST(MountTest, Redicect) {
  10594. Server svr;
  10595. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10596. auto se = detail::scope_exit([&] {
  10597. svr.stop();
  10598. listen_thread.join();
  10599. ASSERT_FALSE(svr.is_running());
  10600. });
  10601. svr.set_mount_point("/", "./www");
  10602. svr.wait_until_ready();
  10603. Client cli("localhost", PORT);
  10604. auto res = cli.Get("/dir/");
  10605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10606. EXPECT_EQ(StatusCode::OK_200, res->status);
  10607. res = cli.Get("/dir");
  10608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10609. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10610. res = cli.Get("/file");
  10611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10612. EXPECT_EQ(StatusCode::OK_200, res->status);
  10613. res = cli.Get("/file/");
  10614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10615. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10616. cli.set_follow_location(true);
  10617. res = cli.Get("/dir");
  10618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10619. EXPECT_EQ(StatusCode::OK_200, res->status);
  10620. }
  10621. TEST(MountTest, MultibytesPathName) {
  10622. Server svr;
  10623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10624. auto se = detail::scope_exit([&] {
  10625. svr.stop();
  10626. listen_thread.join();
  10627. ASSERT_FALSE(svr.is_running());
  10628. });
  10629. svr.set_mount_point("/", "./www");
  10630. svr.wait_until_ready();
  10631. Client cli("localhost", PORT);
  10632. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10634. EXPECT_EQ(StatusCode::OK_200, res->status);
  10635. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10636. }
  10637. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10638. // in the pre-routing handler sees the path of every file that is served
  10639. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10640. Server svr;
  10641. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10642. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10643. if (req.path == "/dir/test.html") {
  10644. res.status = StatusCode::Unauthorized_401;
  10645. return Server::HandlerResponse::Handled;
  10646. }
  10647. return Server::HandlerResponse::Unhandled;
  10648. });
  10649. auto port = svr.bind_to_any_port(HOST);
  10650. ASSERT_LT(0, port);
  10651. thread t = thread([&] { svr.listen_after_bind(); });
  10652. auto se = detail::scope_exit([&] {
  10653. svr.stop();
  10654. t.join();
  10655. ASSERT_FALSE(svr.is_running());
  10656. });
  10657. svr.wait_until_ready();
  10658. Client cli(HOST, port);
  10659. for (auto path :
  10660. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10661. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10662. SCOPED_TRACE(path);
  10663. auto res = cli.Get(path);
  10664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10665. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10666. }
  10667. }
  10668. #ifdef _WIN32
  10669. // Issue #2435: mmap::open() must succeed even when another handle holds
  10670. // the file open for writing (e.g. an active log file).
  10671. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10672. const char *path = "mmap_concurrent_writer_test.txt";
  10673. const char *content = "hello";
  10674. {
  10675. std::ofstream f(path, std::ios::binary);
  10676. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10677. }
  10678. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10679. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10680. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10681. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10682. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10683. detail::mmap m(path);
  10684. ASSERT_TRUE(m.is_open());
  10685. EXPECT_EQ(strlen(content), m.size());
  10686. char buf[8];
  10687. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10688. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10689. }
  10690. #endif
  10691. #ifndef _WIN32
  10692. // A directory or a device has no size to serve.
  10693. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10694. const char *path = "./mmap_not_regular_test_dir";
  10695. ASSERT_EQ(0, ::mkdir(path, 0755));
  10696. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10697. for (auto p : {path, "/dev/null"}) {
  10698. detail::mmap m(p);
  10699. EXPECT_FALSE(m.is_open()) << p;
  10700. EXPECT_EQ(0U, m.size()) << p;
  10701. }
  10702. Server svr;
  10703. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10704. res.set_file_content("/dev/null");
  10705. });
  10706. auto port = svr.bind_to_any_port(HOST);
  10707. thread t = thread([&] { svr.listen_after_bind(); });
  10708. auto se = detail::scope_exit([&] {
  10709. svr.stop();
  10710. t.join();
  10711. });
  10712. svr.wait_until_ready();
  10713. auto res = Client(HOST, port).Get("/null");
  10714. ASSERT_TRUE(res);
  10715. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10716. }
  10717. #endif
  10718. #ifdef __linux__
  10719. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10720. TEST(MmapTest, FileIsNotMapped) {
  10721. const char *path = "mmap_not_mapped_test.txt";
  10722. {
  10723. std::ofstream f(path, std::ios::binary);
  10724. f << "hello";
  10725. }
  10726. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10727. detail::mmap m(path);
  10728. ASSERT_TRUE(m.is_open());
  10729. std::ifstream maps("/proc/self/maps");
  10730. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10731. std::istreambuf_iterator<char>());
  10732. EXPECT_EQ(std::string::npos, mappings.find(path));
  10733. }
  10734. #endif
  10735. TEST(KeepAliveTest, ReadTimeout) {
  10736. Server svr;
  10737. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10738. std::this_thread::sleep_for(std::chrono::seconds(2));
  10739. res.set_content("a", "text/plain");
  10740. });
  10741. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10742. res.set_content("b", "text/plain");
  10743. });
  10744. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10745. auto se = detail::scope_exit([&] {
  10746. svr.stop();
  10747. listen_thread.join();
  10748. ASSERT_FALSE(svr.is_running());
  10749. });
  10750. svr.wait_until_ready();
  10751. Client cli("localhost", PORT);
  10752. cli.set_keep_alive(true);
  10753. cli.set_read_timeout(std::chrono::seconds(1));
  10754. auto resa = cli.Get("/a");
  10755. ASSERT_FALSE(resa);
  10756. EXPECT_EQ(Error::Read, resa.error());
  10757. auto resb = cli.Get("/b");
  10758. ASSERT_TRUE(resb);
  10759. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10760. EXPECT_EQ("b", resb->body);
  10761. }
  10762. TEST(KeepAliveTest, MaxCount) {
  10763. size_t keep_alive_max_count = 3;
  10764. Server svr;
  10765. svr.set_keep_alive_max_count(keep_alive_max_count);
  10766. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10767. res.set_content("Hello World!", "text/plain");
  10768. });
  10769. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10770. auto se = detail::scope_exit([&] {
  10771. svr.stop();
  10772. listen_thread.join();
  10773. ASSERT_FALSE(svr.is_running());
  10774. });
  10775. svr.wait_until_ready();
  10776. Client cli(HOST, PORT);
  10777. cli.set_keep_alive(true);
  10778. for (size_t i = 0; i < 5; i++) {
  10779. auto result = cli.Get("/hi");
  10780. ASSERT_TRUE(result);
  10781. EXPECT_EQ(StatusCode::OK_200, result->status);
  10782. if (i == keep_alive_max_count - 1) {
  10783. EXPECT_EQ("close", result->get_header_value("Connection"));
  10784. } else {
  10785. EXPECT_FALSE(result->has_header("Connection"));
  10786. }
  10787. }
  10788. }
  10789. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10790. // can pull the next one into the server's buffer. The server must serve it
  10791. // without waiting for the socket to become readable again. The keep-alive
  10792. // timeout outlasts the client's read timeout, so a request left waiting for it
  10793. // shows up as a missing response.
  10794. static void serve_pipelining_routes(Server &svr,
  10795. const std::function<void(int)> &client) {
  10796. svr.set_keep_alive_timeout(5);
  10797. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10798. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10799. });
  10800. svr.Post("/echo", [](const Request &req, Response &res) {
  10801. res.set_content("echo " + req.body, "text/plain");
  10802. });
  10803. auto port = svr.bind_to_any_port(HOST);
  10804. thread t = thread([&] { svr.listen_after_bind(); });
  10805. auto se = detail::scope_exit([&] {
  10806. svr.stop();
  10807. t.join();
  10808. });
  10809. svr.wait_until_ready();
  10810. client(port);
  10811. }
  10812. static std::string
  10813. send_pipelined_requests(const std::vector<std::string> &parts) {
  10814. Server svr;
  10815. std::string res;
  10816. serve_pipelining_routes(svr, [&](int port) {
  10817. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10818. });
  10819. return res;
  10820. }
  10821. static void expect_in_order(const std::string &res,
  10822. const std::vector<std::string> &bodies) {
  10823. size_t pos = 0;
  10824. for (const auto &body : bodies) {
  10825. pos = res.find(body, pos);
  10826. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10827. pos += body.size();
  10828. }
  10829. }
  10830. TEST(KeepAliveTest, PipelinedRequests) {
  10831. auto res = send_pipelined_requests(
  10832. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10833. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10834. "Content-Length: 4\r\n\r\nbody"
  10835. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10836. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10837. }
  10838. // The second request starts in the server's buffer and ends on the socket.
  10839. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10840. auto res =
  10841. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10842. "GET /hi/2 HTTP/1.1\r\nHo",
  10843. "st: localhost\r\nConnection: close\r\n\r\n"});
  10844. expect_in_order(res, {"hi 1", "hi 2"});
  10845. }
  10846. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10847. // CRLF after a body does not turn into a 400 for the next request.
  10848. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10849. auto res = send_pipelined_requests(
  10850. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10851. "Content-Length: 4\r\n\r\nbody\r\n"
  10852. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10853. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10854. expect_in_order(res, {"echo body", "hi 2"});
  10855. }
  10856. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10857. // must not be served as the next request.
  10858. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10859. auto res = send_pipelined_requests(
  10860. {"INVALID REQUEST LINE\r\n\r\n"
  10861. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10862. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10863. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10864. }
  10865. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10866. // Over TLS, the next request is held by the TLS library as already decrypted
  10867. // data rather than on the socket.
  10868. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10870. std::string res;
  10871. serve_pipelining_routes(svr, [&](int port) {
  10872. // One part, so all three requests arrive in one TLS record
  10873. EXPECT_TRUE(send_ssl_request_in_parts(
  10874. 2,
  10875. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10876. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10877. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10878. &res, port));
  10879. });
  10880. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10881. }
  10882. #endif
  10883. TEST(KeepAliveTest, Issue1041) {
  10884. Server svr;
  10885. svr.set_keep_alive_timeout(3);
  10886. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10887. res.set_content("Hello World!", "text/plain");
  10888. });
  10889. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10890. auto se = detail::scope_exit([&] {
  10891. svr.stop();
  10892. listen_thread.join();
  10893. ASSERT_FALSE(svr.is_running());
  10894. });
  10895. svr.wait_until_ready();
  10896. Client cli(HOST, PORT);
  10897. cli.set_keep_alive(true);
  10898. auto result = cli.Get("/hi");
  10899. ASSERT_TRUE(result);
  10900. EXPECT_EQ(StatusCode::OK_200, result->status);
  10901. std::this_thread::sleep_for(std::chrono::seconds(5));
  10902. result = cli.Get("/hi");
  10903. ASSERT_TRUE(result);
  10904. EXPECT_EQ(StatusCode::OK_200, result->status);
  10905. }
  10906. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10907. Server svr;
  10908. svr.set_keep_alive_max_count(0);
  10909. std::set<int> remote_ports;
  10910. svr.Get("/hi", [&](const Request &req, Response &res) {
  10911. remote_ports.insert(req.remote_port);
  10912. res.set_content("hi", "text/plain");
  10913. });
  10914. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10915. auto se = detail::scope_exit([&] {
  10916. svr.stop();
  10917. listen_thread.join();
  10918. ASSERT_FALSE(svr.is_running());
  10919. });
  10920. svr.wait_until_ready();
  10921. Client cli(HOST, PORT);
  10922. cli.set_keep_alive(true);
  10923. for (int i = 0; i < 3; i++) {
  10924. auto res = cli.Get("/hi");
  10925. ASSERT_TRUE(res);
  10926. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10927. }
  10928. // All three over one connection
  10929. EXPECT_EQ(1u, remote_ports.size());
  10930. }
  10931. TEST(KeepAliveTest, Issue1959) {
  10932. Server svr;
  10933. svr.set_keep_alive_timeout(5);
  10934. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10935. res.set_content("a", "text/plain");
  10936. });
  10937. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10938. auto se = detail::scope_exit([&] {
  10939. if (!svr.is_running()) return;
  10940. svr.stop();
  10941. listen_thread.join();
  10942. ASSERT_FALSE(svr.is_running());
  10943. });
  10944. svr.wait_until_ready();
  10945. Client cli("localhost", PORT);
  10946. cli.set_keep_alive(true);
  10947. using namespace std::chrono;
  10948. auto start = steady_clock::now();
  10949. cli.Get("/a");
  10950. svr.stop();
  10951. listen_thread.join();
  10952. auto end = steady_clock::now();
  10953. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10954. EXPECT_LT(elapsed, 5000);
  10955. }
  10956. #ifdef CPPHTTPLIB_SSL_ENABLED
  10957. TEST(KeepAliveTest, SSLClientReconnection) {
  10958. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10959. ASSERT_TRUE(svr.is_valid());
  10960. svr.set_keep_alive_timeout(1);
  10961. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10962. res.set_content("Hello World!", "text/plain");
  10963. });
  10964. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10965. auto se = detail::scope_exit([&] {
  10966. svr.stop();
  10967. listen_thread.join();
  10968. ASSERT_FALSE(svr.is_running());
  10969. });
  10970. svr.wait_until_ready();
  10971. SSLClient cli(HOST, PORT);
  10972. cli.enable_server_certificate_verification(false);
  10973. cli.set_keep_alive(true);
  10974. auto result = cli.Get("/hi");
  10975. ASSERT_TRUE(result);
  10976. EXPECT_EQ(StatusCode::OK_200, result->status);
  10977. result = cli.Get("/hi");
  10978. ASSERT_TRUE(result);
  10979. EXPECT_EQ(StatusCode::OK_200, result->status);
  10980. std::this_thread::sleep_for(std::chrono::seconds(2));
  10981. // Recoonect
  10982. result = cli.Get("/hi");
  10983. ASSERT_TRUE(result);
  10984. EXPECT_EQ(StatusCode::OK_200, result->status);
  10985. result = cli.Get("/hi");
  10986. ASSERT_TRUE(result);
  10987. EXPECT_EQ(StatusCode::OK_200, result->status);
  10988. }
  10989. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10990. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10991. ASSERT_TRUE(svr.is_valid());
  10992. svr.set_keep_alive_timeout(1);
  10993. std::string content = "reconnect";
  10994. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10995. res.set_content("Hello World!", "text/plain");
  10996. });
  10997. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10998. auto se = detail::scope_exit([&] {
  10999. svr.stop();
  11000. listen_thread.join();
  11001. ASSERT_FALSE(svr.is_running());
  11002. });
  11003. svr.wait_until_ready();
  11004. SSLClient cli(HOST, PORT);
  11005. cli.enable_server_certificate_verification(false);
  11006. cli.set_keep_alive(true);
  11007. auto result = cli.Post(
  11008. "/hi", content.size(),
  11009. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11010. sink.write(content.c_str(), content.size());
  11011. return true;
  11012. },
  11013. "text/plain");
  11014. ASSERT_TRUE(result);
  11015. EXPECT_EQ(200, result->status);
  11016. std::this_thread::sleep_for(std::chrono::seconds(2));
  11017. // Recoonect
  11018. result = cli.Post(
  11019. "/hi", content.size(),
  11020. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11021. sink.write(content.c_str(), content.size());
  11022. return true;
  11023. },
  11024. "text/plain");
  11025. ASSERT_TRUE(result);
  11026. EXPECT_EQ(200, result->status);
  11027. result = cli.Post(
  11028. "/hi", content.size(),
  11029. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11030. sink.write(content.c_str(), content.size());
  11031. return true;
  11032. },
  11033. "text/plain");
  11034. ASSERT_TRUE(result);
  11035. EXPECT_EQ(200, result->status);
  11036. }
  11037. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11038. using namespace httplib::tls;
  11039. {
  11040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11041. ASSERT_TRUE(svr.is_valid());
  11042. svr.Get("/sni", [&](const Request &req, Response &res) {
  11043. std::string expected = req.sni();
  11044. EXPECT_EQ(expected, req.get_param_value("expected"));
  11045. res.set_content("ok", "text/plain");
  11046. });
  11047. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11048. auto se = detail::scope_exit([&] {
  11049. svr.stop();
  11050. listen_thread.join();
  11051. ASSERT_FALSE(svr.is_running());
  11052. });
  11053. svr.wait_until_ready();
  11054. {
  11055. SSLClient cli("localhost", PORT);
  11056. cli.enable_server_certificate_verification(false);
  11057. auto res = cli.Get("/sni?expected=localhost");
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. }
  11060. {
  11061. SSLClient cli("::1", PORT);
  11062. cli.enable_server_certificate_verification(false);
  11063. auto res = cli.Get("/sni?expected=");
  11064. // NOTE: This may fail if the server is listening on IPv4 only
  11065. // (e.g., when localhost resolves to 127.0.0.1 only)
  11066. if (res) {
  11067. EXPECT_EQ(StatusCode::OK_200, res->status);
  11068. } else {
  11069. EXPECT_EQ(Error::Connection, res.error());
  11070. }
  11071. }
  11072. }
  11073. }
  11074. // The SNI of a failed handshake does not reach the next connection that the
  11075. // same worker thread serves
  11076. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11078. ASSERT_TRUE(svr.is_valid());
  11079. svr.new_task_queue = [] { return new ThreadPool(1); };
  11080. svr.Get("/sni", [](const Request &req, Response &res) {
  11081. res.set_content(req.sni(), "text/plain");
  11082. });
  11083. auto port = svr.bind_to_any_port("127.0.0.1");
  11084. ASSERT_LT(0, port);
  11085. thread t = thread([&] { svr.listen_after_bind(); });
  11086. auto se = detail::scope_exit([&] {
  11087. svr.stop();
  11088. t.join();
  11089. ASSERT_FALSE(svr.is_running());
  11090. });
  11091. svr.wait_until_ready();
  11092. {
  11093. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11094. SSLClient cli("localhost", port);
  11095. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11096. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11097. auto res = cli.Get("/sni");
  11098. ASSERT_FALSE(res);
  11099. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11100. }
  11101. // An IP host sends no SNI (RFC 6066)
  11102. SSLClient cli("127.0.0.1", port);
  11103. cli.enable_server_certificate_verification(false);
  11104. auto res = cli.Get("/sni");
  11105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11106. EXPECT_EQ("", res->body);
  11107. }
  11108. #endif
  11109. TEST(ClientProblemDetectionTest, ContentProvider) {
  11110. Server svr;
  11111. size_t content_length = 1024 * 1024;
  11112. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11113. res.set_content_provider(
  11114. content_length, "text/plain",
  11115. [&](size_t offset, size_t length, DataSink &sink) {
  11116. auto out_len = std::min(length, static_cast<size_t>(1024));
  11117. std::string out(out_len, '@');
  11118. sink.write(out.data(), out_len);
  11119. return offset < 4096;
  11120. },
  11121. [](bool success) { ASSERT_FALSE(success); });
  11122. });
  11123. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11124. res.set_content_provider(
  11125. 0, "text/plain",
  11126. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11127. EXPECT_TRUE(false);
  11128. return true;
  11129. },
  11130. [](bool success) { ASSERT_FALSE(success); });
  11131. });
  11132. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11133. auto se = detail::scope_exit([&] {
  11134. svr.stop();
  11135. listen_thread.join();
  11136. ASSERT_FALSE(svr.is_running());
  11137. });
  11138. svr.wait_until_ready();
  11139. Client cli("localhost", PORT);
  11140. {
  11141. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11142. size_t /*data_length*/) { return false; });
  11143. ASSERT_FALSE(res);
  11144. }
  11145. {
  11146. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11147. size_t /*data_length*/) { return false; });
  11148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11149. }
  11150. }
  11151. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11152. // A provider that reports success without writing anything and without
  11153. // calling done() used to be handed the same offset and length again on every
  11154. // pass, so it spun for as long as the peer stayed connected.
  11155. Server svr;
  11156. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11157. res.set_content("ok", "text/plain");
  11158. });
  11159. auto port = svr.bind_to_any_port(HOST);
  11160. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11161. auto se = detail::scope_exit([&] {
  11162. svr.stop();
  11163. listen_thread.join();
  11164. ASSERT_FALSE(svr.is_running());
  11165. });
  11166. svr.wait_until_ready();
  11167. std::atomic<int> call_count{0};
  11168. Client cli(HOST, port);
  11169. auto res = cli.Post(
  11170. "/", 1024,
  11171. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11172. // Give up after enough passes to show the spin, so that losing the
  11173. // check below fails this test instead of hanging it.
  11174. return ++call_count < 100;
  11175. },
  11176. "text/plain");
  11177. ASSERT_FALSE(res);
  11178. EXPECT_EQ(Error::Write, res.error());
  11179. EXPECT_EQ(1, call_count.load());
  11180. }
  11181. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11182. // A writer only has to assign `write`. The other three used to be left as
  11183. // empty std::functions, so a provider calling one threw
  11184. // std::bad_function_call out of the thread running it and took the whole
  11185. // process down.
  11186. DataSink sink;
  11187. std::string written;
  11188. sink.write = [&](const char *data, size_t data_len) {
  11189. written.append(data, data_len);
  11190. return true;
  11191. };
  11192. EXPECT_TRUE(sink.is_writable());
  11193. sink.done();
  11194. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11195. EXPECT_TRUE(written.empty());
  11196. }
  11197. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11198. // A sink that cannot carry trailers still has to finish.
  11199. DataSink sink;
  11200. auto done_count = 0;
  11201. sink.done = [&]() { done_count++; };
  11202. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11203. EXPECT_EQ(1, done_count);
  11204. }
  11205. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11206. Server svr;
  11207. const std::string body(4096, 'x');
  11208. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11209. res.set_content_provider(body.size(), "text/plain",
  11210. [&](size_t offset, size_t length, DataSink &sink) {
  11211. sink.write(body.data() + offset, length);
  11212. sink.done();
  11213. return true;
  11214. });
  11215. });
  11216. auto port = svr.bind_to_any_port(HOST);
  11217. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11218. auto se = detail::scope_exit([&] {
  11219. svr.stop();
  11220. listen_thread.join();
  11221. ASSERT_FALSE(svr.is_running());
  11222. });
  11223. svr.wait_until_ready();
  11224. Client cli(HOST, port);
  11225. auto res = cli.Get("/");
  11226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11227. EXPECT_EQ(StatusCode::OK_200, res->status);
  11228. EXPECT_EQ(body, res->body);
  11229. }
  11230. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11231. Server svr;
  11232. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11233. res.set_content_provider(
  11234. 1024, "text/plain",
  11235. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11236. sink.write("hello", 5);
  11237. sink.done(); // short of the 1024 bytes the response promised
  11238. return true;
  11239. });
  11240. });
  11241. auto port = svr.bind_to_any_port(HOST);
  11242. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11243. auto se = detail::scope_exit([&] {
  11244. svr.stop();
  11245. listen_thread.join();
  11246. ASSERT_FALSE(svr.is_running());
  11247. });
  11248. svr.wait_until_ready();
  11249. Client cli(HOST, port);
  11250. cli.set_read_timeout(5, 0);
  11251. // The response is short of its Content-Length, so the client cannot read a
  11252. // complete body. What matters is that this returns at all: a no-op done()
  11253. // would leave the writer looping over a provider that never makes progress.
  11254. auto res = cli.Get("/");
  11255. EXPECT_FALSE(res);
  11256. }
  11257. // Read as the next response by a peer that sees it after a framed body.
  11258. static const std::string smuggled_response =
  11259. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11260. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11261. Server svr;
  11262. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11263. res.set_content_provider(
  11264. 5, "text/plain",
  11265. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11266. auto data = "AAAAA" + smuggled_response;
  11267. sink.write(data.data(), data.size());
  11268. return true;
  11269. });
  11270. });
  11271. thread t = thread([&] { svr.listen(HOST, PORT); });
  11272. auto se = detail::scope_exit([&] {
  11273. svr.stop();
  11274. t.join();
  11275. ASSERT_FALSE(svr.is_running());
  11276. });
  11277. svr.wait_until_ready();
  11278. std::string resp;
  11279. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11280. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11281. resp.clear();
  11282. ASSERT_TRUE(send_request(
  11283. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11284. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11285. }
  11286. TEST(NoContentTest, BodyIsNotSent) {
  11287. Server svr;
  11288. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11289. res.status = StatusCode::NoContent_204;
  11290. res.set_content(smuggled_response, "text/plain");
  11291. });
  11292. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11293. res.status = StatusCode::NotModified_304;
  11294. res.set_chunked_content_provider(
  11295. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11296. sink.write(smuggled_response.data(), smuggled_response.size());
  11297. sink.done();
  11298. return true;
  11299. });
  11300. });
  11301. thread t = thread([&] { svr.listen(HOST, PORT); });
  11302. auto se = detail::scope_exit([&] {
  11303. svr.stop();
  11304. t.join();
  11305. ASSERT_FALSE(svr.is_running());
  11306. });
  11307. svr.wait_until_ready();
  11308. for (auto path : {"/204", "/304"}) {
  11309. std::string resp;
  11310. ASSERT_TRUE(send_request(
  11311. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11312. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11313. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11314. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11315. }
  11316. }
  11317. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11318. Server svr;
  11319. std::atomic<bool> smuggled(false);
  11320. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11321. res.set_content("ok", "text/plain");
  11322. });
  11323. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11324. smuggled = true;
  11325. });
  11326. auto port = svr.bind_to_any_port(HOST);
  11327. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11328. auto se = detail::scope_exit([&] {
  11329. svr.stop();
  11330. listen_thread.join();
  11331. ASSERT_FALSE(svr.is_running());
  11332. });
  11333. svr.wait_until_ready();
  11334. // What follows the body would be read as the next request.
  11335. Client cli(HOST, port);
  11336. auto res = cli.Post(
  11337. "/", 5,
  11338. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11339. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11340. sink.write(data.data(), data.size());
  11341. return true;
  11342. },
  11343. "text/plain");
  11344. ASSERT_FALSE(res);
  11345. EXPECT_EQ(Error::Write, res.error());
  11346. EXPECT_FALSE(smuggled);
  11347. }
  11348. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11349. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11350. // The compressed path builds the whole body before connecting, so this
  11351. // fails client-side and never reaches a server.
  11352. Client cli(HOST, PORT);
  11353. cli.set_compress(true);
  11354. auto res = cli.Post(
  11355. "/", 1024,
  11356. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11357. sink.write("hello", 5);
  11358. sink.done(); // short of the 1024 bytes the request announced
  11359. return true;
  11360. },
  11361. "text/plain");
  11362. ASSERT_FALSE(res);
  11363. EXPECT_EQ(Error::Write, res.error());
  11364. }
  11365. #endif
  11366. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11367. Server svr;
  11368. svr.set_error_handler([](Request const &, Response &res) -> void {
  11369. res.set_chunked_content_provider(
  11370. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11371. sink.os << "hello";
  11372. sink.os << "world";
  11373. sink.done();
  11374. return true;
  11375. });
  11376. });
  11377. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11378. auto se = detail::scope_exit([&] {
  11379. svr.stop();
  11380. listen_thread.join();
  11381. ASSERT_FALSE(svr.is_running());
  11382. });
  11383. svr.wait_until_ready();
  11384. Client cli("localhost", PORT);
  11385. auto res = cli.Get("/");
  11386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11387. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11388. EXPECT_EQ("helloworld", res->body);
  11389. }
  11390. // A body set after a content provider must replace it, not be sent through it.
  11391. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11392. Server svr;
  11393. svr.set_mount_point("/", "./www");
  11394. svr.set_file_request_handler([](const Request &req, Response &res) {
  11395. if (req.path == "/dir/test.html") {
  11396. res.status = StatusCode::Forbidden_403;
  11397. res.set_content(std::string(5000, 'D'), "text/plain");
  11398. } else if (req.path == "/file") {
  11399. res.status = StatusCode::Forbidden_403;
  11400. res.body = "Denied";
  11401. }
  11402. });
  11403. auto port = svr.bind_to_any_port(HOST);
  11404. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11405. auto se = detail::scope_exit([&] {
  11406. svr.stop();
  11407. t.join();
  11408. ASSERT_FALSE(svr.is_running());
  11409. });
  11410. svr.wait_until_ready();
  11411. Client cli(HOST, port);
  11412. {
  11413. auto res = cli.Get("/dir/test.html");
  11414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11415. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11416. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11417. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11418. }
  11419. {
  11420. auto res = cli.Get("/file");
  11421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11422. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11423. EXPECT_EQ("Denied", res->body);
  11424. }
  11425. {
  11426. auto res = cli.Get("/dir/index.html");
  11427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11428. EXPECT_EQ(StatusCode::OK_200, res->status);
  11429. EXPECT_EQ(0U, res->body.find("<html>"));
  11430. }
  11431. }
  11432. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11433. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11434. Server svr;
  11435. std::vector<bool> released;
  11436. std::mutex released_mutex;
  11437. auto releaser = [&](bool success) {
  11438. std::lock_guard<std::mutex> guard(released_mutex);
  11439. released.push_back(success);
  11440. };
  11441. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11442. return sink.write(&"hello"[offset], length);
  11443. };
  11444. svr.Get("/sized", [&](const Request &, Response &res) {
  11445. res.status = StatusCode::NotFound_404;
  11446. res.set_content_provider(5, "text/plain", provider, releaser);
  11447. });
  11448. svr.Get("/chunked", [&](const Request &, Response &res) {
  11449. res.status = StatusCode::ServiceUnavailable_503;
  11450. res.set_chunked_content_provider(
  11451. "text/plain",
  11452. [](size_t, DataSink &sink) {
  11453. sink.os << "chunk";
  11454. sink.done();
  11455. return true;
  11456. },
  11457. releaser);
  11458. });
  11459. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11460. res.set_content_provider(5, "text/plain", provider, releaser);
  11461. throw std::runtime_error("after the provider");
  11462. });
  11463. svr.set_error_handler([](const Request &req, Response &res) {
  11464. // Leave the exception handler's content to it.
  11465. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11466. res.set_content(std::string(1000, 'E'), "text/html");
  11467. return Server::HandlerResponse::Handled;
  11468. });
  11469. svr.set_exception_handler(
  11470. [](const Request &, Response &res, std::exception_ptr) {
  11471. res.status = StatusCode::InternalServerError_500;
  11472. res.set_content(std::string(1000, 'X'), "text/html");
  11473. });
  11474. auto port = svr.bind_to_any_port(HOST);
  11475. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11476. auto se = detail::scope_exit([&] {
  11477. svr.stop();
  11478. t.join();
  11479. ASSERT_FALSE(svr.is_running());
  11480. });
  11481. svr.wait_until_ready();
  11482. Client cli(HOST, port);
  11483. {
  11484. auto res = cli.Get("/sized");
  11485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11487. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11488. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11489. }
  11490. {
  11491. auto res = cli.Get("/chunked");
  11492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11493. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11494. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11495. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11496. }
  11497. {
  11498. auto res = cli.Get("/throw");
  11499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11500. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11501. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11502. }
  11503. std::lock_guard<std::mutex> guard(released_mutex);
  11504. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11505. }
  11506. #endif
  11507. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11508. Server svr;
  11509. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11510. return sink.write(&"abc"[offset], length);
  11511. };
  11512. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11513. res.set_file_content("./www/dir/test.html");
  11514. res.set_content("body", "text/plain");
  11515. });
  11516. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11517. res.set_content(std::string(100, 'B'), "text/plain");
  11518. res.set_file_content("./www/dir/test.html");
  11519. });
  11520. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11521. res.set_content(std::string(100, 'B'), "text/plain");
  11522. res.set_content_provider(3, "text/x-provider", abc);
  11523. });
  11524. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11525. res.set_content_provider(3, "text/x-provider", abc);
  11526. res.set_content(std::string(100, 'B'), "text/plain");
  11527. });
  11528. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11529. res.set_content_provider(3, "text/x-provider", abc);
  11530. res.set_file_content("./www/dir/test.html", "text/x-file");
  11531. });
  11532. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11533. res.set_file_content("./www/dir/test.html");
  11534. res.set_header("Content-Type", "text/x-handler");
  11535. });
  11536. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11537. res.set_content_provider(3, "text/plain", abc);
  11538. res.body = "direct";
  11539. });
  11540. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11541. res.set_file_content("./www/dir/test.html");
  11542. res.body = "direct";
  11543. });
  11544. auto port = svr.bind_to_any_port(HOST);
  11545. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11546. auto se = detail::scope_exit([&] {
  11547. svr.stop();
  11548. t.join();
  11549. ASSERT_FALSE(svr.is_running());
  11550. });
  11551. svr.wait_until_ready();
  11552. Client cli(HOST, port);
  11553. auto expect_body = [&](const char *path, const std::string &body,
  11554. const std::string &type) {
  11555. // Uncompressed, so Content-Length can be compared with the body.
  11556. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11557. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11558. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11559. EXPECT_EQ(body, res->body) << path;
  11560. EXPECT_EQ(std::to_string(body.size()),
  11561. res->get_header_value("Content-Length"))
  11562. << path;
  11563. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11564. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11565. };
  11566. expect_body("/file-then-body", "body", "text/plain");
  11567. expect_body("/body-then-file", "test.html", "text/html");
  11568. expect_body("/body-then-provider", "abc", "text/x-provider");
  11569. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11570. expect_body("/provider-then-file", "test.html", "text/x-file");
  11571. expect_body("/file-then-header", "test.html", "text/x-handler");
  11572. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11573. expect_body("/file-then-direct-body", "direct", "text/plain");
  11574. // Ranges are checked against the body, not the dropped provider.
  11575. {
  11576. auto res = cli.Get("/provider-then-direct-body",
  11577. Headers{{make_range_header({{1, 2}})}});
  11578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11579. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11580. EXPECT_EQ("ir", res->body);
  11581. }
  11582. {
  11583. auto res = cli.Get("/file-then-direct-body",
  11584. Headers{{make_range_header({{7, 8}})}});
  11585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11586. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11587. }
  11588. }
  11589. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11590. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11591. const char *path = "./truncated_while_served.txt";
  11592. const size_t size = 32 * 1024 * 1024;
  11593. {
  11594. std::ofstream f(path, std::ios::binary);
  11595. f << std::string(size, 'x');
  11596. }
  11597. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11598. // Over TLS, where the bytes are encrypted in this process rather than
  11599. // copied by send().
  11600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11601. svr.Get("/file", [&](const Request &, Response &res) {
  11602. res.set_file_content(path, "text/plain");
  11603. });
  11604. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11605. auto se = detail::scope_exit([&] {
  11606. svr.stop();
  11607. thread.join();
  11608. ASSERT_FALSE(svr.is_running());
  11609. });
  11610. svr.wait_until_ready();
  11611. // The file shrinks once the first bytes are in, as a rewrite in place
  11612. // would, and reading the mapping past its new end used to raise SIGBUS.
  11613. SSLClient cli(HOST, PORT);
  11614. cli.enable_server_certificate_verification(false);
  11615. size_t received = 0;
  11616. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11617. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11618. received += len;
  11619. return true;
  11620. });
  11621. EXPECT_FALSE(res);
  11622. EXPECT_LT(received, size);
  11623. }
  11624. #endif
  11625. // Forward declaration (see the base64_encode note).
  11626. namespace httplib {
  11627. namespace detail {
  11628. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11629. const std::string &content_type,
  11630. EncodingType encoding);
  11631. } // namespace detail
  11632. } // namespace httplib
  11633. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11634. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11635. ASSERT_TRUE(mm->is_open());
  11636. Response res;
  11637. detail::set_file_content_provider(res, mm, "text/html",
  11638. detail::EncodingType::None);
  11639. std::string out;
  11640. DataSink sink;
  11641. sink.write = [&](const char *d, size_t l) {
  11642. out.append(d, l);
  11643. return true;
  11644. };
  11645. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11646. EXPECT_EQ("test.html", out);
  11647. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11648. EXPECT_EQ("test.html", out);
  11649. }
  11650. TEST(LongPollingTest, ClientCloseDetection) {
  11651. Server svr;
  11652. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11653. res.set_chunked_content_provider(
  11654. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11655. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11656. sink.os << "hello";
  11657. auto count = 10;
  11658. while (count > 0 && sink.is_writable()) {
  11659. this_thread::sleep_for(chrono::milliseconds(10));
  11660. count--;
  11661. }
  11662. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11663. return true;
  11664. });
  11665. });
  11666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11667. auto se = detail::scope_exit([&] {
  11668. svr.stop();
  11669. listen_thread.join();
  11670. ASSERT_FALSE(svr.is_running());
  11671. });
  11672. svr.wait_until_ready();
  11673. Client cli("localhost", PORT);
  11674. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11675. EXPECT_EQ("hello", string(data, data_length));
  11676. return false; // close the socket immediately.
  11677. });
  11678. ASSERT_FALSE(res);
  11679. }
  11680. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11681. Server svr;
  11682. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11683. res.set_chunked_content_provider(
  11684. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11685. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11686. sink.os << "hello";
  11687. EXPECT_TRUE(sink.os.good());
  11688. // Wait for the client to close the connection
  11689. auto count = 10;
  11690. while (count > 0 && sink.is_writable()) {
  11691. this_thread::sleep_for(chrono::milliseconds(10));
  11692. count--;
  11693. }
  11694. // After client disconnect, write repeatedly until the socket
  11695. // write actually fails (small writes may be absorbed by the
  11696. // kernel buffer)
  11697. std::string chunk(1024, 'x');
  11698. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11699. sink.os << chunk;
  11700. }
  11701. EXPECT_TRUE(sink.os.fail());
  11702. return true;
  11703. });
  11704. });
  11705. auto port = svr.bind_to_any_port("localhost");
  11706. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11707. auto se = detail::scope_exit([&] {
  11708. svr.stop();
  11709. listen_thread.join();
  11710. ASSERT_FALSE(svr.is_running());
  11711. });
  11712. svr.wait_until_ready();
  11713. Client cli("localhost", port);
  11714. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11715. EXPECT_EQ("hello", string(data, data_length));
  11716. return false; // close the socket immediately.
  11717. });
  11718. ASSERT_FALSE(res);
  11719. }
  11720. TEST(GetWithParametersTest, GetWithParameters) {
  11721. Server svr;
  11722. svr.Get("/", [&](const Request &req, Response &) {
  11723. EXPECT_EQ("world", req.get_param_value("hello"));
  11724. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11725. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11726. });
  11727. svr.Get("/params", [&](const Request &req, Response &) {
  11728. EXPECT_EQ("world", req.get_param_value("hello"));
  11729. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11730. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11731. });
  11732. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11733. EXPECT_EQ("resource-id", req.matches[1]);
  11734. EXPECT_EQ("foo", req.get_param_value("param1"));
  11735. EXPECT_EQ("bar", req.get_param_value("param2"));
  11736. });
  11737. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11738. EXPECT_EQ("user-id", req.path_params.at("id"));
  11739. EXPECT_EQ("foo", req.get_param_value("param1"));
  11740. EXPECT_EQ("bar", req.get_param_value("param2"));
  11741. });
  11742. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11743. auto se = detail::scope_exit([&] {
  11744. svr.stop();
  11745. listen_thread.join();
  11746. ASSERT_FALSE(svr.is_running());
  11747. });
  11748. svr.wait_until_ready();
  11749. {
  11750. Client cli(HOST, PORT);
  11751. Params params;
  11752. params.emplace("hello", "world");
  11753. params.emplace("hello2", "world2");
  11754. params.emplace("hello3", "world3");
  11755. auto res = cli.Get("/", params, Headers{});
  11756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11757. EXPECT_EQ(StatusCode::OK_200, res->status);
  11758. }
  11759. {
  11760. Client cli(HOST, PORT);
  11761. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11763. EXPECT_EQ(StatusCode::OK_200, res->status);
  11764. }
  11765. {
  11766. Client cli(HOST, PORT);
  11767. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11769. EXPECT_EQ(StatusCode::OK_200, res->status);
  11770. }
  11771. {
  11772. Client cli(HOST, PORT);
  11773. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11775. EXPECT_EQ(StatusCode::OK_200, res->status);
  11776. }
  11777. }
  11778. TEST(GetWithParametersTest, GetWithParameters2) {
  11779. Server svr;
  11780. svr.Get("/", [&](const Request &req, Response &res) {
  11781. auto text = req.get_param_value("hello");
  11782. res.set_content(text, "text/plain");
  11783. });
  11784. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11785. auto se = detail::scope_exit([&] {
  11786. svr.stop();
  11787. listen_thread.join();
  11788. ASSERT_FALSE(svr.is_running());
  11789. });
  11790. svr.wait_until_ready();
  11791. Client cli("localhost", PORT);
  11792. Params params;
  11793. params.emplace("hello", "world");
  11794. std::string body;
  11795. auto res = cli.Get("/", params, Headers{},
  11796. [&](const char *data, size_t data_length) {
  11797. body.append(data, data_length);
  11798. return true;
  11799. });
  11800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11801. EXPECT_EQ(StatusCode::OK_200, res->status);
  11802. EXPECT_EQ("world", body);
  11803. }
  11804. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11805. Server svr;
  11806. svr.Get("/search", [&](const Request &req, Response &res) {
  11807. auto q = req.get_param_value("q");
  11808. res.set_content(q, "text/plain");
  11809. });
  11810. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11811. auto se = detail::scope_exit([&] {
  11812. svr.stop();
  11813. listen_thread.join();
  11814. ASSERT_FALSE(svr.is_running());
  11815. });
  11816. svr.wait_until_ready();
  11817. Client cli("localhost", PORT);
  11818. // Verify that Get(path, params) works without requiring Headers argument
  11819. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11821. EXPECT_EQ(StatusCode::OK_200, res->status);
  11822. EXPECT_EQ("cpp-httplib", res->body);
  11823. }
  11824. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11825. auto host = "httpbingo.org";
  11826. auto path = std::string{"/range/32"};
  11827. #ifdef CPPHTTPLIB_SSL_ENABLED
  11828. SSLClient cli(host);
  11829. #else
  11830. Client cli(host);
  11831. #endif
  11832. cli.set_default_headers({make_range_header({{1, 10}})});
  11833. cli.set_connection_timeout(5);
  11834. {
  11835. auto res = cli.Get(path);
  11836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11837. EXPECT_EQ("bcdefghijk", res->body);
  11838. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11839. }
  11840. {
  11841. auto res = cli.Get(path);
  11842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11843. EXPECT_EQ("bcdefghijk", res->body);
  11844. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11845. }
  11846. }
  11847. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11848. Server svr;
  11849. svr.set_default_headers({{"Hello", "World"}});
  11850. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11851. res.set_content("ok", "text/plain");
  11852. });
  11853. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11854. auto se = detail::scope_exit([&] {
  11855. svr.stop();
  11856. listen_thread.join();
  11857. ASSERT_FALSE(svr.is_running());
  11858. });
  11859. svr.wait_until_ready();
  11860. Client cli("localhost", PORT);
  11861. auto res = cli.Get("/");
  11862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11863. EXPECT_EQ(StatusCode::OK_200, res->status);
  11864. EXPECT_EQ("ok", res->body);
  11865. EXPECT_EQ("World", res->get_header_value("Hello"));
  11866. }
  11867. #ifdef CPPHTTPLIB_SSL_ENABLED
  11868. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11870. ASSERT_TRUE(svr.is_valid());
  11871. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11872. std::this_thread::sleep_for(std::chrono::seconds(2));
  11873. res.set_content("a", "text/plain");
  11874. });
  11875. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11876. res.set_content("b", "text/plain");
  11877. });
  11878. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11879. auto se = detail::scope_exit([&] {
  11880. svr.stop();
  11881. listen_thread.join();
  11882. ASSERT_FALSE(svr.is_running());
  11883. });
  11884. svr.wait_until_ready();
  11885. SSLClient cli("localhost", PORT);
  11886. cli.enable_server_certificate_verification(false);
  11887. cli.set_keep_alive(true);
  11888. cli.set_read_timeout(std::chrono::seconds(1));
  11889. auto resa = cli.Get("/a");
  11890. ASSERT_TRUE(!resa);
  11891. EXPECT_EQ(Error::Read, resa.error());
  11892. auto resb = cli.Get("/b");
  11893. ASSERT_TRUE(resb);
  11894. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11895. EXPECT_EQ("b", resb->body);
  11896. }
  11897. // Closing an idle keep-alive connection sends close_notify and returns. The
  11898. // server must not wait for the client's close_notify: an idle client never
  11899. // sends one, so the worker would be held until the read timeout expires, and
  11900. // stop() would wait for it.
  11901. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11902. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11903. ASSERT_TRUE(svr.is_valid());
  11904. svr.set_keep_alive_timeout(1);
  11905. svr.set_read_timeout(10, 0);
  11906. svr.Get("/", [](const Request &, Response &res) {
  11907. res.set_content("ok", "text/plain");
  11908. });
  11909. auto port = svr.bind_to_any_port(HOST);
  11910. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11911. auto se = detail::scope_exit([&] {
  11912. if (listen_thread.joinable()) {
  11913. svr.stop();
  11914. listen_thread.join();
  11915. }
  11916. });
  11917. svr.wait_until_ready();
  11918. SSLClient cli(HOST, port);
  11919. cli.enable_server_certificate_verification(false);
  11920. cli.set_keep_alive(true);
  11921. auto res = cli.Get("/");
  11922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11923. EXPECT_EQ(StatusCode::OK_200, res->status);
  11924. // Stay idle past the keep-alive timeout so the server closes the connection.
  11925. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11926. auto start = std::chrono::steady_clock::now();
  11927. svr.stop();
  11928. listen_thread.join();
  11929. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11930. std::chrono::steady_clock::now() - start)
  11931. .count();
  11932. EXPECT_LT(elapsed, 3000);
  11933. }
  11934. #endif
  11935. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11936. protected:
  11937. ServerTestWithAI_PASSIVE()
  11938. : cli_(HOST, PORT)
  11939. #ifdef CPPHTTPLIB_SSL_ENABLED
  11940. ,
  11941. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11942. #endif
  11943. {
  11944. #ifdef CPPHTTPLIB_SSL_ENABLED
  11945. cli_.enable_server_certificate_verification(false);
  11946. #endif
  11947. }
  11948. virtual void SetUp() {
  11949. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11950. res.set_content("Hello World!", "text/plain");
  11951. });
  11952. t_ = thread(
  11953. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11954. svr_.wait_until_ready();
  11955. }
  11956. virtual void TearDown() {
  11957. svr_.stop();
  11958. t_.join();
  11959. }
  11960. #ifdef CPPHTTPLIB_SSL_ENABLED
  11961. SSLClient cli_;
  11962. SSLServer svr_;
  11963. #else
  11964. Client cli_;
  11965. Server svr_;
  11966. #endif
  11967. thread t_;
  11968. };
  11969. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11970. auto res = cli_.Get("/hi");
  11971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11972. EXPECT_EQ(StatusCode::OK_200, res->status);
  11973. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11974. EXPECT_EQ("Hello World!", res->body);
  11975. }
  11976. class ServerUpDownTest : public ::testing::Test {
  11977. protected:
  11978. ServerUpDownTest() : cli_(HOST, PORT) {}
  11979. virtual void SetUp() {
  11980. t_ = thread([&]() {
  11981. svr_.bind_to_any_port(HOST);
  11982. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11983. ASSERT_TRUE(svr_.listen_after_bind());
  11984. });
  11985. svr_.wait_until_ready();
  11986. }
  11987. virtual void TearDown() {
  11988. svr_.stop();
  11989. t_.join();
  11990. }
  11991. Client cli_;
  11992. Server svr_;
  11993. thread t_;
  11994. };
  11995. TEST_F(ServerUpDownTest, QuickStartStop) {
  11996. // Should not crash, especially when run with
  11997. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11998. }
  11999. class PayloadMaxLengthTest : public ::testing::Test {
  12000. protected:
  12001. PayloadMaxLengthTest()
  12002. : cli_(HOST, PORT)
  12003. #ifdef CPPHTTPLIB_SSL_ENABLED
  12004. ,
  12005. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12006. #endif
  12007. {
  12008. #ifdef CPPHTTPLIB_SSL_ENABLED
  12009. cli_.enable_server_certificate_verification(false);
  12010. #endif
  12011. }
  12012. virtual void SetUp() {
  12013. svr_.set_payload_max_length(8);
  12014. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12015. res.set_content("test", "text/plain");
  12016. });
  12017. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12018. svr_.wait_until_ready();
  12019. }
  12020. virtual void TearDown() {
  12021. svr_.stop();
  12022. t_.join();
  12023. }
  12024. #ifdef CPPHTTPLIB_SSL_ENABLED
  12025. SSLClient cli_;
  12026. SSLServer svr_;
  12027. #else
  12028. Client cli_;
  12029. Server svr_;
  12030. #endif
  12031. thread t_;
  12032. };
  12033. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12034. auto res = cli_.Post("/test", "123456789", "text/plain");
  12035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12036. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12037. res = cli_.Post("/test", "12345678", "text/plain");
  12038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12039. EXPECT_EQ(StatusCode::OK_200, res->status);
  12040. }
  12041. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12042. // Test chunked encoding with payload exceeding the 8-byte limit
  12043. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12044. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12046. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12047. }
  12048. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12049. // Test chunked encoding with payload within the 8-byte limit
  12050. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12051. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12053. EXPECT_EQ(StatusCode::OK_200, res->status);
  12054. }
  12055. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12056. // Test using send_request to send chunked data exceeding payload limit
  12057. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12058. "Host: " +
  12059. std::string(HOST) + ":" + std::to_string(PORT) +
  12060. "\r\n"
  12061. "Transfer-Encoding: chunked\r\n"
  12062. "Connection: close\r\n"
  12063. "\r\n"
  12064. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12065. "0123456789\r\n"
  12066. "0\r\n" // End chunk
  12067. "\r\n";
  12068. std::string response;
  12069. bool result = send_request(1, chunked_request, &response);
  12070. if (!result) {
  12071. // If send_request fails, it might be because the server closed the
  12072. // connection due to payload limit enforcement, which is acceptable
  12073. SUCCEED()
  12074. << "Server rejected oversized chunked request (connection closed)";
  12075. } else {
  12076. // If we got a response, check if it's an error response or connection was
  12077. // closed early Short response length indicates connection was closed due to
  12078. // payload limit
  12079. if (response.length() <= 10) {
  12080. SUCCEED() << "Server closed connection for oversized chunked request";
  12081. } else {
  12082. // Check for error status codes
  12083. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12084. response.find("Payload Too Large") != std::string::npos ||
  12085. response.find("400") != std::string::npos);
  12086. }
  12087. }
  12088. }
  12089. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  12090. // Test request without Content-Length header exceeding payload limit
  12091. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12092. "Host: " +
  12093. std::string(HOST) + ":" +
  12094. std::to_string(PORT) +
  12095. "\r\n"
  12096. "Connection: close\r\n"
  12097. "\r\n";
  12098. // Add payload exceeding the 8-byte limit
  12099. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  12100. request_without_content_length += large_payload;
  12101. std::string response;
  12102. bool result = send_request(1, request_without_content_length, &response);
  12103. if (!result) {
  12104. // If send_request fails, server likely closed connection due to payload
  12105. // limit
  12106. SUCCEED() << "Server rejected oversized request without Content-Length "
  12107. "(connection closed)";
  12108. } else {
  12109. // Check if server responded with error or closed connection early
  12110. if (response.length() <= 10) {
  12111. SUCCEED() << "Server closed connection for oversized request without "
  12112. "Content-Length";
  12113. } else {
  12114. // Check for error status codes
  12115. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12116. response.find("Payload Too Large") != std::string::npos ||
  12117. response.find("400") != std::string::npos);
  12118. }
  12119. }
  12120. }
  12121. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12122. // Test request without Content-Length header within payload limit
  12123. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12124. "Host: " +
  12125. std::string(HOST) + ":" +
  12126. std::to_string(PORT) +
  12127. "\r\n"
  12128. "Connection: close\r\n"
  12129. "\r\n";
  12130. // Add payload within the 8-byte limit
  12131. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12132. request_without_content_length += small_payload;
  12133. std::string response;
  12134. bool result = send_request(1, request_without_content_length, &response);
  12135. // For requests without Content-Length, the server may have different behavior
  12136. // The key is that it should not reject due to payload limit for small
  12137. // payloads
  12138. if (result) {
  12139. // Check for any HTTP response (success or error, but not connection closed)
  12140. if (response.length() > 10) {
  12141. SUCCEED()
  12142. << "Server processed request without Content-Length within limit";
  12143. } else {
  12144. // Short response might indicate connection closed, which is acceptable
  12145. SUCCEED() << "Server closed connection for request without "
  12146. "Content-Length (acceptable behavior)";
  12147. }
  12148. } else {
  12149. // Connection failure might be due to protocol requirements
  12150. SUCCEED() << "Connection issue with request without Content-Length "
  12151. "(environment-specific)";
  12152. }
  12153. }
  12154. class LargePayloadMaxLengthTest : public ::testing::Test {
  12155. protected:
  12156. LargePayloadMaxLengthTest()
  12157. : cli_(HOST, PORT)
  12158. #ifdef CPPHTTPLIB_SSL_ENABLED
  12159. ,
  12160. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12161. #endif
  12162. {
  12163. #ifdef CPPHTTPLIB_SSL_ENABLED
  12164. cli_.enable_server_certificate_verification(false);
  12165. #endif
  12166. }
  12167. virtual void SetUp() {
  12168. // Set 10MB payload limit
  12169. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12170. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12171. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12172. res.set_content("Large payload test", "text/plain");
  12173. });
  12174. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12175. svr_.wait_until_ready();
  12176. }
  12177. virtual void TearDown() {
  12178. svr_.stop();
  12179. t_.join();
  12180. }
  12181. #ifdef CPPHTTPLIB_SSL_ENABLED
  12182. SSLClient cli_;
  12183. SSLServer svr_;
  12184. #else
  12185. Client cli_;
  12186. Server svr_;
  12187. #endif
  12188. thread t_;
  12189. };
  12190. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12191. // Test chunked encoding with payload within 10MB limit
  12192. std::string medium_payload(5 * 1024 * 1024,
  12193. 'A'); // 5MB payload, within 10MB limit
  12194. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12196. EXPECT_EQ(StatusCode::OK_200, res->status);
  12197. }
  12198. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12199. // Test chunked encoding with payload exceeding 10MB limit
  12200. std::string large_payload(12 * 1024 * 1024,
  12201. 'B'); // 12MB payload, exceeds 10MB limit
  12202. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12203. // Server may either return 413 or close the connection
  12204. if (res) {
  12205. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12206. } else {
  12207. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12208. }
  12209. }
  12210. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12211. // Test request without Content-Length header within 10MB limit
  12212. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12213. "Host: " +
  12214. std::string(HOST) + ":" +
  12215. std::to_string(PORT) +
  12216. "\r\n"
  12217. "Connection: close\r\n"
  12218. "\r\n";
  12219. // Add 1MB payload (within 10MB limit)
  12220. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12221. request_without_content_length += medium_payload;
  12222. std::string response;
  12223. bool result = send_request(5, request_without_content_length, &response);
  12224. if (result) {
  12225. // Should get a proper HTTP response for payloads within limit
  12226. if (response.length() > 10) {
  12227. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12228. "10MB limit";
  12229. } else {
  12230. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12231. "Content-Length)";
  12232. }
  12233. } else {
  12234. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12235. }
  12236. }
  12237. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12238. // Test request without Content-Length header exceeding 10MB limit
  12239. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12240. "Host: " +
  12241. std::string(HOST) + ":" +
  12242. std::to_string(PORT) +
  12243. "\r\n"
  12244. "Connection: close\r\n"
  12245. "\r\n";
  12246. // Add 12MB payload (exceeds 10MB limit)
  12247. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12248. request_without_content_length += large_payload;
  12249. std::string response;
  12250. bool result = send_request(10, request_without_content_length, &response);
  12251. if (!result) {
  12252. // Server should close connection due to payload limit
  12253. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12254. "(connection closed)";
  12255. } else {
  12256. // Check for error response
  12257. if (response.length() <= 10) {
  12258. SUCCEED()
  12259. << "Server closed connection for 12MB request exceeding 10MB limit";
  12260. } else {
  12261. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12262. response.find("Payload Too Large") != std::string::npos ||
  12263. response.find("400") != std::string::npos);
  12264. }
  12265. }
  12266. }
  12267. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12268. Server svr;
  12269. svr.Get("/", [](const Request &, Response &res) {
  12270. // Claims the most the client accepts, far more than it sends, then drops
  12271. // the connection.
  12272. res.set_content_provider(std::string().max_size(), "text/plain",
  12273. [](size_t, size_t, DataSink &sink) {
  12274. sink.write("abc", 3);
  12275. return false;
  12276. });
  12277. });
  12278. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12279. auto se = detail::scope_exit([&] {
  12280. svr.stop();
  12281. thread.join();
  12282. ASSERT_FALSE(svr.is_running());
  12283. });
  12284. svr.wait_until_ready();
  12285. Client cli(HOST, PORT);
  12286. cli.set_payload_max_length(0);
  12287. EXPECT_FALSE(cli.Get("/"));
  12288. }
  12289. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12290. // Stream API does, not as a plain read failure
  12291. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12292. Server svr;
  12293. svr.Get("/big", [](const Request &, Response &res) {
  12294. res.set_content(std::string(100000, 'b'), "text/plain");
  12295. });
  12296. auto port = svr.bind_to_any_port(HOST);
  12297. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12298. auto se = detail::scope_exit([&] {
  12299. svr.stop();
  12300. thread.join();
  12301. });
  12302. svr.wait_until_ready();
  12303. Client cli(HOST, port);
  12304. cli.set_payload_max_length(1000);
  12305. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12306. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12307. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12308. [](const char *, size_t) { return true; });
  12309. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12310. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12311. // Small on the wire, over the limit once decompressed
  12312. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12313. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12314. #endif
  12315. }
  12316. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12317. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12318. // path.
  12319. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12320. Server svr;
  12321. const size_t LIMIT = 64 * 1024; // 64KB
  12322. svr.set_payload_max_length(LIMIT);
  12323. size_t total = 0;
  12324. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12325. const ContentReader &content_reader) {
  12326. content_reader([&](const char * /*data*/, size_t len) {
  12327. total += len;
  12328. return true;
  12329. });
  12330. res.status = 200;
  12331. res.set_content("stream_ok", "text/plain");
  12332. });
  12333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12334. auto se = detail::scope_exit([&] {
  12335. svr.stop();
  12336. thread.join();
  12337. ASSERT_FALSE(svr.is_running());
  12338. });
  12339. svr.wait_until_ready();
  12340. // Prepare 256KB raw data and gzip-compress it
  12341. std::string raw(256 * 1024, 'A');
  12342. std::string gz;
  12343. {
  12344. z_stream zs{};
  12345. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12346. Z_DEFAULT_STRATEGY);
  12347. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12348. zs.avail_in = static_cast<uInt>(raw.size());
  12349. char outbuf[4096];
  12350. int ret;
  12351. do {
  12352. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12353. zs.avail_out = sizeof(outbuf);
  12354. ret = deflate(&zs, Z_FINISH);
  12355. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12356. } while (ret != Z_STREAM_END);
  12357. deflateEnd(&zs);
  12358. }
  12359. Client cli(HOST, PORT);
  12360. cli.set_connection_timeout(std::chrono::seconds(5));
  12361. Headers headers = {{"Content-Encoding", "gzip"}};
  12362. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12363. "application/octet-stream");
  12364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12365. // Server must reject oversized decompressed payloads with 413.
  12366. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12367. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12368. EXPECT_LE(total, LIMIT);
  12369. }
  12370. #ifndef CPPHTTPLIB_SSL_ENABLED
  12371. // For a request with neither Content-Length nor Transfer-Encoding, the
  12372. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12373. // compressed wire bytes straight to the ContentReader without ever routing
  12374. // them through the decompressor, so payload_max_length_ only bounded the
  12375. // compressed size on the wire, not the decompressed size.
  12376. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12377. Server svr;
  12378. const size_t LIMIT = 64 * 1024; // 64KB
  12379. svr.set_payload_max_length(LIMIT);
  12380. size_t total = 0;
  12381. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12382. const ContentReader &content_reader) {
  12383. content_reader([&](const char * /*data*/, size_t len) {
  12384. total += len;
  12385. return true;
  12386. });
  12387. res.status = 200;
  12388. res.set_content("stream_ok", "text/plain");
  12389. });
  12390. auto port = svr.bind_to_any_port(HOST);
  12391. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12392. auto se = detail::scope_exit([&] {
  12393. svr.stop();
  12394. thread.join();
  12395. ASSERT_FALSE(svr.is_running());
  12396. });
  12397. svr.wait_until_ready();
  12398. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12399. // StreamingGzipDecompression test above.
  12400. std::string raw(256 * 1024, 'A');
  12401. std::string gz;
  12402. {
  12403. httplib::detail::gzip_compressor compressor;
  12404. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12405. [&](const char *chunk, size_t len) {
  12406. gz.append(chunk, len);
  12407. return true;
  12408. });
  12409. ASSERT_TRUE(result);
  12410. }
  12411. // Send the gzip body over raw TCP with neither Content-Length nor
  12412. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12413. // kicks in.
  12414. std::string req = "POST /stream HTTP/1.1\r\n"
  12415. "Host: " +
  12416. std::string(HOST) + ":" + std::to_string(port) +
  12417. "\r\n"
  12418. "Content-Encoding: gzip\r\n"
  12419. "Connection: close\r\n"
  12420. "\r\n" +
  12421. gz;
  12422. std::string response;
  12423. ASSERT_TRUE(send_request(5, req, &response, port));
  12424. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12425. EXPECT_LE(total, LIMIT);
  12426. }
  12427. #endif
  12428. #endif
  12429. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12430. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12431. // the payload must be passed through untouched instead of being rejected.
  12432. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12433. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12434. Server svr;
  12435. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12436. res.set_content(body, "image/jpeg");
  12437. res.set_header("Content-Encoding", "UTF-8");
  12438. });
  12439. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12440. res.set_content(body, "image/jpeg");
  12441. res.set_header("Content-Encoding", "identity");
  12442. });
  12443. svr.Post("/echo", [](const Request &req, Response &res) {
  12444. res.set_content(req.body, "image/jpeg");
  12445. });
  12446. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12447. auto se = detail::scope_exit([&] {
  12448. svr.stop();
  12449. t.join();
  12450. ASSERT_FALSE(svr.is_running());
  12451. });
  12452. svr.wait_until_ready();
  12453. Client cli(HOST, PORT);
  12454. {
  12455. auto res = cli.Get("/image");
  12456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12457. EXPECT_EQ(StatusCode::OK_200, res->status);
  12458. EXPECT_EQ(body, res->body);
  12459. }
  12460. {
  12461. auto res = cli.Get("/identity");
  12462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12463. EXPECT_EQ(StatusCode::OK_200, res->status);
  12464. EXPECT_EQ(body, res->body);
  12465. }
  12466. {
  12467. // The same applies to a request body reaching the server.
  12468. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12469. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12471. EXPECT_EQ(StatusCode::OK_200, res->status);
  12472. EXPECT_EQ(body, res->body);
  12473. }
  12474. }
  12475. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12476. // gzip-encoded response even when the build has no zlib support.
  12477. static const char GZIPPED_HELLO_WORLD[] = {
  12478. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12479. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12480. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12481. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12482. // A content coding is a whole token, not something the field value merely
  12483. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12484. // as "fibre" look like Brotli, and turned a multi-coding value like
  12485. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12486. // it was never meant to see.
  12487. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12488. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12489. Server svr;
  12490. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12491. res.set_content(body, "image/jpeg");
  12492. res.set_header("Content-Encoding", "fibre");
  12493. });
  12494. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12495. res.set_content(body, "image/jpeg");
  12496. res.set_header("Content-Encoding", "gzip, br");
  12497. });
  12498. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12499. res.set_content(body, "image/jpeg");
  12500. res.set_header("Content-Encoding", "x-zstd-ish");
  12501. });
  12502. auto port = svr.bind_to_any_port(HOST);
  12503. thread t = thread([&]() { svr.listen_after_bind(); });
  12504. auto se = detail::scope_exit([&] {
  12505. svr.stop();
  12506. t.join();
  12507. ASSERT_FALSE(svr.is_running());
  12508. });
  12509. svr.wait_until_ready();
  12510. Client cli(HOST, port);
  12511. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12512. auto res = cli.Get(path);
  12513. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12514. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12515. // Not a coding we recognize, so the payload comes back untouched
  12516. EXPECT_EQ(body, res->body) << path;
  12517. }
  12518. }
  12519. // A content coding cpp-httplib recognizes but was not built with must be
  12520. // reported as such. Handing the still-compressed payload back to the caller
  12521. // would silently corrupt it.
  12522. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12523. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12524. Server svr;
  12525. // "image/jpeg" keeps the server from applying a content coding of its own,
  12526. // so the hand-crafted Content-Encoding below survives.
  12527. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12528. res.set_content(gzipped, "image/jpeg");
  12529. res.set_header("Content-Encoding", "gzip");
  12530. });
  12531. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12532. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12533. res.set_content(gzipped, "image/jpeg");
  12534. res.set_header("Content-Encoding", "GZIP");
  12535. });
  12536. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12537. auto se = detail::scope_exit([&] {
  12538. svr.stop();
  12539. t.join();
  12540. ASSERT_FALSE(svr.is_running());
  12541. });
  12542. svr.wait_until_ready();
  12543. Client cli(HOST, PORT);
  12544. {
  12545. auto res = cli.Get("/gzipped");
  12546. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12548. EXPECT_EQ("Hello World!", res->body);
  12549. #else
  12550. ASSERT_FALSE(res);
  12551. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12552. #endif
  12553. }
  12554. {
  12555. // open_stream() must behave the same way.
  12556. auto handle = cli.open_stream("GET", "/gzipped");
  12557. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12558. ASSERT_TRUE(handle.is_valid());
  12559. std::string received;
  12560. char buf[256];
  12561. ssize_t n;
  12562. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12563. received.append(buf, static_cast<size_t>(n));
  12564. }
  12565. EXPECT_EQ("Hello World!", received);
  12566. #else
  12567. EXPECT_FALSE(handle.is_valid());
  12568. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12569. #endif
  12570. }
  12571. {
  12572. // A differently-cased coding must not be mistaken for an unknown one, or
  12573. // the body would be handed back still compressed.
  12574. auto res = cli.Get("/gzipped-uppercase");
  12575. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12577. EXPECT_EQ("Hello World!", res->body);
  12578. #else
  12579. ASSERT_FALSE(res);
  12580. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12581. #endif
  12582. }
  12583. }
  12584. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12585. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12586. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12587. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12588. // body a second time and appending a second Content-Encoding field line, so
  12589. // clients that decode one coding per listed value handed back raw gzip bytes.
  12590. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12591. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12592. Server svr;
  12593. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12594. // keeps the server from applying a coding of its own.
  12595. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12596. res.set_content(gzipped, "text/plain");
  12597. res.set_header("Content-Encoding", "gzip");
  12598. });
  12599. auto port = svr.bind_to_any_port(HOST);
  12600. thread t = thread([&]() { svr.listen_after_bind(); });
  12601. auto se = detail::scope_exit([&] {
  12602. svr.stop();
  12603. t.join();
  12604. ASSERT_FALSE(svr.is_running());
  12605. });
  12606. svr.wait_until_ready();
  12607. Client cli(HOST, port);
  12608. Headers headers = {{"Accept-Encoding", "gzip"}};
  12609. auto res = cli.Get("/pre-gzipped", headers);
  12610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12611. EXPECT_EQ(StatusCode::OK_200, res->status);
  12612. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12613. EXPECT_EQ("Hello World!", res->body);
  12614. }
  12615. // set_compress(false) sends every handler response as it is, buffered or
  12616. // streamed
  12617. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12618. const std::string text(1000, 'a');
  12619. Server svr;
  12620. svr.set_compress(false);
  12621. svr.Get("/buffered", [&](const Request &, Response &res) {
  12622. res.set_content(text, "text/plain");
  12623. });
  12624. svr.Get("/streamed", [&](const Request &, Response &res) {
  12625. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12626. sink.write(text.data(), text.size());
  12627. sink.done();
  12628. return true;
  12629. });
  12630. });
  12631. auto port = svr.bind_to_any_port(HOST);
  12632. ASSERT_LT(0, port);
  12633. thread t = thread([&] { svr.listen_after_bind(); });
  12634. auto se = detail::scope_exit([&] {
  12635. svr.stop();
  12636. t.join();
  12637. ASSERT_FALSE(svr.is_running());
  12638. });
  12639. svr.wait_until_ready();
  12640. Client cli(HOST, port);
  12641. cli.set_decompress(false);
  12642. for (auto path : {"/buffered", "/streamed"}) {
  12643. SCOPED_TRACE(path);
  12644. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12646. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12647. EXPECT_EQ(text, res->body);
  12648. }
  12649. }
  12650. // A chunked provider settles its coding where the headers are written and
  12651. // reuses it at write time. Both ends of that have to hold: a handler's own
  12652. // Content-Encoding suppresses the coding, and a response without one is still
  12653. // compressed as it always was.
  12654. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12655. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12656. const std::string plain = "Hello World! Hello World! Hello World!";
  12657. Server svr;
  12658. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12659. res.set_header("Content-Encoding", "gzip");
  12660. res.set_chunked_content_provider(
  12661. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12662. sink.write(gzipped.data(), gzipped.size());
  12663. sink.done();
  12664. return true;
  12665. });
  12666. });
  12667. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12668. res.set_chunked_content_provider(
  12669. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12670. sink.write(plain.data(), plain.size());
  12671. sink.done();
  12672. return true;
  12673. });
  12674. });
  12675. auto port = svr.bind_to_any_port(HOST);
  12676. thread t = thread([&]() { svr.listen_after_bind(); });
  12677. auto se = detail::scope_exit([&] {
  12678. svr.stop();
  12679. t.join();
  12680. ASSERT_FALSE(svr.is_running());
  12681. });
  12682. svr.wait_until_ready();
  12683. Client cli(HOST, port);
  12684. Headers headers = {{"Accept-Encoding", "gzip"}};
  12685. {
  12686. auto res = cli.Get("/pre-gzipped", headers);
  12687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12688. EXPECT_EQ(StatusCode::OK_200, res->status);
  12689. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12690. EXPECT_EQ("Hello World!", res->body);
  12691. }
  12692. {
  12693. auto res = cli.Get("/negotiated", headers);
  12694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12695. EXPECT_EQ(StatusCode::OK_200, res->status);
  12696. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12697. EXPECT_EQ(plain, res->body);
  12698. }
  12699. }
  12700. #endif
  12701. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12702. // the same message as the comma-joined one, so both have to be read the same
  12703. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12704. // single gzip coding, and a body the sender says was encoded twice was handed
  12705. // back after one pass, still compressed but presented as decoded.
  12706. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12707. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12708. Server svr;
  12709. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12710. res.set_content(body, "image/jpeg");
  12711. res.headers.emplace("Content-Encoding", "gzip");
  12712. res.headers.emplace("Content-Encoding", "gzip");
  12713. });
  12714. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12715. res.set_content(body, "image/jpeg");
  12716. res.set_header("Content-Encoding", "gzip, gzip");
  12717. });
  12718. auto port = svr.bind_to_any_port(HOST);
  12719. thread t = thread([&]() { svr.listen_after_bind(); });
  12720. auto se = detail::scope_exit([&] {
  12721. svr.stop();
  12722. t.join();
  12723. ASSERT_FALSE(svr.is_running());
  12724. });
  12725. svr.wait_until_ready();
  12726. Client cli(HOST, port);
  12727. // Two codings is not something cpp-httplib decodes, so both representations
  12728. // take the pass-through path rather than one of them being gunzipped once.
  12729. for (const char *path : {"/split", "/joined"}) {
  12730. auto res = cli.Get(path);
  12731. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12732. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12733. EXPECT_EQ(body, res->body) << path;
  12734. }
  12735. }
  12736. // Regression test for DoS vulnerability: a malicious server sending a response
  12737. // without Content-Length header must not cause unbounded memory consumption on
  12738. // the client side. The client should stop reading after a reasonable limit,
  12739. // similar to the server-side set_payload_max_length protection.
  12740. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12741. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12742. #ifndef _WIN32
  12743. signal(SIGPIPE, SIG_IGN);
  12744. #endif
  12745. auto server_thread = std::thread([] {
  12746. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12747. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12748. default_socket_options(srv);
  12749. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12750. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12751. sockaddr_in addr{};
  12752. addr.sin_family = AF_INET;
  12753. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12754. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12755. int opt = 1;
  12756. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12757. #ifdef _WIN32
  12758. reinterpret_cast<const char *>(&opt),
  12759. #else
  12760. &opt,
  12761. #endif
  12762. sizeof(opt));
  12763. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12764. ::listen(srv, 1);
  12765. sockaddr_in cli_addr{};
  12766. socklen_t cli_len = sizeof(cli_addr);
  12767. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12768. if (cli != INVALID_SOCKET) {
  12769. char buf[4096];
  12770. ::recv(cli, buf, sizeof(buf), 0);
  12771. // Malicious response: no Content-Length, no chunked encoding
  12772. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12773. "Connection: close\r\n"
  12774. "\r\n";
  12775. ::send(cli,
  12776. #ifdef _WIN32
  12777. static_cast<const char *>(response_header.c_str()),
  12778. static_cast<int>(response_header.size()),
  12779. #else
  12780. response_header.c_str(), response_header.size(),
  12781. #endif
  12782. 0);
  12783. // Send 10MB of data
  12784. std::string chunk(64 * 1024, 'A');
  12785. size_t total_sent = 0;
  12786. while (total_sent < MALICIOUS_DATA_SIZE) {
  12787. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12788. auto sent = ::send(cli,
  12789. #ifdef _WIN32
  12790. static_cast<const char *>(chunk.c_str()),
  12791. static_cast<int>(to_send),
  12792. #else
  12793. chunk.c_str(), to_send,
  12794. #endif
  12795. 0);
  12796. if (sent <= 0) break;
  12797. total_sent += static_cast<size_t>(sent);
  12798. }
  12799. detail::close_socket(cli);
  12800. }
  12801. detail::close_socket(srv);
  12802. });
  12803. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12804. size_t total_read = 0;
  12805. {
  12806. Client cli("127.0.0.1", PORT + 2);
  12807. cli.set_read_timeout(5, 0);
  12808. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12809. auto stream = cli.open_stream("GET", "/malicious");
  12810. ASSERT_TRUE(stream.is_valid());
  12811. char buffer[64 * 1024];
  12812. ssize_t n;
  12813. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12814. total_read += static_cast<size_t>(n);
  12815. }
  12816. } // StreamHandle and Client destroyed here, closing the socket
  12817. server_thread.join();
  12818. // With set_payload_max_length, the client must stop reading before consuming
  12819. // all 10MB. The read loop should be cut off at or near the configured limit.
  12820. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12821. << "Client read " << total_read << " bytes, exceeding the configured "
  12822. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12823. }
  12824. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12825. // the entire response body without truncation.
  12826. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12827. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12828. #ifndef _WIN32
  12829. signal(SIGPIPE, SIG_IGN);
  12830. #endif
  12831. auto server_thread = std::thread([] {
  12832. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12833. default_socket_options(srv);
  12834. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12835. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12836. sockaddr_in addr{};
  12837. addr.sin_family = AF_INET;
  12838. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12839. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12840. int opt = 1;
  12841. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12842. #ifdef _WIN32
  12843. reinterpret_cast<const char *>(&opt),
  12844. #else
  12845. &opt,
  12846. #endif
  12847. sizeof(opt));
  12848. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12849. ::listen(srv, 1);
  12850. sockaddr_in cli_addr{};
  12851. socklen_t cli_len = sizeof(cli_addr);
  12852. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12853. if (cli != INVALID_SOCKET) {
  12854. char buf[4096];
  12855. ::recv(cli, buf, sizeof(buf), 0);
  12856. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12857. "Connection: close\r\n"
  12858. "\r\n";
  12859. ::send(cli,
  12860. #ifdef _WIN32
  12861. static_cast<const char *>(response_header.c_str()),
  12862. static_cast<int>(response_header.size()),
  12863. #else
  12864. response_header.c_str(), response_header.size(),
  12865. #endif
  12866. 0);
  12867. std::string chunk(64 * 1024, 'A');
  12868. size_t total_sent = 0;
  12869. while (total_sent < DATA_SIZE) {
  12870. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12871. auto sent = ::send(cli,
  12872. #ifdef _WIN32
  12873. static_cast<const char *>(chunk.c_str()),
  12874. static_cast<int>(to_send),
  12875. #else
  12876. chunk.c_str(), to_send,
  12877. #endif
  12878. 0);
  12879. if (sent <= 0) break;
  12880. total_sent += static_cast<size_t>(sent);
  12881. }
  12882. #ifdef _WIN32
  12883. ::shutdown(cli, SD_SEND);
  12884. #else
  12885. ::shutdown(cli, SHUT_WR);
  12886. #endif
  12887. // Drain until the client closes its end, ensuring all data is delivered
  12888. char drain[1024];
  12889. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12890. detail::close_socket(cli);
  12891. }
  12892. detail::close_socket(srv);
  12893. });
  12894. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12895. size_t total_read = 0;
  12896. {
  12897. Client cli("127.0.0.1", PORT + 2);
  12898. cli.set_read_timeout(5, 0);
  12899. cli.set_payload_max_length(0); // 0 means no limit
  12900. auto stream = cli.open_stream("GET", "/data");
  12901. ASSERT_TRUE(stream.is_valid());
  12902. char buffer[64 * 1024];
  12903. ssize_t n;
  12904. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12905. total_read += static_cast<size_t>(n);
  12906. }
  12907. }
  12908. server_thread.join();
  12909. EXPECT_EQ(total_read, DATA_SIZE)
  12910. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12911. << " bytes without truncation, but only read " << total_read << " bytes.";
  12912. }
  12913. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12914. // enormous Content-Length must not cause the client to pre-allocate a huge
  12915. // response body buffer. The reservation is capped at payload_max_length_, and
  12916. // the read itself fails when the body exceeds the limit.
  12917. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12918. #ifndef _WIN32
  12919. signal(SIGPIPE, SIG_IGN);
  12920. #endif
  12921. auto server_thread = std::thread([] {
  12922. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12923. default_socket_options(srv);
  12924. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12925. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12926. sockaddr_in addr{};
  12927. addr.sin_family = AF_INET;
  12928. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12929. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12930. int opt = 1;
  12931. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12932. #ifdef _WIN32
  12933. reinterpret_cast<const char *>(&opt),
  12934. #else
  12935. &opt,
  12936. #endif
  12937. sizeof(opt));
  12938. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12939. ::listen(srv, 1);
  12940. sockaddr_in cli_addr{};
  12941. socklen_t cli_len = sizeof(cli_addr);
  12942. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12943. if (cli != INVALID_SOCKET) {
  12944. char buf[4096];
  12945. ::recv(cli, buf, sizeof(buf), 0);
  12946. // Malicious response: claim a 20GB body but send only a tiny payload.
  12947. std::string response = "HTTP/1.1 200 OK\r\n"
  12948. "Content-Length: 20000000000\r\n"
  12949. "\r\n"
  12950. "abc";
  12951. ::send(cli,
  12952. #ifdef _WIN32
  12953. static_cast<const char *>(response.c_str()),
  12954. static_cast<int>(response.size()),
  12955. #else
  12956. response.c_str(), response.size(),
  12957. #endif
  12958. 0);
  12959. detail::close_socket(cli);
  12960. }
  12961. detail::close_socket(srv);
  12962. });
  12963. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12964. {
  12965. Client cli("127.0.0.1", PORT + 2);
  12966. cli.set_read_timeout(5, 0);
  12967. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12968. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12969. // (server claims more bytes than payload_max_length permits), but it must
  12970. // not exhaust memory before getting there.
  12971. auto res = cli.Get("/malicious");
  12972. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12973. }
  12974. server_thread.join();
  12975. }
  12976. // Verify that content_receiver bypasses the default payload_max_length,
  12977. // allowing streaming downloads larger than 100MB without requiring an explicit
  12978. // set_payload_max_length call.
  12979. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12980. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12981. #ifndef _WIN32
  12982. signal(SIGPIPE, SIG_IGN);
  12983. #endif
  12984. auto server_thread = std::thread([] {
  12985. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12986. default_socket_options(srv);
  12987. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12988. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12989. sockaddr_in addr{};
  12990. addr.sin_family = AF_INET;
  12991. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12992. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12993. int opt = 1;
  12994. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12995. #ifdef _WIN32
  12996. reinterpret_cast<const char *>(&opt),
  12997. #else
  12998. &opt,
  12999. #endif
  13000. sizeof(opt));
  13001. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13002. ::listen(srv, 1);
  13003. sockaddr_in cli_addr{};
  13004. socklen_t cli_len = sizeof(cli_addr);
  13005. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13006. if (cli != INVALID_SOCKET) {
  13007. char buf[4096];
  13008. ::recv(cli, buf, sizeof(buf), 0);
  13009. // Response with Content-Length larger than default 100MB limit
  13010. auto content_length = std::to_string(DATA_SIZE);
  13011. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13012. "Content-Length: " +
  13013. content_length +
  13014. "\r\n"
  13015. "Connection: close\r\n"
  13016. "\r\n";
  13017. ::send(cli,
  13018. #ifdef _WIN32
  13019. static_cast<const char *>(response_header.c_str()),
  13020. static_cast<int>(response_header.size()),
  13021. #else
  13022. response_header.c_str(), response_header.size(),
  13023. #endif
  13024. 0);
  13025. std::string chunk(64 * 1024, 'A');
  13026. size_t total_sent = 0;
  13027. while (total_sent < DATA_SIZE) {
  13028. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13029. auto sent = ::send(cli,
  13030. #ifdef _WIN32
  13031. static_cast<const char *>(chunk.c_str()),
  13032. static_cast<int>(to_send),
  13033. #else
  13034. chunk.c_str(), to_send,
  13035. #endif
  13036. 0);
  13037. if (sent <= 0) break;
  13038. total_sent += static_cast<size_t>(sent);
  13039. }
  13040. detail::close_socket(cli);
  13041. }
  13042. detail::close_socket(srv);
  13043. });
  13044. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13045. size_t total_received = 0;
  13046. {
  13047. Client cli("127.0.0.1", PORT + 2);
  13048. cli.set_read_timeout(10, 0);
  13049. // Do NOT call set_payload_max_length — use the default 100MB limit
  13050. auto res =
  13051. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13052. total_received += data_length;
  13053. return true;
  13054. });
  13055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13056. EXPECT_EQ(StatusCode::OK_200, res->status);
  13057. }
  13058. server_thread.join();
  13059. EXPECT_EQ(total_received, DATA_SIZE)
  13060. << "With content_receiver, the client should read all " << DATA_SIZE
  13061. << " bytes despite the default 100MB payload_max_length, but only read "
  13062. << total_received << " bytes.";
  13063. }
  13064. // Verify that an explicit set_payload_max_length smaller than the response is
  13065. // enforced even when a content_receiver is used.
  13066. TEST(ClientVulnerabilityTest,
  13067. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13068. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13069. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13070. #ifndef _WIN32
  13071. signal(SIGPIPE, SIG_IGN);
  13072. #endif
  13073. auto server_thread = std::thread([] {
  13074. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13075. default_socket_options(srv);
  13076. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13077. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13078. sockaddr_in addr{};
  13079. addr.sin_family = AF_INET;
  13080. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13081. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13082. int opt = 1;
  13083. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13084. #ifdef _WIN32
  13085. reinterpret_cast<const char *>(&opt),
  13086. #else
  13087. &opt,
  13088. #endif
  13089. sizeof(opt));
  13090. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13091. ::listen(srv, 1);
  13092. sockaddr_in cli_addr{};
  13093. socklen_t cli_len = sizeof(cli_addr);
  13094. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13095. if (cli != INVALID_SOCKET) {
  13096. char buf[4096];
  13097. ::recv(cli, buf, sizeof(buf), 0);
  13098. auto content_length = std::to_string(DATA_SIZE);
  13099. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13100. "Content-Length: " +
  13101. content_length +
  13102. "\r\n"
  13103. "Connection: close\r\n"
  13104. "\r\n";
  13105. ::send(cli,
  13106. #ifdef _WIN32
  13107. static_cast<const char *>(response_header.c_str()),
  13108. static_cast<int>(response_header.size()),
  13109. #else
  13110. response_header.c_str(), response_header.size(),
  13111. #endif
  13112. 0);
  13113. std::string chunk(64 * 1024, 'A');
  13114. size_t total_sent = 0;
  13115. while (total_sent < DATA_SIZE) {
  13116. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13117. auto sent = ::send(cli,
  13118. #ifdef _WIN32
  13119. static_cast<const char *>(chunk.c_str()),
  13120. static_cast<int>(to_send),
  13121. #else
  13122. chunk.c_str(), to_send,
  13123. #endif
  13124. 0);
  13125. if (sent <= 0) break;
  13126. total_sent += static_cast<size_t>(sent);
  13127. }
  13128. detail::close_socket(cli);
  13129. }
  13130. detail::close_socket(srv);
  13131. });
  13132. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13133. size_t total_received = 0;
  13134. {
  13135. Client cli("127.0.0.1", PORT + 2);
  13136. cli.set_read_timeout(10, 0);
  13137. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13138. auto res =
  13139. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13140. total_received += data_length;
  13141. return true;
  13142. });
  13143. // Should fail because 200MB exceeds the explicit 150MB limit
  13144. EXPECT_FALSE(res);
  13145. }
  13146. server_thread.join();
  13147. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13148. << "Client with content_receiver should respect the explicit "
  13149. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13150. << total_received << " bytes.";
  13151. }
  13152. // Verify that an explicit set_payload_max_length larger than the response
  13153. // allows the content_receiver to read all data successfully.
  13154. TEST(ClientVulnerabilityTest,
  13155. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13156. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13157. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13158. #ifndef _WIN32
  13159. signal(SIGPIPE, SIG_IGN);
  13160. #endif
  13161. auto server_thread = std::thread([] {
  13162. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13163. default_socket_options(srv);
  13164. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13165. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13166. sockaddr_in addr{};
  13167. addr.sin_family = AF_INET;
  13168. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13169. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13170. int opt = 1;
  13171. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13172. #ifdef _WIN32
  13173. reinterpret_cast<const char *>(&opt),
  13174. #else
  13175. &opt,
  13176. #endif
  13177. sizeof(opt));
  13178. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13179. ::listen(srv, 1);
  13180. sockaddr_in cli_addr{};
  13181. socklen_t cli_len = sizeof(cli_addr);
  13182. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13183. if (cli != INVALID_SOCKET) {
  13184. char buf[4096];
  13185. ::recv(cli, buf, sizeof(buf), 0);
  13186. auto content_length = std::to_string(DATA_SIZE);
  13187. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13188. "Content-Length: " +
  13189. content_length +
  13190. "\r\n"
  13191. "Connection: close\r\n"
  13192. "\r\n";
  13193. ::send(cli,
  13194. #ifdef _WIN32
  13195. static_cast<const char *>(response_header.c_str()),
  13196. static_cast<int>(response_header.size()),
  13197. #else
  13198. response_header.c_str(), response_header.size(),
  13199. #endif
  13200. 0);
  13201. std::string chunk(64 * 1024, 'A');
  13202. size_t total_sent = 0;
  13203. while (total_sent < DATA_SIZE) {
  13204. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13205. auto sent = ::send(cli,
  13206. #ifdef _WIN32
  13207. static_cast<const char *>(chunk.c_str()),
  13208. static_cast<int>(to_send),
  13209. #else
  13210. chunk.c_str(), to_send,
  13211. #endif
  13212. 0);
  13213. if (sent <= 0) break;
  13214. total_sent += static_cast<size_t>(sent);
  13215. }
  13216. #ifdef _WIN32
  13217. ::shutdown(cli, SD_SEND);
  13218. #else
  13219. ::shutdown(cli, SHUT_WR);
  13220. #endif
  13221. char drain[1024];
  13222. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13223. detail::close_socket(cli);
  13224. }
  13225. detail::close_socket(srv);
  13226. });
  13227. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13228. size_t total_received = 0;
  13229. {
  13230. Client cli("127.0.0.1", PORT + 2);
  13231. cli.set_read_timeout(10, 0);
  13232. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13233. auto res =
  13234. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13235. total_received += data_length;
  13236. return true;
  13237. });
  13238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13239. EXPECT_EQ(StatusCode::OK_200, res->status);
  13240. }
  13241. server_thread.join();
  13242. EXPECT_EQ(total_received, DATA_SIZE)
  13243. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13244. << " bytes (larger than " << DATA_SIZE
  13245. << " bytes response), content_receiver should read all data, but only "
  13246. "read "
  13247. << total_received << " bytes.";
  13248. }
  13249. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13250. // Regression test for "zip bomb" attack on the client side: a malicious server
  13251. // sends a small gzip-compressed response that decompresses to a huge payload.
  13252. // The client must enforce payload_max_length on the decompressed size.
  13253. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13254. constexpr size_t DECOMPRESSED_SIZE =
  13255. 10 * 1024 * 1024; // 10MB after decompression
  13256. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13257. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13258. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13259. std::string compressed;
  13260. {
  13261. httplib::detail::gzip_compressor compressor;
  13262. bool ok =
  13263. compressor.compress(uncompressed.data(), uncompressed.size(),
  13264. /*last=*/true, [&](const char *buf, size_t len) {
  13265. compressed.append(buf, len);
  13266. return true;
  13267. });
  13268. ASSERT_TRUE(ok);
  13269. }
  13270. // Sanity: compressed data should be much smaller than the decompressed size
  13271. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13272. #ifndef _WIN32
  13273. signal(SIGPIPE, SIG_IGN);
  13274. #endif
  13275. // Set up the listening socket in the main thread so the server is guaranteed
  13276. // to be ready before the client connects (eliminates race condition).
  13277. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13278. default_socket_options(srv);
  13279. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13280. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13281. sockaddr_in addr{};
  13282. addr.sin_family = AF_INET;
  13283. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13284. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13285. int opt = 1;
  13286. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13287. #ifdef _WIN32
  13288. reinterpret_cast<const char *>(&opt),
  13289. #else
  13290. &opt,
  13291. #endif
  13292. sizeof(opt));
  13293. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13294. ASSERT_EQ(0, ::listen(srv, 1));
  13295. auto server_thread = std::thread([&compressed, srv] {
  13296. sockaddr_in cli_addr{};
  13297. socklen_t cli_len = sizeof(cli_addr);
  13298. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13299. if (cli != INVALID_SOCKET) {
  13300. // Read the full HTTP request (until \r\n\r\n)
  13301. char buf[4096];
  13302. size_t total = 0;
  13303. while (total < sizeof(buf)) {
  13304. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13305. if (n <= 0) break;
  13306. total += static_cast<size_t>(n);
  13307. // Check for end of headers
  13308. if (total >= 4) {
  13309. std::string req(buf, total);
  13310. if (req.find("\r\n\r\n") != std::string::npos) break;
  13311. }
  13312. }
  13313. // Malicious response: gzip-compressed body, no Content-Length
  13314. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13315. "Content-Encoding: gzip\r\n"
  13316. "Connection: close\r\n"
  13317. "\r\n";
  13318. ::send(cli,
  13319. #ifdef _WIN32
  13320. static_cast<const char *>(response_header.c_str()),
  13321. static_cast<int>(response_header.size()),
  13322. #else
  13323. response_header.c_str(), response_header.size(),
  13324. #endif
  13325. 0);
  13326. // Send the compressed payload (small on the wire, huge when decompressed)
  13327. size_t total_sent = 0;
  13328. while (total_sent < compressed.size()) {
  13329. auto to_send = std::min(compressed.size() - total_sent,
  13330. static_cast<size_t>(64 * 1024));
  13331. auto sent =
  13332. ::send(cli,
  13333. #ifdef _WIN32
  13334. static_cast<const char *>(compressed.c_str() + total_sent),
  13335. static_cast<int>(to_send),
  13336. #else
  13337. compressed.c_str() + total_sent, to_send,
  13338. #endif
  13339. 0);
  13340. if (sent <= 0) break;
  13341. total_sent += static_cast<size_t>(sent);
  13342. }
  13343. detail::close_socket(cli);
  13344. }
  13345. });
  13346. auto se = detail::scope_exit([&] {
  13347. detail::close_socket(srv);
  13348. server_thread.join();
  13349. });
  13350. size_t total_decompressed = 0;
  13351. {
  13352. Client cli("127.0.0.1", PORT + 3);
  13353. cli.set_read_timeout(5, 0);
  13354. cli.set_decompress(true);
  13355. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13356. auto stream = cli.open_stream("GET", "/zipbomb");
  13357. ASSERT_TRUE(stream.is_valid());
  13358. char buffer[64 * 1024];
  13359. ssize_t n;
  13360. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13361. total_decompressed += static_cast<size_t>(n);
  13362. }
  13363. }
  13364. // The decompressed size must be capped by payload_max_length. Without
  13365. // protection, the client would decompress the full 10MB from a tiny
  13366. // compressed payload, enabling a zip bomb DoS attack.
  13367. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13368. << "Client decompressed " << total_decompressed
  13369. << " bytes from a gzip response. The decompressed size should be "
  13370. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13371. }
  13372. #endif
  13373. TEST(HostAndPortPropertiesTest, NoSSL) {
  13374. httplib::Client cli("www.google.com", 1234);
  13375. ASSERT_EQ("www.google.com", cli.host());
  13376. ASSERT_EQ(1234, cli.port());
  13377. }
  13378. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13379. httplib::Client cli("www.google.com:1234");
  13380. ASSERT_EQ("www.google.com", cli.host());
  13381. ASSERT_EQ(1234, cli.port());
  13382. }
  13383. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13384. // Port number that overflows int — should not crash, client becomes invalid
  13385. httplib::Client cli("http://www.google.com:99999999999999999999");
  13386. ASSERT_FALSE(cli.is_valid());
  13387. }
  13388. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13389. // Port 99999 exceeds valid range (1-65535) — should not crash
  13390. httplib::Client cli("http://www.google.com:99999");
  13391. ASSERT_FALSE(cli.is_valid());
  13392. auto res = cli.Get("/");
  13393. EXPECT_FALSE(res);
  13394. EXPECT_EQ(Error::Connection, res.error());
  13395. }
  13396. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13397. httplib::Client cli("http://user:pass@localhost:1234");
  13398. ASSERT_FALSE(cli.is_valid());
  13399. EXPECT_FALSE(cli.Get("/"));
  13400. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13401. }
  13402. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13403. httplib::Client cli("http://www.google.com:80abc");
  13404. ASSERT_FALSE(cli.is_valid());
  13405. }
  13406. #ifdef CPPHTTPLIB_SSL_ENABLED
  13407. TEST(HostAndPortPropertiesTest, SSL) {
  13408. httplib::SSLClient cli("www.google.com");
  13409. ASSERT_EQ("www.google.com", cli.host());
  13410. ASSERT_EQ(443, cli.port());
  13411. }
  13412. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13413. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13414. std::string cert;
  13415. read_file(CA_CERT_FILE, cert);
  13416. httplib::SSLClient httplib_client("www.google.com");
  13417. // Load CA store first time
  13418. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13419. // Load CA store second time (update)
  13420. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13421. // Verify client is still valid and can make connections
  13422. httplib_client.enable_server_certificate_verification(true);
  13423. auto res = httplib_client.Get("/");
  13424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13425. // Google may return 200 or 301 depending on various factors
  13426. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13427. res->status == StatusCode::MovedPermanently_301);
  13428. }
  13429. TEST(SSLClientTest, ServerNameIndication_Online) {
  13430. auto host = "httpbingo.org";
  13431. auto path = std::string{"/get"};
  13432. SSLClient cli(host, 443);
  13433. auto res = cli.Get(path);
  13434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13435. ASSERT_EQ(StatusCode::OK_200, res->status);
  13436. }
  13437. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13438. // Use a site that will cause SSL verification failure due to self-signed cert
  13439. SSLClient cli("self-signed.badssl.com", 443);
  13440. cli.enable_server_certificate_verification(true);
  13441. auto res = cli.Get("/");
  13442. ASSERT_TRUE(!res);
  13443. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13444. // Verify backend error is captured for SSLServerVerification
  13445. // This occurs when certificate verification fails
  13446. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13447. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13448. EXPECT_NE(0UL, res.ssl_backend_error());
  13449. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13450. res.ssl_error());
  13451. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13452. #if !defined(_WIN32) || \
  13453. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13454. // On non-Windows or when Windows Schannel is disabled, the error comes
  13455. // from OpenSSL's verification
  13456. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13457. res.ssl_backend_error());
  13458. #endif
  13459. #endif
  13460. }
  13461. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13462. // Use a site where hostname doesn't match the certificate
  13463. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13464. SSLClient cli("wrong.host.badssl.com", 443);
  13465. cli.enable_server_certificate_verification(true);
  13466. cli.enable_server_hostname_verification(true);
  13467. auto res = cli.Get("/");
  13468. ASSERT_TRUE(!res);
  13469. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13470. // Verify backend error is captured for hostname verification failure
  13471. EXPECT_NE(0UL, res.ssl_backend_error());
  13472. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13473. res.ssl_error());
  13474. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13475. #if !defined(_WIN32) || \
  13476. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13477. // On non-Windows or when Windows Schannel is disabled, the error comes
  13478. // from OpenSSL's hostname verification
  13479. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13480. res.ssl_backend_error());
  13481. #endif
  13482. #endif
  13483. }
  13484. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13485. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13486. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13487. SSLClient cli("www.google.com", 443);
  13488. cli.enable_server_certificate_verification(true);
  13489. auto res = cli.Get("/");
  13490. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13491. }
  13492. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13493. SSLClient cli("www.google.com", 443);
  13494. cli.enable_server_certificate_verification(true);
  13495. cli.enable_windows_certificate_verification(false);
  13496. auto res = cli.Get("/");
  13497. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13498. }
  13499. // The server sends an intermediate cross-signed by a root Windows trusts,
  13500. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13501. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13502. SSLClient cli("accounts.spotify.com", 443);
  13503. auto res = cli.Get("/");
  13504. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13505. << " ssl_backend_error=" << res.ssl_backend_error();
  13506. }
  13507. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13508. // policy status, which no backend reports for a self-signed certificate.
  13509. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13510. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13511. ASSERT_TRUE(svr.is_valid());
  13512. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13513. auto se = detail::scope_exit([&] {
  13514. svr.stop();
  13515. t.join();
  13516. ASSERT_FALSE(svr.is_running());
  13517. });
  13518. svr.wait_until_ready();
  13519. SSLClient cli("127.0.0.1", PORT);
  13520. cli.set_connection_timeout(30);
  13521. auto res = cli.Get("/");
  13522. ASSERT_FALSE(res);
  13523. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13524. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13525. }
  13526. #endif
  13527. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13528. Client cli("https://google.com");
  13529. auto res = cli.Get("/");
  13530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13531. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13532. }
  13533. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13534. SSLClient cli("google.com");
  13535. cli.set_ca_cert_path(CA_CERT_FILE);
  13536. auto res = cli.Get("/");
  13537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13538. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13539. }
  13540. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13541. SSLClient cli("google.com");
  13542. cli.enable_server_certificate_verification(true);
  13543. cli.set_ca_cert_path("hello");
  13544. auto res = cli.Get("/");
  13545. ASSERT_TRUE(!res);
  13546. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13547. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13548. // should be set
  13549. EXPECT_EQ(0, res.ssl_error());
  13550. // Verify backend error is captured for SSLLoadingCerts
  13551. // This error occurs when loading CA certificates fails
  13552. EXPECT_NE(0UL, res.ssl_backend_error());
  13553. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13554. // OpenSSL specific error codes:
  13555. // > openssl errstr 0x80000002
  13556. // error:80000002:system library::No such file or directory
  13557. // > openssl errstr 0xA000126
  13558. // error:0A000126:SSL routines::unexpected eof while reading
  13559. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13560. res.ssl_backend_error() == 0xA000126);
  13561. #endif
  13562. }
  13563. TEST(SSLClientTest, ServerCertificateVerification4) {
  13564. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13565. ASSERT_TRUE(svr.is_valid());
  13566. svr.Get("/test", [&](const Request &, Response &res) {
  13567. res.set_content("test", "text/plain");
  13568. svr.stop();
  13569. ASSERT_TRUE(true);
  13570. });
  13571. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13572. auto se = detail::scope_exit([&] {
  13573. t.join();
  13574. ASSERT_FALSE(svr.is_running());
  13575. });
  13576. svr.wait_until_ready();
  13577. SSLClient cli("127.0.0.1", PORT);
  13578. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13579. cli.enable_server_certificate_verification(true);
  13580. cli.set_connection_timeout(30);
  13581. auto res = cli.Get("/test");
  13582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13583. ASSERT_EQ(StatusCode::OK_200, res->status);
  13584. }
  13585. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13586. std::string cert;
  13587. read_file(CA_CERT_FILE, cert);
  13588. SSLClient cli("google.com");
  13589. cli.load_ca_cert_store(cert.data(), cert.size());
  13590. const auto res = cli.Get("/");
  13591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13592. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13593. }
  13594. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13595. // clang-format off
  13596. static constexpr char cert[] =
  13597. "GlobalSign Root CA\n"
  13598. "==================\n"
  13599. "-----BEGIN CERTIFICATE-----\n"
  13600. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13601. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13602. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13603. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13604. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13605. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13606. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13607. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13608. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13609. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13610. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13611. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13612. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13613. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13614. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13615. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13616. "-----END CERTIFICATE-----\n";
  13617. // clang-format on
  13618. SSLClient cli("google.com");
  13619. cli.load_ca_cert_store(cert, sizeof(cert));
  13620. const auto res = cli.Get("/");
  13621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13622. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13623. }
  13624. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13625. SSLClient cli("www.youtube.com");
  13626. cli.set_ca_cert_path(CA_CERT_FILE);
  13627. cli.enable_server_certificate_verification(true);
  13628. cli.set_follow_location(true);
  13629. auto res = cli.Get("/");
  13630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13631. ASSERT_EQ(StatusCode::OK_200, res->status);
  13632. }
  13633. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13634. SSLClient cli("wWw.YouTube.Com");
  13635. cli.set_ca_cert_path(CA_CERT_FILE);
  13636. cli.enable_server_certificate_verification(true);
  13637. cli.enable_server_hostname_verification(true);
  13638. cli.set_follow_location(true);
  13639. auto res = cli.Get("/");
  13640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13641. ASSERT_EQ(StatusCode::OK_200, res->status);
  13642. }
  13643. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13644. SSLClient cli("gOoGlE.COm");
  13645. cli.enable_server_certificate_verification(true);
  13646. cli.enable_server_hostname_verification(true);
  13647. cli.set_follow_location(true);
  13648. auto res = cli.Get("/");
  13649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13650. ASSERT_EQ(StatusCode::OK_200, res->status);
  13651. }
  13652. TEST(SSLClientTest, Issue2004_Online) {
  13653. Client client("https://google.com");
  13654. client.set_follow_location(true);
  13655. auto res = client.Get("/");
  13656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13657. ASSERT_EQ(StatusCode::OK_200, res->status);
  13658. auto body = res->body;
  13659. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13660. }
  13661. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13662. // Create SSLClient with invalid cert/key to make is_valid() return false
  13663. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13664. "nonexistent_key.pem");
  13665. // is_valid() should be false due to cert loading failure
  13666. ASSERT_FALSE(cli.is_valid());
  13667. auto res = cli.Get("/");
  13668. ASSERT_FALSE(res);
  13669. EXPECT_EQ(Error::SSLConnection, res.error());
  13670. }
  13671. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13672. // Test for Issue #2251: SSL error not properly reported when client cert
  13673. // and key paths are swapped or mismatched
  13674. // This simulates the scenario where user accidentally swaps the cert and key
  13675. // files
  13676. // Using client cert file as private key and vice versa (completely wrong)
  13677. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13678. // Should fail validation due to cert/key mismatch
  13679. ASSERT_FALSE(cli.is_valid());
  13680. // Attempt to make a request should fail with proper error
  13681. auto res = cli.Get("/");
  13682. ASSERT_FALSE(res);
  13683. EXPECT_EQ(Error::SSLConnection, res.error());
  13684. // SSL error should be recorded in the Result object (this is the key fix for
  13685. // Issue #2251)
  13686. auto backend_error = res.ssl_backend_error();
  13687. EXPECT_NE(0u, backend_error);
  13688. }
  13689. // Tests cert/key mismatch detection at the TLS context level
  13690. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13691. // Test that using mismatched cert/key causes connection failure.
  13692. // We verify this at the SSLClient level rather than through internal
  13693. // TLS API functions.
  13694. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13695. cli.enable_server_certificate_verification(false);
  13696. cli.set_connection_timeout(2);
  13697. // The mismatch should cause a connection or handshake error
  13698. auto res = cli.Get("/test");
  13699. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13700. // Either way, the request should fail
  13701. EXPECT_FALSE(res);
  13702. }
  13703. #endif
  13704. #if 0
  13705. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13706. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13707. ASSERT_TRUE(cli != nullptr);
  13708. cli->set_address_family(AF_INET6);
  13709. cli->set_interface("en0");
  13710. auto res = cli->Get("/get");
  13711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13712. ASSERT_EQ(StatusCode::OK_200, res->status);
  13713. }
  13714. #endif
  13715. // Client certificate tests - work with all TLS backends
  13716. #ifdef CPPHTTPLIB_SSL_ENABLED
  13717. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13718. void ClientCertPresent(
  13719. const std::string &client_cert_file,
  13720. const std::string &client_private_key_file,
  13721. const std::string &client_encrypted_private_key_pass = std::string(),
  13722. const ClientCertServerSetup &setup = nullptr) {
  13723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13724. ASSERT_TRUE(svr.is_valid());
  13725. if (setup) { setup(svr); }
  13726. svr.Get("/test", [&](const Request &req, Response &res) {
  13727. res.set_content("test", "text/plain");
  13728. auto cert = req.peer_cert();
  13729. ASSERT_TRUE(static_cast<bool>(cert));
  13730. std::string common_name = cert.subject_cn();
  13731. EXPECT_EQ("Common Name", common_name);
  13732. });
  13733. auto port = svr.bind_to_any_port(HOST);
  13734. ASSERT_LT(0, port);
  13735. thread t = thread([&]() { svr.listen_after_bind(); });
  13736. auto se = detail::scope_exit([&] {
  13737. svr.stop();
  13738. t.join();
  13739. ASSERT_FALSE(svr.is_running());
  13740. });
  13741. svr.wait_until_ready();
  13742. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13743. client_encrypted_private_key_pass);
  13744. cli.enable_server_certificate_verification(false);
  13745. cli.set_connection_timeout(30);
  13746. auto res = cli.Get("/test");
  13747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13748. ASSERT_EQ(StatusCode::OK_200, res->status);
  13749. }
  13750. TEST(SSLClientServerTest, ClientCertPresent) {
  13751. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13752. }
  13753. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13754. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13755. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13756. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13757. }
  13758. // Expects svr, which must require client certificates, to reject a client
  13759. // that has none
  13760. void RejectsClientWithoutCert(SSLServer &svr) {
  13761. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13762. auto port = svr.bind_to_any_port(HOST);
  13763. ASSERT_LT(0, port);
  13764. thread t = thread([&]() { svr.listen_after_bind(); });
  13765. auto se = detail::scope_exit([&] {
  13766. svr.stop();
  13767. t.join();
  13768. ASSERT_FALSE(svr.is_running());
  13769. });
  13770. svr.wait_until_ready();
  13771. SSLClient cli(HOST, port);
  13772. cli.set_connection_timeout(30);
  13773. // Skip the server certificate check, so that the request fails because the
  13774. // client certificate is missing rather than because cert.pem is not trusted
  13775. cli.enable_server_certificate_verification(false);
  13776. auto res = cli.Get("/test");
  13777. ASSERT_FALSE(res);
  13778. // The server rejects the client during the handshake, or on TLS 1.3 right
  13779. // after it, which the client notices on its first write or read
  13780. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13781. res.error() == Error::Write || res.error() == Error::Read)
  13782. << to_string(res.error());
  13783. if (res.error() == Error::SSLConnection) {
  13784. EXPECT_NE(0UL, res.ssl_backend_error());
  13785. }
  13786. // A rejection noticed on the write keeps the TLS error the write hit
  13787. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13788. }
  13789. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13790. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13791. ASSERT_TRUE(svr.is_valid());
  13792. if (setup) { setup(svr); }
  13793. RejectsClientWithoutCert(svr);
  13794. }
  13795. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13796. // A server that requires client certificates must keep requiring them after
  13797. // setup changes it, and keep accepting a client that has one
  13798. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13799. ClientCertMissing(setup);
  13800. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13801. setup);
  13802. }
  13803. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13804. ClientCertStillRequired([](SSLServer &svr) {
  13805. ASSERT_TRUE(tls::set_verify_callback(
  13806. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13807. });
  13808. }
  13809. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13810. ClientCertStillRequired([](SSLServer &svr) {
  13811. ASSERT_TRUE(tls::set_verify_callback(
  13812. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13813. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13814. });
  13815. }
  13816. // The client verifies the server certificate during the handshake, so a
  13817. // server that fails the check never gets the client certificate, even when a
  13818. // verifier of the client's own accepts it
  13819. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13820. struct Case {
  13821. const char *trusted_ca;
  13822. const char *host;
  13823. Error error;
  13824. };
  13825. // cert2.pem names localhost: the first client does not trust it, and the
  13826. // second trusts it but asks for another name
  13827. for (const auto &c :
  13828. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13829. Case{SERVER_CERT2_FILE, "example.com",
  13830. Error::SSLServerHostnameVerification}}) {
  13831. for (auto with_verifier : {false, true}) {
  13832. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13833. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13834. CLIENT_CA_CERT_FILE);
  13835. ASSERT_TRUE(svr.is_valid());
  13836. std::atomic<bool> got_client_cert{false};
  13837. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13838. [&](const tls::VerifyContext &) {
  13839. got_client_cert = true;
  13840. return true;
  13841. }));
  13842. auto port = svr.bind_to_any_port("127.0.0.1");
  13843. ASSERT_LT(0, port);
  13844. thread t = thread([&] { svr.listen_after_bind(); });
  13845. svr.wait_until_ready();
  13846. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13847. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13848. cli.set_ca_cert_path(c.trusted_ca);
  13849. if (with_verifier) {
  13850. cli.set_server_certificate_verifier(
  13851. [](const tls::VerifyContext &) { return true; });
  13852. }
  13853. auto res = cli.Get("/");
  13854. EXPECT_FALSE(res);
  13855. EXPECT_EQ(c.error, res.error());
  13856. svr.stop();
  13857. t.join();
  13858. EXPECT_FALSE(got_client_cert);
  13859. }
  13860. }
  13861. }
  13862. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13863. std::string cert_pem, key_pem, ca_pem;
  13864. read_file(SERVER_CERT_FILE, cert_pem);
  13865. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13866. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13867. ASSERT_TRUE(
  13868. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13869. }
  13870. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13872. ASSERT_TRUE(svr.is_valid());
  13873. UpdateCertsPemWithClientCA(svr);
  13874. RejectsClientWithoutCert(svr);
  13875. }
  13876. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13877. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13878. }
  13879. // A TLS error from one request must not show up in a later request's Result
  13880. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13881. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13882. ASSERT_TRUE(svr.is_valid());
  13883. svr.Get("/test", [](const Request &, Response &res) {
  13884. res.set_content("test", "text/plain");
  13885. });
  13886. auto port = svr.bind_to_any_port(HOST);
  13887. ASSERT_LT(0, port);
  13888. thread t = thread([&]() { svr.listen_after_bind(); });
  13889. auto se = detail::scope_exit([&] {
  13890. svr.stop();
  13891. t.join();
  13892. ASSERT_FALSE(svr.is_running());
  13893. });
  13894. svr.wait_until_ready();
  13895. SSLClient cli(HOST, port);
  13896. cli.set_connection_timeout(30);
  13897. cli.enable_server_hostname_verification(false);
  13898. // cert.pem is not trusted, so the handshake fails
  13899. ASSERT_FALSE(cli.Get("/test"));
  13900. cli.enable_server_certificate_verification(false);
  13901. auto res = cli.Get("/test");
  13902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13903. EXPECT_EQ(0, res.ssl_error());
  13904. EXPECT_EQ(0UL, res.ssl_backend_error());
  13905. }
  13906. // PEM memory-based constructor tests (works with all TLS backends).
  13907. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13908. // terminator after it.
  13909. void PemMemoryClientCertPresent(
  13910. const std::string &client_cert_file,
  13911. const std::string &client_private_key_file,
  13912. const std::string &client_encrypted_private_key_pass = std::string(),
  13913. bool exact_size = false) {
  13914. // Read PEM files into memory
  13915. std::string server_cert_pem, server_key_pem;
  13916. std::string client_ca_pem;
  13917. std::string client_cert_pem, client_key_pem;
  13918. read_file(SERVER_CERT_FILE, server_cert_pem);
  13919. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13920. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13921. read_file(client_cert_file, client_cert_pem);
  13922. read_file(client_private_key_file, client_key_pem);
  13923. std::list<std::vector<char>> exact_copies;
  13924. auto data = [&](const std::string &pem) -> const char * {
  13925. if (!exact_size) { return pem.c_str(); }
  13926. exact_copies.emplace_back(pem.begin(), pem.end());
  13927. return exact_copies.back().data();
  13928. };
  13929. // Create server with PEM memory
  13930. SSLServer::PemMemory server_pem = {
  13931. data(server_cert_pem),
  13932. server_cert_pem.size(),
  13933. data(server_key_pem),
  13934. server_key_pem.size(),
  13935. data(client_ca_pem),
  13936. client_ca_pem.size(),
  13937. nullptr // no password for server key
  13938. };
  13939. SSLServer svr(server_pem);
  13940. ASSERT_TRUE(svr.is_valid());
  13941. svr.Get("/test", [&](const Request &req, Response &res) {
  13942. res.set_content("test", "text/plain");
  13943. auto cert = req.peer_cert();
  13944. ASSERT_TRUE(static_cast<bool>(cert));
  13945. EXPECT_EQ("Common Name", cert.subject_cn());
  13946. });
  13947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13948. auto se = detail::scope_exit([&] {
  13949. svr.stop();
  13950. t.join();
  13951. ASSERT_FALSE(svr.is_running());
  13952. });
  13953. svr.wait_until_ready();
  13954. // Create client with PEM memory
  13955. const char *password = client_encrypted_private_key_pass.empty()
  13956. ? nullptr
  13957. : client_encrypted_private_key_pass.c_str();
  13958. SSLClient::PemMemory client_pem = {
  13959. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13960. client_key_pem.size(), password};
  13961. SSLClient cli(HOST, PORT, client_pem);
  13962. cli.enable_server_certificate_verification(false);
  13963. cli.set_connection_timeout(30);
  13964. auto res = cli.Get("/test");
  13965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13966. ASSERT_EQ(StatusCode::OK_200, res->status);
  13967. }
  13968. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13969. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13970. }
  13971. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13972. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13973. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13974. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13975. }
  13976. // A server built from PEM memory with a client CA requires client certificates,
  13977. // also when the CA is a NUL-terminated string passed with a length of 0
  13978. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13979. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13980. read_file(SERVER_CERT_FILE, server_cert_pem);
  13981. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13982. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13983. SSLServer::PemMemory server_pem = {
  13984. server_cert_pem.c_str(),
  13985. server_cert_pem.size(),
  13986. server_key_pem.c_str(),
  13987. server_key_pem.size(),
  13988. client_ca_pem.c_str(),
  13989. client_ca_pem.size(),
  13990. nullptr // no password for server key
  13991. };
  13992. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13993. SCOPED_TRACE(client_ca_pem_len);
  13994. server_pem.client_ca_pem_len = client_ca_pem_len;
  13995. SSLServer svr(server_pem);
  13996. ASSERT_TRUE(svr.is_valid());
  13997. RejectsClientWithoutCert(svr);
  13998. }
  13999. // An empty CA fails to load instead of turning the check off
  14000. server_pem.client_ca_pem = "";
  14001. server_pem.client_ca_pem_len = 0;
  14002. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14003. }
  14004. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14005. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14006. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14007. true);
  14008. }
  14009. // A length shorter than the PEM cuts it short, so it no longer loads
  14010. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14011. std::string cert, key;
  14012. read_file(SERVER_CERT_FILE, cert);
  14013. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14014. for (auto cut_cert : {true, false}) {
  14015. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14016. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14017. SSLServer::PemMemory server_pem = {
  14018. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14019. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14020. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14021. key_len, nullptr};
  14022. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14023. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14024. key.c_str(), key_len, nullptr};
  14025. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14026. }
  14027. }
  14028. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14029. class NoListenSSLServer : public SSLServer {
  14030. public:
  14031. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14032. const char *client_ca_cert_file_path,
  14033. const char *client_ca_cert_dir_path = nullptr)
  14034. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14035. client_ca_cert_dir_path),
  14036. stop_(false) {}
  14037. std::atomic_bool stop_;
  14038. private:
  14039. bool process_and_close_socket(socket_t /*sock*/) override {
  14040. // Don't create SSL context
  14041. while (!stop_.load()) {
  14042. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14043. }
  14044. return true;
  14045. }
  14046. };
  14047. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14048. CLIENT_CA_CERT_FILE);
  14049. ASSERT_TRUE(svr.is_valid());
  14050. svr.Get("/test", [&](const Request &, Response &res) {
  14051. res.set_content("test", "text/plain");
  14052. });
  14053. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14054. auto se = detail::scope_exit([&] {
  14055. svr.stop_ = true;
  14056. svr.stop();
  14057. t.join();
  14058. ASSERT_FALSE(svr.is_running());
  14059. });
  14060. svr.wait_until_ready();
  14061. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14062. cli.enable_server_certificate_verification(false);
  14063. cli.set_connection_timeout(1);
  14064. auto res = cli.Get("/test");
  14065. ASSERT_TRUE(!res);
  14066. EXPECT_EQ(Error::SSLConnection, res.error());
  14067. // Timeout results in WantRead error code (maps to backend-specific value)
  14068. EXPECT_NE(0, res.ssl_error());
  14069. }
  14070. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14071. // Test SSLServer with client certificate verification using the standard
  14072. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14074. CLIENT_CA_CERT_DIR);
  14075. ASSERT_TRUE(svr.is_valid());
  14076. svr.Get("/test", [&](const Request &req, Response &res) {
  14077. res.set_content("test", "text/plain");
  14078. auto cert = req.peer_cert();
  14079. ASSERT_TRUE(static_cast<bool>(cert));
  14080. auto common_name = cert.subject_cn();
  14081. EXPECT_EQ("Common Name", common_name);
  14082. });
  14083. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14084. auto se = detail::scope_exit([&] {
  14085. svr.stop();
  14086. t.join();
  14087. ASSERT_FALSE(svr.is_running());
  14088. });
  14089. svr.wait_until_ready();
  14090. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14091. cli.enable_server_certificate_verification(false);
  14092. cli.set_connection_timeout(30);
  14093. auto res = cli.Get("/test");
  14094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14095. ASSERT_EQ(StatusCode::OK_200, res->status);
  14096. }
  14097. // Test verify_hostname for both OpenSSL and MbedTLS backends
  14098. // Verifies that wildcard matching and exact matching work consistently
  14099. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14100. using namespace httplib::tls;
  14101. // We need a running server to test against
  14102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14103. ASSERT_TRUE(svr.is_valid());
  14104. svr.Get("/test", [](const Request &, Response &res) {
  14105. res.set_content("ok", "text/plain");
  14106. });
  14107. thread t([&]() { svr.listen(HOST, PORT); });
  14108. auto se = detail::scope_exit([&] {
  14109. svr.stop();
  14110. t.join();
  14111. });
  14112. svr.wait_until_ready();
  14113. bool verify_callback_called = false;
  14114. bool verify_result_wrong = false;
  14115. SSLClient cli(HOST, PORT);
  14116. cli.enable_server_certificate_verification(true);
  14117. cli.set_ca_cert_path(CA_CERT_FILE);
  14118. cli.set_connection_timeout(5);
  14119. // Note: Test certificate has CN="Common Name", not "localhost"
  14120. bool verify_result_cn = false;
  14121. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14122. verify_callback_called = true;
  14123. if (!ctx.cert) return false;
  14124. // Test 1: "Common Name" should match (our test server cert CN)
  14125. verify_result_cn = ctx.check_hostname("Common Name");
  14126. // Test 2: wrong hostname should not match
  14127. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14128. return true; // Accept for the purpose of this test
  14129. });
  14130. auto res = cli.Get("/test");
  14131. // The request may succeed or fail depending on cert configuration
  14132. // but the callback should have been called
  14133. ASSERT_TRUE(verify_callback_called)
  14134. << "Verify callback should have been called";
  14135. // CN="Common Name" should match our test certificate
  14136. //
  14137. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14138. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14139. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14140. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14141. // <openssl/base.h>, which is included transitively when
  14142. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14143. #if defined(OPENSSL_IS_BORINGSSL)
  14144. EXPECT_FALSE(verify_result_cn)
  14145. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14146. #else
  14147. EXPECT_TRUE(verify_result_cn)
  14148. << "verify_hostname should match 'Common Name' (certificate CN)";
  14149. #endif
  14150. // Wrong hostname should not match
  14151. EXPECT_FALSE(verify_result_wrong)
  14152. << "verify_hostname should not match 'wronghost.example.com'";
  14153. }
  14154. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14155. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14156. // X509_check_ip behavior and must hold for every backend.
  14157. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14158. using namespace httplib::tls;
  14159. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14160. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14161. ASSERT_TRUE(svr.is_valid());
  14162. svr.Get("/test", [](const Request &, Response &res) {
  14163. res.set_content("ok", "text/plain");
  14164. });
  14165. thread t([&]() { svr.listen(HOST, PORT); });
  14166. auto se = detail::scope_exit([&] {
  14167. svr.stop();
  14168. t.join();
  14169. });
  14170. svr.wait_until_ready();
  14171. bool verify_callback_called = false;
  14172. bool ip_matched_via_cn = true;
  14173. SSLClient cli(HOST, PORT);
  14174. cli.enable_server_certificate_verification(true);
  14175. cli.set_ca_cert_path(CA_CERT_FILE);
  14176. cli.set_connection_timeout(5);
  14177. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14178. verify_callback_called = true;
  14179. if (!ctx.cert) return false;
  14180. // The IP appears only in the CN, so it must NOT be accepted.
  14181. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14182. return true; // Accept for the purpose of this test
  14183. });
  14184. cli.Get("/test");
  14185. ASSERT_TRUE(verify_callback_called)
  14186. << "Verify callback should have been called";
  14187. EXPECT_FALSE(ip_matched_via_cn)
  14188. << "An IP host must not be authenticated via the certificate CN";
  14189. }
  14190. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14191. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14192. using namespace httplib::tls;
  14193. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14194. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14195. ASSERT_TRUE(svr.is_valid());
  14196. svr.Get("/test", [](const Request &, Response &res) {
  14197. res.set_content("ok", "text/plain");
  14198. });
  14199. thread t([&]() { svr.listen(HOST, PORT); });
  14200. auto se = detail::scope_exit([&] {
  14201. svr.stop();
  14202. t.join();
  14203. });
  14204. svr.wait_until_ready();
  14205. bool verify_callback_called = false;
  14206. bool san_matched = false;
  14207. bool wrong_ipv6_matched = true;
  14208. bool cn_ipv6_matched = true;
  14209. SSLClient cli(HOST, PORT);
  14210. cli.enable_server_certificate_verification(true);
  14211. cli.set_ca_cert_path(CA_CERT_FILE);
  14212. cli.set_connection_timeout(5);
  14213. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14214. verify_callback_called = true;
  14215. if (!ctx.cert) return false;
  14216. // Matches the IPv6 iPAddress SAN.
  14217. san_matched = ctx.check_hostname("2001:db8::1");
  14218. // A different IPv6 address must not match.
  14219. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14220. // "::1" lives only in the CN, so it must not be accepted.
  14221. cn_ipv6_matched = ctx.check_hostname("::1");
  14222. return true; // Accept for the purpose of this test
  14223. });
  14224. cli.Get("/test");
  14225. ASSERT_TRUE(verify_callback_called)
  14226. << "Verify callback should have been called";
  14227. EXPECT_TRUE(san_matched)
  14228. << "verify_hostname should match an IPv6 iPAddress SAN";
  14229. EXPECT_FALSE(wrong_ipv6_matched)
  14230. << "verify_hostname should not match a non-matching IPv6 address";
  14231. EXPECT_FALSE(cn_ipv6_matched)
  14232. << "An IPv6 host must not be authenticated via the certificate CN";
  14233. }
  14234. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14235. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14236. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14237. using namespace httplib::tls;
  14238. // SANs: DNS:a.zz, IP:42.46.122.122
  14239. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14240. ASSERT_TRUE(svr.is_valid());
  14241. svr.Get("/test", [](const Request &, Response &res) {
  14242. res.set_content("ok", "text/plain");
  14243. });
  14244. auto port = svr.bind_to_any_port(HOST);
  14245. thread t([&]() { svr.listen_after_bind(); });
  14246. auto se = detail::scope_exit([&] {
  14247. svr.stop();
  14248. t.join();
  14249. });
  14250. svr.wait_until_ready();
  14251. bool verify_callback_called = false;
  14252. bool dns_san_matched = false;
  14253. bool ip_san_matched = false;
  14254. bool ip_matched_via_dns_san = true;
  14255. bool dns_matched_via_ip_san = true;
  14256. bool cn_matched_next_to_dns_san = true;
  14257. SSLClient cli(HOST, port);
  14258. cli.enable_server_certificate_verification(true);
  14259. cli.set_ca_cert_path(CA_CERT_FILE);
  14260. cli.set_connection_timeout(5);
  14261. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14262. verify_callback_called = true;
  14263. if (!ctx.cert) return false;
  14264. dns_san_matched = ctx.check_hostname("a.zz");
  14265. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14266. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14267. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14268. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14269. return true; // Accept for the purpose of this test
  14270. });
  14271. cli.Get("/test");
  14272. ASSERT_TRUE(verify_callback_called)
  14273. << "Verify callback should have been called";
  14274. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14275. EXPECT_TRUE(ip_san_matched)
  14276. << "verify_hostname should match an iPAddress SAN";
  14277. EXPECT_FALSE(ip_matched_via_dns_san)
  14278. << "An IP host must not be authenticated via a dNSName SAN";
  14279. EXPECT_FALSE(dns_matched_via_ip_san)
  14280. << "A DNS host must not be authenticated via an iPAddress SAN";
  14281. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14282. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14283. }
  14284. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14285. // "www.*.example.test" names one host and not every host under example.test.
  14286. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14287. using namespace httplib::tls;
  14288. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14289. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14290. ASSERT_TRUE(svr.is_valid());
  14291. svr.Get("/test", [](const Request &, Response &res) {
  14292. res.set_content("ok", "text/plain");
  14293. });
  14294. auto port = svr.bind_to_any_port(HOST);
  14295. thread t([&]() { svr.listen_after_bind(); });
  14296. auto se = detail::scope_exit([&] {
  14297. svr.stop();
  14298. t.join();
  14299. });
  14300. svr.wait_until_ready();
  14301. bool verify_callback_called = false;
  14302. bool leftmost_wildcard_matched = false;
  14303. bool wildcard_spanned_labels = true;
  14304. bool inner_wildcard_matched = true;
  14305. SSLClient cli(HOST, port);
  14306. cli.enable_server_certificate_verification(true);
  14307. cli.set_ca_cert_path(CA_CERT_FILE);
  14308. cli.set_connection_timeout(5);
  14309. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14310. verify_callback_called = true;
  14311. if (!ctx.cert) return false;
  14312. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14313. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14314. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14315. return true; // Accept for the purpose of this test
  14316. });
  14317. cli.Get("/test");
  14318. ASSERT_TRUE(verify_callback_called)
  14319. << "Verify callback should have been called";
  14320. EXPECT_TRUE(leftmost_wildcard_matched)
  14321. << "A leftmost wildcard should match a single label";
  14322. EXPECT_FALSE(wildcard_spanned_labels)
  14323. << "A wildcard label must not match more than one label";
  14324. EXPECT_FALSE(inner_wildcard_matched)
  14325. << "A wildcard outside the leftmost label must not be honoured";
  14326. }
  14327. // sans() must report each SAN entry under its own type.
  14328. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14329. using namespace httplib::tls;
  14330. // SANs: DNS:a.zz, IP:42.46.122.122
  14331. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14332. ASSERT_TRUE(svr.is_valid());
  14333. svr.Get("/test", [](const Request &, Response &res) {
  14334. res.set_content("ok", "text/plain");
  14335. });
  14336. auto port = svr.bind_to_any_port(HOST);
  14337. thread t([&]() { svr.listen_after_bind(); });
  14338. auto se = detail::scope_exit([&] {
  14339. svr.stop();
  14340. t.join();
  14341. });
  14342. svr.wait_until_ready();
  14343. bool verify_callback_called = false;
  14344. std::vector<SanEntry> sans;
  14345. SSLClient cli(HOST, port);
  14346. cli.enable_server_certificate_verification(true);
  14347. cli.set_ca_cert_path(CA_CERT_FILE);
  14348. cli.set_connection_timeout(5);
  14349. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14350. verify_callback_called = true;
  14351. if (!ctx.cert) return false;
  14352. sans = ctx.sans();
  14353. return true; // Accept for the purpose of this test
  14354. });
  14355. cli.Get("/test");
  14356. ASSERT_TRUE(verify_callback_called)
  14357. << "Verify callback should have been called";
  14358. auto has_san = [&](SanType type, const std::string &value) {
  14359. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14360. return san.type == type && san.value == value;
  14361. });
  14362. };
  14363. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14364. << "sans() should report the dNSName SAN";
  14365. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14366. << "sans() should report the iPAddress SAN";
  14367. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14368. << "sans() must not report the dNSName SAN as an address";
  14369. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14370. << "sans() must not report the iPAddress SAN as a DNS name";
  14371. }
  14372. #endif
  14373. // mbedTLS-specific callback constructor test
  14374. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14375. #ifdef CPPHTTPLIB_SSL_ENABLED
  14376. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14378. ASSERT_TRUE(svr.is_valid());
  14379. // Set up a handler to verify client certificate is present
  14380. bool client_cert_verified = false;
  14381. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14382. // Verify that client certificate was provided
  14383. client_cert_verified = true;
  14384. res.set_content("success", "text/plain");
  14385. });
  14386. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14387. auto se = detail::scope_exit([&] {
  14388. svr.stop();
  14389. t.join();
  14390. ASSERT_FALSE(svr.is_running());
  14391. });
  14392. svr.wait_until_ready();
  14393. // Client with certificate
  14394. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14395. cli.enable_server_certificate_verification(false);
  14396. cli.set_connection_timeout(30);
  14397. auto res = cli.Get("/test");
  14398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14399. ASSERT_EQ(StatusCode::OK_200, res->status);
  14400. ASSERT_TRUE(client_cert_verified);
  14401. EXPECT_EQ("success", res->body);
  14402. }
  14403. #endif
  14404. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14405. // backends
  14406. #ifdef CPPHTTPLIB_SSL_ENABLED
  14407. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14408. using namespace httplib::tls;
  14409. // Test that when client CA cert file is provided,
  14410. // the server properly requests and validates client certificates
  14411. // Create a server with client authentication
  14412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14413. ASSERT_TRUE(svr.is_valid());
  14414. bool handler_called = false;
  14415. svr.Get("/test", [&](const Request &req, Response &res) {
  14416. handler_called = true;
  14417. // Verify that a client certificate was provided
  14418. auto cert = req.peer_cert();
  14419. ASSERT_TRUE(static_cast<bool>(cert));
  14420. // Get the issuer name
  14421. std::string issuer_str = cert.issuer_name();
  14422. ASSERT_FALSE(issuer_str.empty());
  14423. // The client certificate should be issued by our test CA
  14424. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14425. res.set_content("authenticated", "text/plain");
  14426. });
  14427. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14428. auto se = detail::scope_exit([&] {
  14429. svr.stop();
  14430. t.join();
  14431. ASSERT_FALSE(svr.is_running());
  14432. });
  14433. svr.wait_until_ready();
  14434. // Connect with a client certificate issued by the CA
  14435. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14436. cli.enable_server_certificate_verification(false);
  14437. cli.set_connection_timeout(30);
  14438. auto res = cli.Get("/test");
  14439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14440. ASSERT_EQ(StatusCode::OK_200, res->status);
  14441. ASSERT_TRUE(handler_called);
  14442. EXPECT_EQ("authenticated", res->body);
  14443. }
  14444. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14445. using namespace httplib::tls;
  14446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14447. ASSERT_TRUE(svr.is_valid());
  14448. svr.Get("/test", [](const Request &, Response &res) {
  14449. res.set_content("ok", "text/plain");
  14450. });
  14451. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14452. auto se = detail::scope_exit([&] {
  14453. svr.stop();
  14454. t.join();
  14455. });
  14456. svr.wait_until_ready();
  14457. SSLClient cli(HOST, PORT);
  14458. cli.enable_server_certificate_verification(false);
  14459. cli.set_connection_timeout(30);
  14460. bool cert_checked = false;
  14461. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14462. if (ctx.cert) {
  14463. auto sans = ctx.sans();
  14464. // Test certificate may or may not have SANs - just verify the API
  14465. // works If SANs exist, verify the types are valid
  14466. for (const auto &san : sans) {
  14467. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14468. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14469. san.type == SanType::OTHER);
  14470. EXPECT_FALSE(san.value.empty());
  14471. }
  14472. cert_checked = true;
  14473. }
  14474. return true;
  14475. });
  14476. auto res = cli.Get("/test");
  14477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14478. EXPECT_TRUE(cert_checked);
  14479. }
  14480. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14481. using namespace httplib::tls;
  14482. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14483. ASSERT_TRUE(svr.is_valid());
  14484. svr.Get("/test", [](const Request &, Response &res) {
  14485. res.set_content("ok", "text/plain");
  14486. });
  14487. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14488. auto se = detail::scope_exit([&] {
  14489. svr.stop();
  14490. t.join();
  14491. });
  14492. svr.wait_until_ready();
  14493. SSLClient cli(HOST, PORT);
  14494. cli.enable_server_certificate_verification(false);
  14495. cli.set_connection_timeout(30);
  14496. bool validity_checked = false;
  14497. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14498. if (ctx.cert) {
  14499. time_t not_before = 0, not_after = 0;
  14500. bool result = ctx.validity(not_before, not_after);
  14501. EXPECT_TRUE(result);
  14502. // Verify that not_before < now < not_after for a valid cert
  14503. time_t now = time(nullptr);
  14504. EXPECT_LT(not_before, now);
  14505. EXPECT_GT(not_after, now);
  14506. validity_checked = true;
  14507. }
  14508. return true;
  14509. });
  14510. auto res = cli.Get("/test");
  14511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14512. EXPECT_TRUE(validity_checked);
  14513. }
  14514. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14515. using namespace httplib::tls;
  14516. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14517. ASSERT_TRUE(svr.is_valid());
  14518. svr.Get("/test", [](const Request &, Response &res) {
  14519. res.set_content("ok", "text/plain");
  14520. });
  14521. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14522. auto se = detail::scope_exit([&] {
  14523. svr.stop();
  14524. t.join();
  14525. });
  14526. svr.wait_until_ready();
  14527. SSLClient cli(HOST, PORT);
  14528. cli.enable_server_certificate_verification(false);
  14529. cli.set_connection_timeout(30);
  14530. bool serial_checked = false;
  14531. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14532. if (ctx.cert) {
  14533. std::string serial = ctx.serial();
  14534. EXPECT_FALSE(serial.empty());
  14535. // Serial should be a hex string
  14536. for (char c : serial) {
  14537. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14538. (c >= 'a' && c <= 'f'));
  14539. }
  14540. serial_checked = true;
  14541. }
  14542. return true;
  14543. });
  14544. auto res = cli.Get("/test");
  14545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14546. EXPECT_TRUE(serial_checked);
  14547. }
  14548. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14549. // Test 1: Valid CA file - no error should be recorded
  14550. {
  14551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14552. CLIENT_CA_CERT_FILE);
  14553. ASSERT_TRUE(svr.is_valid());
  14554. // With valid setup, last_ssl_error should be 0
  14555. EXPECT_EQ(0, svr.ssl_last_error());
  14556. }
  14557. // Test 2: Invalid CA file content
  14558. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14559. {
  14560. // Create a temporary file with completely invalid content
  14561. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14562. {
  14563. std::ofstream ofs(temp_invalid_ca);
  14564. ofs << "This is not a certificate file at all\n";
  14565. ofs << "Just plain text content\n";
  14566. }
  14567. // Create server with invalid CA file
  14568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14569. // Clean up temporary file
  14570. std::remove(temp_invalid_ca);
  14571. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14572. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14573. // Note: SSL_CTX_load_verify_locations typically fails first,
  14574. // but our error handling code path is still exercised
  14575. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14576. }
  14577. }
  14578. TEST(VerifyCallbackTest, VerifyContextFields) {
  14579. using namespace httplib::tls;
  14580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14581. ASSERT_TRUE(svr.is_valid());
  14582. svr.Get("/test", [](const Request &, Response &res) {
  14583. res.set_content("ok", "text/plain");
  14584. });
  14585. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14586. auto se = detail::scope_exit([&] {
  14587. svr.stop();
  14588. t.join();
  14589. });
  14590. svr.wait_until_ready();
  14591. SSLClient cli(HOST, PORT);
  14592. cli.enable_server_certificate_verification(false);
  14593. cli.set_connection_timeout(30);
  14594. int callback_count = 0;
  14595. bool saw_leaf_cert = false;
  14596. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14597. if (ctx.cert) {
  14598. callback_count++;
  14599. // We should see at least one certificate (the leaf)
  14600. std::string cn = ctx.subject_cn();
  14601. if (!cn.empty()) { saw_leaf_cert = true; }
  14602. // Verify context fields are populated
  14603. EXPECT_NE(ctx.session, nullptr);
  14604. EXPECT_GE(ctx.depth, 0);
  14605. }
  14606. return true;
  14607. });
  14608. auto res = cli.Get("/test");
  14609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14610. EXPECT_GT(callback_count, 0);
  14611. EXPECT_TRUE(saw_leaf_cert);
  14612. }
  14613. // A verifier that accepts runs alongside the built-in verification, and is the
  14614. // only check once that is turned off.
  14615. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14616. using namespace httplib::tls;
  14617. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14618. ASSERT_TRUE(svr.is_valid());
  14619. svr.Get("/test", [](const Request &, Response &res) {
  14620. res.set_content("ok", "text/plain");
  14621. });
  14622. auto port = svr.bind_to_any_port(HOST);
  14623. thread t([&]() { svr.listen_after_bind(); });
  14624. auto se = detail::scope_exit([&] {
  14625. svr.stop();
  14626. t.join();
  14627. });
  14628. svr.wait_until_ready();
  14629. SSLClient cli(HOST, port);
  14630. cli.enable_server_hostname_verification(false);
  14631. auto calls = 0;
  14632. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14633. calls++;
  14634. return true;
  14635. });
  14636. // cert.pem is not trusted
  14637. auto res = cli.Get("/test");
  14638. ASSERT_FALSE(res);
  14639. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14640. EXPECT_GT(calls, 0);
  14641. cli.enable_server_certificate_verification(false);
  14642. res = cli.Get("/test");
  14643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14644. EXPECT_EQ("ok", res->body);
  14645. }
  14646. // A verifier belongs to the client that set it, not to the thread that set it.
  14647. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14648. using namespace httplib::tls;
  14649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14650. ASSERT_TRUE(svr.is_valid());
  14651. svr.Get("/test", [](const Request &, Response &res) {
  14652. res.set_content("ok", "text/plain");
  14653. });
  14654. auto port = svr.bind_to_any_port(HOST);
  14655. thread t([&]() { svr.listen_after_bind(); });
  14656. auto se = detail::scope_exit([&] {
  14657. svr.stop();
  14658. t.join();
  14659. });
  14660. svr.wait_until_ready();
  14661. auto rejecting_calls = 0;
  14662. SSLClient rejecting(HOST, port);
  14663. rejecting.enable_server_certificate_verification(false);
  14664. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14665. rejecting_calls++;
  14666. return false;
  14667. });
  14668. auto accepting_calls = 0;
  14669. SSLClient accepting(HOST, port);
  14670. accepting.enable_server_certificate_verification(false);
  14671. // Set on another thread than the requests below.
  14672. thread([&]() {
  14673. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14674. accepting_calls++;
  14675. return true;
  14676. });
  14677. }).join();
  14678. // Requested on another thread than the verifier was set on.
  14679. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14680. EXPECT_GT(rejecting_calls, 0);
  14681. auto res = accepting.Get("/test");
  14682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14683. EXPECT_GT(accepting_calls, 0);
  14684. }
  14685. // A verifier replaced while a handshake runs it lives until it returns.
  14686. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14687. using namespace httplib::tls;
  14688. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14689. ASSERT_TRUE(svr.is_valid());
  14690. svr.Get("/test", [](const Request &, Response &res) {
  14691. res.set_content("ok", "text/plain");
  14692. });
  14693. auto port = svr.bind_to_any_port(HOST);
  14694. thread t([&]() { svr.listen_after_bind(); });
  14695. auto se = detail::scope_exit([&] {
  14696. svr.stop();
  14697. t.join();
  14698. });
  14699. svr.wait_until_ready();
  14700. SSLClient cli(HOST, port);
  14701. cli.enable_server_certificate_verification(false);
  14702. std::promise<void> entered;
  14703. std::promise<void> replaced;
  14704. auto replaced_future = replaced.get_future();
  14705. auto first_call = true;
  14706. // Long enough to live on the heap
  14707. std::string expected(64, 'v');
  14708. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14709. if (first_call) {
  14710. first_call = false;
  14711. entered.set_value();
  14712. replaced_future.wait();
  14713. }
  14714. return expected == std::string(64, 'v');
  14715. });
  14716. thread request([&]() {
  14717. auto res = cli.Get("/test");
  14718. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14719. });
  14720. entered.get_future().wait();
  14721. cli.set_server_certificate_verifier(
  14722. [](const VerifyContext &) { return true; });
  14723. replaced.set_value();
  14724. request.join();
  14725. }
  14726. // VerifyContext::session is the same handle the other tls:: functions take.
  14727. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14728. using namespace httplib::tls;
  14729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14730. ASSERT_TRUE(svr.is_valid());
  14731. svr.Get("/test", [](const Request &, Response &res) {
  14732. res.set_content("ok", "text/plain");
  14733. });
  14734. auto port = svr.bind_to_any_port(HOST);
  14735. thread t([&]() { svr.listen_after_bind(); });
  14736. auto se = detail::scope_exit([&] {
  14737. svr.stop();
  14738. t.join();
  14739. });
  14740. svr.wait_until_ready();
  14741. SSLClient cli(HOST, port);
  14742. cli.enable_server_certificate_verification(false);
  14743. session_t verifier_session = nullptr;
  14744. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14745. verifier_session = ctx.session;
  14746. return true;
  14747. });
  14748. session_t session_verifier_session = nullptr;
  14749. cli.set_session_verifier([&](session_t session) {
  14750. session_verifier_session = session;
  14751. return SSLVerifierResponse::NoDecisionMade;
  14752. });
  14753. auto res = cli.Get("/test");
  14754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14755. EXPECT_NE(nullptr, verifier_session);
  14756. EXPECT_EQ(session_verifier_session, verifier_session);
  14757. }
  14758. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14759. using httplib::tls::TlsError;
  14760. // Test that verify_error_to_string returns empty for success
  14761. std::string success_str = TlsError::verify_error_to_string(0);
  14762. EXPECT_TRUE(success_str.empty());
  14763. // Test that verify_error_to_string returns non-empty for error codes
  14764. // Using a common error code (certificate expired)
  14765. std::string error_str =
  14766. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14767. EXPECT_FALSE(error_str.empty());
  14768. }
  14769. TEST(SessionVerifierTest, CertificateAccepted) {
  14770. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14771. ASSERT_TRUE(svr.is_valid());
  14772. svr.Get("/test", [](const Request &, Response &res) {
  14773. res.set_content("ok", "text/plain");
  14774. });
  14775. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14776. auto se = detail::scope_exit([&] {
  14777. svr.stop();
  14778. t.join();
  14779. });
  14780. svr.wait_until_ready();
  14781. SSLClient cli(HOST, PORT);
  14782. cli.enable_server_certificate_verification(false);
  14783. cli.set_connection_timeout(30);
  14784. bool callback_called = false;
  14785. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14786. EXPECT_NE(session, nullptr);
  14787. callback_called = true;
  14788. return SSLVerifierResponse::CertificateAccepted;
  14789. });
  14790. auto res = cli.Get("/test");
  14791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14792. EXPECT_EQ(200, res->status);
  14793. EXPECT_TRUE(callback_called);
  14794. }
  14795. TEST(SessionVerifierTest, CertificateRejected) {
  14796. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14797. ASSERT_TRUE(svr.is_valid());
  14798. svr.Get("/test", [](const Request &, Response &res) {
  14799. res.set_content("ok", "text/plain");
  14800. });
  14801. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14802. auto se = detail::scope_exit([&] {
  14803. svr.stop();
  14804. t.join();
  14805. });
  14806. svr.wait_until_ready();
  14807. SSLClient cli(HOST, PORT);
  14808. cli.enable_server_certificate_verification(false);
  14809. cli.set_connection_timeout(30);
  14810. bool callback_called = false;
  14811. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14812. EXPECT_NE(session, nullptr);
  14813. callback_called = true;
  14814. return SSLVerifierResponse::CertificateRejected;
  14815. });
  14816. auto res = cli.Get("/test");
  14817. EXPECT_FALSE(res);
  14818. EXPECT_TRUE(callback_called);
  14819. }
  14820. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14821. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14822. ASSERT_TRUE(svr.is_valid());
  14823. svr.Get("/test", [](const Request &, Response &res) {
  14824. res.set_content("ok", "text/plain");
  14825. });
  14826. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14827. auto se = detail::scope_exit([&] {
  14828. svr.stop();
  14829. t.join();
  14830. });
  14831. svr.wait_until_ready();
  14832. // NoDecisionMade with verification disabled should succeed (no default check)
  14833. SSLClient cli(HOST, PORT);
  14834. cli.enable_server_certificate_verification(false);
  14835. cli.set_connection_timeout(30);
  14836. bool callback_called = false;
  14837. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14838. EXPECT_NE(session, nullptr);
  14839. callback_called = true;
  14840. return SSLVerifierResponse::NoDecisionMade;
  14841. });
  14842. auto res = cli.Get("/test");
  14843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14844. EXPECT_EQ(200, res->status);
  14845. EXPECT_TRUE(callback_called);
  14846. }
  14847. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14849. ASSERT_TRUE(svr.is_valid());
  14850. svr.Get("/test", [](const Request &, Response &res) {
  14851. res.set_content("ok", "text/plain");
  14852. });
  14853. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14854. auto se = detail::scope_exit([&] {
  14855. svr.stop();
  14856. t.join();
  14857. });
  14858. svr.wait_until_ready();
  14859. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14860. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14861. // so we only check that the request fails, not whether the callback was
  14862. // called.
  14863. SSLClient cli(HOST, PORT);
  14864. cli.enable_server_certificate_verification(true);
  14865. cli.set_connection_timeout(30);
  14866. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14867. EXPECT_NE(session, nullptr);
  14868. return SSLVerifierResponse::NoDecisionMade;
  14869. });
  14870. auto res = cli.Get("/test");
  14871. EXPECT_FALSE(res);
  14872. }
  14873. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14874. // Test SSL server using PemMemory constructor with client CA certificates
  14875. // Read PEM files
  14876. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14877. read_file(SERVER_CERT_FILE, server_cert_pem);
  14878. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14879. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14880. // Create SSLServer with PemMemory constructor including client CA
  14881. SSLServer::PemMemory server_pem = {
  14882. server_cert_pem.c_str(),
  14883. server_cert_pem.size(),
  14884. server_key_pem.c_str(),
  14885. server_key_pem.size(),
  14886. client_ca_pem.c_str(),
  14887. client_ca_pem.size(),
  14888. nullptr // no password for server key
  14889. };
  14890. SSLServer svr(server_pem);
  14891. ASSERT_TRUE(svr.is_valid());
  14892. // No SSL error should be recorded for valid setup
  14893. EXPECT_EQ(0, svr.ssl_last_error());
  14894. // Set up server endpoints
  14895. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14896. res.set_content("ok", "text/plain");
  14897. });
  14898. // Start server in a thread
  14899. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14900. svr.wait_until_ready();
  14901. // Connect with client certificate (using constructor with paths)
  14902. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14903. cli.enable_server_certificate_verification(false);
  14904. auto res = cli.Get("/test-pem-ca");
  14905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14906. EXPECT_EQ(200, res->status);
  14907. EXPECT_EQ("ok", res->body);
  14908. svr.stop();
  14909. server_thread.join();
  14910. }
  14911. #endif
  14912. #ifdef _WIN32
  14913. TEST(CleanupTest, WSACleanup) {
  14914. int ret = WSACleanup();
  14915. ASSERT_EQ(0, ret);
  14916. }
  14917. #endif
  14918. #ifndef CPPHTTPLIB_SSL_ENABLED
  14919. TEST(NoSSLSupport, SimpleInterface) {
  14920. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14921. }
  14922. #endif
  14923. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14924. TEST(InvalidScheme, SimpleInterface) {
  14925. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14926. }
  14927. #endif
  14928. TEST(NoScheme, SimpleInterface) {
  14929. Client cli("yahoo.com:80");
  14930. ASSERT_TRUE(cli.is_valid());
  14931. }
  14932. TEST(SendAPI, SimpleInterface_Online) {
  14933. Client cli("http://yahoo.com");
  14934. Request req;
  14935. req.method = "GET";
  14936. req.path = "/";
  14937. auto res = cli.send(req);
  14938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14939. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14940. }
  14941. TEST(SendAPI, WithParamsInRequest) {
  14942. Server svr;
  14943. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14944. EXPECT_TRUE(req.has_param("test"));
  14945. EXPECT_EQ("test_value", req.get_param_value("test"));
  14946. });
  14947. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14948. auto se = detail::scope_exit([&] {
  14949. svr.stop();
  14950. t.join();
  14951. ASSERT_FALSE(svr.is_running());
  14952. });
  14953. svr.wait_until_ready();
  14954. Client cli(HOST, PORT);
  14955. {
  14956. Request req;
  14957. req.method = "GET";
  14958. req.path = "/";
  14959. req.params.emplace("test", "test_value");
  14960. auto res = cli.send(req);
  14961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14962. }
  14963. {
  14964. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14966. }
  14967. }
  14968. TEST(ClientImplMethods, GetSocketTest) {
  14969. httplib::Server svr;
  14970. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14971. res.status = StatusCode::OK_200;
  14972. });
  14973. auto port = svr.bind_to_any_port("127.0.0.1");
  14974. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14975. auto se = detail::scope_exit([&] {
  14976. svr.stop();
  14977. thread.join();
  14978. ASSERT_FALSE(svr.is_running());
  14979. });
  14980. svr.wait_until_ready();
  14981. {
  14982. httplib::Client cli("127.0.0.1", port);
  14983. cli.set_keep_alive(true);
  14984. // Use the behavior of cpp-httplib of opening the connection
  14985. // only when the first request happens. If that changes,
  14986. // this test would be obsolete.
  14987. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14988. // This also implicitly tests the server. But other tests would fail much
  14989. // earlier than this one to be considered.
  14990. auto res = cli.Get("/");
  14991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14992. EXPECT_EQ(StatusCode::OK_200, res->status);
  14993. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14994. }
  14995. }
  14996. #ifdef CPPHTTPLIB_SSL_ENABLED
  14997. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14998. Client cli("http://yahoo.com");
  14999. auto res = cli.Get("/");
  15000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15001. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15002. cli.set_follow_location(true);
  15003. res = cli.Get("/");
  15004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15005. EXPECT_EQ(StatusCode::OK_200, res->status);
  15006. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15007. }
  15008. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15009. Client cli("https://yahoo.com");
  15010. auto res = cli.Get("/");
  15011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15012. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15013. cli.set_follow_location(true);
  15014. res = cli.Get("/");
  15015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15016. EXPECT_EQ(StatusCode::OK_200, res->status);
  15017. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15018. }
  15019. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15020. Client cli("https://yahoo.com");
  15021. auto res = cli.Get("/");
  15022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15023. ASSERT_FALSE(!res);
  15024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15025. ASSERT_FALSE(res == nullptr);
  15026. ASSERT_TRUE(res != nullptr);
  15027. EXPECT_EQ(Error::Success, res.error());
  15028. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15029. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15030. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15031. cli.set_follow_location(true);
  15032. res = cli.Get("/");
  15033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15034. EXPECT_EQ(Error::Success, res.error());
  15035. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15036. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15037. EXPECT_EQ(StatusCode::OK_200, res->status);
  15038. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15039. }
  15040. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15041. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15042. Client cli("https://cdnjs.cloudflare.com");
  15043. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15044. Headers{{"Accept-Encoding", "br"}});
  15045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15046. EXPECT_EQ(StatusCode::OK_200, res->status);
  15047. EXPECT_EQ(287630U, res->body.size());
  15048. EXPECT_EQ("application/javascript; charset=utf-8",
  15049. res->get_header_value("Content-Type"));
  15050. }
  15051. #endif
  15052. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15053. #undef REDIR_HOST // Silence compiler warning
  15054. #define REDIR_HOST "https://httpbingo.org"
  15055. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15056. Client cli(REDIR_HOST);
  15057. cli.set_follow_location(true);
  15058. auto res =
  15059. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15061. EXPECT_EQ(StatusCode::OK_200, res->status);
  15062. }
  15063. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15064. Client cli(REDIR_HOST);
  15065. cli.set_follow_location(true);
  15066. Params params;
  15067. params.emplace("url", "http://example.com");
  15068. params.emplace("status_code", "302");
  15069. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15071. EXPECT_EQ(StatusCode::OK_200, res->status);
  15072. }
  15073. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15074. Client cli(REDIR_HOST);
  15075. cli.set_follow_location(true);
  15076. Params params;
  15077. params.emplace("url", "http://example.com");
  15078. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15080. EXPECT_EQ(StatusCode::OK_200, res->status);
  15081. }
  15082. TEST(HttpToHttpsRedirectTest, CertFile) {
  15083. auto ssl_port = PORT + 1;
  15084. Server svr;
  15085. ASSERT_TRUE(svr.is_valid());
  15086. svr.Get("/index", [&](const Request &, Response &res) {
  15087. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15088. "/index");
  15089. svr.stop();
  15090. });
  15091. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15092. ASSERT_TRUE(ssl_svr.is_valid());
  15093. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15094. res.set_content("test", "text/plain");
  15095. ssl_svr.stop();
  15096. });
  15097. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15098. thread t2 =
  15099. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15100. auto se = detail::scope_exit([&] {
  15101. t2.join();
  15102. t.join();
  15103. ASSERT_FALSE(svr.is_running());
  15104. });
  15105. svr.wait_until_ready();
  15106. ssl_svr.wait_until_ready();
  15107. Client cli("127.0.0.1", PORT);
  15108. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15109. cli.enable_server_certificate_verification(true);
  15110. cli.set_follow_location(true);
  15111. cli.set_connection_timeout(30);
  15112. auto res = cli.Get("/index");
  15113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15114. ASSERT_EQ(StatusCode::OK_200, res->status);
  15115. }
  15116. TEST(SSLClientRedirectTest, CertFile) {
  15117. auto ssl_port = PORT + 1;
  15118. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15119. ASSERT_TRUE(ssl_svr1.is_valid());
  15120. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15121. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15122. "/index");
  15123. ssl_svr1.stop();
  15124. });
  15125. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15126. ASSERT_TRUE(ssl_svr2.is_valid());
  15127. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15128. res.set_content("test", "text/plain");
  15129. ssl_svr2.stop();
  15130. });
  15131. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15132. thread t2 =
  15133. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15134. auto se = detail::scope_exit([&] {
  15135. t2.join();
  15136. t.join();
  15137. ASSERT_FALSE(ssl_svr1.is_running());
  15138. });
  15139. ssl_svr1.wait_until_ready();
  15140. ssl_svr2.wait_until_ready();
  15141. SSLClient cli("127.0.0.1", PORT);
  15142. std::string cert;
  15143. read_file(SERVER_CERT2_FILE, cert);
  15144. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15145. cli.enable_server_certificate_verification(true);
  15146. cli.set_follow_location(true);
  15147. cli.set_connection_timeout(30);
  15148. auto res = cli.Get("/index");
  15149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15150. ASSERT_EQ(StatusCode::OK_200, res->status);
  15151. }
  15152. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15153. // another port, so the client follows it with a new client.
  15154. static Result GetThroughTlsRedirectToDifferentPort(
  15155. const std::function<void(SSLClient &)> &setup,
  15156. const char *target_cert = SERVER_CERT2_FILE,
  15157. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15158. auto ssl_port = PORT + 1;
  15159. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15160. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15161. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15162. "/index");
  15163. });
  15164. SSLServer ssl_svr2(target_cert, target_key);
  15165. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15166. res.set_content("test", "text/plain");
  15167. });
  15168. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15169. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15170. auto se = detail::scope_exit([&] {
  15171. ssl_svr2.stop();
  15172. ssl_svr1.stop();
  15173. t2.join();
  15174. t.join();
  15175. });
  15176. ssl_svr1.wait_until_ready();
  15177. ssl_svr2.wait_until_ready();
  15178. SSLClient cli("127.0.0.1", PORT);
  15179. cli.set_follow_location(true);
  15180. cli.set_connection_timeout(30);
  15181. setup(cli);
  15182. return cli.Get("/index");
  15183. }
  15184. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15185. auto calls = 0;
  15186. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15187. cli.enable_server_certificate_verification(false);
  15188. // Accept the first server only.
  15189. cli.set_session_verifier([&](tls::session_t) {
  15190. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15191. : SSLVerifierResponse::CertificateRejected;
  15192. });
  15193. });
  15194. ASSERT_FALSE(res);
  15195. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15196. EXPECT_EQ(2, calls);
  15197. }
  15198. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15199. std::string pinned;
  15200. auto res = GetThroughTlsRedirectToDifferentPort(
  15201. [&](SSLClient &cli) {
  15202. cli.enable_server_certificate_verification(false);
  15203. // Pin the first certificate seen.
  15204. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15205. if (pinned.empty()) { pinned = ctx.serial(); }
  15206. return ctx.serial() == pinned;
  15207. });
  15208. },
  15209. // A certificate other than the first server's.
  15210. SERVER_CERT_FILE);
  15211. EXPECT_FALSE(res);
  15212. EXPECT_FALSE(pinned.empty());
  15213. }
  15214. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15215. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15216. std::string cert;
  15217. read_file(SERVER_CERT2_FILE, cert);
  15218. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15219. });
  15220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15221. EXPECT_EQ(StatusCode::OK_200, res->status);
  15222. }
  15223. // The target's certificate is signed by the root CA, which the first server's
  15224. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15225. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15226. auto res = GetThroughTlsRedirectToDifferentPort(
  15227. [](SSLClient &cli) {
  15228. std::string root_ca, cert;
  15229. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15230. read_file(SERVER_CERT2_FILE, cert);
  15231. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15232. cli.load_ca_cert_store(cert.data(), cert.size());
  15233. cli.enable_server_hostname_verification(false);
  15234. },
  15235. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15237. EXPECT_EQ(StatusCode::OK_200, res->status);
  15238. }
  15239. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15240. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15241. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15242. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15243. auto res = GetThroughTlsRedirectToDifferentPort(
  15244. [](SSLClient &cli) {
  15245. std::string root_ca, cert;
  15246. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15247. read_file(SERVER_CERT2_FILE, cert);
  15248. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15249. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15250. cli.enable_server_hostname_verification(false);
  15251. },
  15252. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15253. ASSERT_FALSE(res);
  15254. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15255. }
  15256. #endif
  15257. #endif
  15258. #ifdef CPPHTTPLIB_SSL_ENABLED
  15259. // Test that set_ca_cert_store() skips system certs (consistent with
  15260. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15261. // should be trusted - system certs should NOT be loaded.
  15262. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15263. // Load a specific cert that is NOT a system CA cert
  15264. std::string cert;
  15265. read_file(SERVER_CERT2_FILE, cert);
  15266. SSLClient cli("google.com");
  15267. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15268. cli.enable_server_certificate_verification(true);
  15269. // This should FAIL because:
  15270. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15271. // 2. System certs should NOT be loaded when custom store is set
  15272. // If system certs WERE loaded, this would succeed
  15273. auto res = cli.Get("/");
  15274. ASSERT_FALSE(res);
  15275. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15276. }
  15277. // Same as above, but through the native store handle path. Regression test:
  15278. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15279. // merged system certs into the user-provided store.
  15280. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15281. std::string cert;
  15282. read_file(SERVER_CERT2_FILE, cert);
  15283. SSLClient cli("google.com");
  15284. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15285. cli.enable_server_certificate_verification(true);
  15286. auto res = cli.Get("/");
  15287. ASSERT_FALSE(res);
  15288. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15289. }
  15290. // A custom store set via the native handle must still verify a server whose
  15291. // cert it does contain.
  15292. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15293. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15294. ASSERT_TRUE(svr.is_valid());
  15295. svr.Get("/test", [&](const Request &, Response &res) {
  15296. res.set_content("test", "text/plain");
  15297. });
  15298. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15299. auto se = detail::scope_exit([&] {
  15300. svr.stop();
  15301. t.join();
  15302. ASSERT_FALSE(svr.is_running());
  15303. });
  15304. svr.wait_until_ready();
  15305. SSLClient cli("127.0.0.1", PORT);
  15306. std::string cert;
  15307. read_file(SERVER_CERT2_FILE, cert);
  15308. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15309. cli.enable_server_certificate_verification(true);
  15310. cli.set_connection_timeout(30);
  15311. auto res = cli.Get("/test");
  15312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15313. ASSERT_EQ(StatusCode::OK_200, res->status);
  15314. }
  15315. // CA certs loaded through the universal Client must be transferred to the
  15316. // client created internally for following an HTTPS redirect. Regression test:
  15317. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15318. // the CA data for redirect transfer.
  15319. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15320. auto ssl_port = PORT + 1;
  15321. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15322. ASSERT_TRUE(ssl_svr1.is_valid());
  15323. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15324. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15325. "/index");
  15326. });
  15327. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15328. ASSERT_TRUE(ssl_svr2.is_valid());
  15329. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15330. res.set_content("test", "text/plain");
  15331. });
  15332. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15333. thread t2 =
  15334. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15335. auto se = detail::scope_exit([&] {
  15336. ssl_svr2.stop();
  15337. ssl_svr1.stop();
  15338. t2.join();
  15339. t.join();
  15340. ASSERT_FALSE(ssl_svr1.is_running());
  15341. });
  15342. ssl_svr1.wait_until_ready();
  15343. ssl_svr2.wait_until_ready();
  15344. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15345. std::string cert;
  15346. read_file(SERVER_CERT2_FILE, cert);
  15347. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15348. cli.enable_server_certificate_verification(true);
  15349. cli.set_follow_location(true);
  15350. cli.set_connection_timeout(30);
  15351. auto res = cli.Get("/index");
  15352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15353. ASSERT_EQ(StatusCode::OK_200, res->status);
  15354. }
  15355. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15356. // so a host signed by a system CA verifies even though a custom CA is set
  15357. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15358. std::string cert;
  15359. read_file(SERVER_CERT2_FILE, cert);
  15360. SSLClient cli("google.com");
  15361. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15362. cli.enable_system_ca(true);
  15363. cli.enable_server_certificate_verification(true);
  15364. auto res = cli.Get("/");
  15365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15366. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15367. }
  15368. // The custom CA remains effective when combined with the system CA
  15369. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15370. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15371. ASSERT_TRUE(svr.is_valid());
  15372. svr.Get("/test", [&](const Request &, Response &res) {
  15373. res.set_content("test", "text/plain");
  15374. });
  15375. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15376. auto se = detail::scope_exit([&] {
  15377. svr.stop();
  15378. t.join();
  15379. ASSERT_FALSE(svr.is_running());
  15380. });
  15381. svr.wait_until_ready();
  15382. SSLClient cli("127.0.0.1", PORT);
  15383. std::string cert;
  15384. read_file(SERVER_CERT2_FILE, cert);
  15385. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15386. cli.enable_system_ca(true);
  15387. cli.enable_server_certificate_verification(true);
  15388. cli.set_connection_timeout(30);
  15389. auto res = cli.Get("/test");
  15390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15391. ASSERT_EQ(StatusCode::OK_200, res->status);
  15392. }
  15393. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15394. // skip chain verification entirely (only the certificate identity was
  15395. // checked), so a server presenting an untrusted certificate with a matching
  15396. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15397. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15398. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15399. ASSERT_TRUE(svr.is_valid());
  15400. svr.Get("/test", [&](const Request &, Response &res) {
  15401. res.set_content("test", "text/plain");
  15402. });
  15403. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15404. auto se = detail::scope_exit([&] {
  15405. svr.stop();
  15406. t.join();
  15407. ASSERT_FALSE(svr.is_running());
  15408. });
  15409. svr.wait_until_ready();
  15410. SSLClient cli("127.0.0.1", PORT);
  15411. std::string cert;
  15412. // A trusted CA that did not sign the server certificate. The server cert
  15413. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15414. // this connection.
  15415. read_file(CLIENT_CA_CERT_FILE, cert);
  15416. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15417. cli.enable_server_certificate_verification(true);
  15418. cli.set_connection_timeout(30);
  15419. auto res = cli.Get("/test");
  15420. ASSERT_FALSE(res);
  15421. }
  15422. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15423. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15424. // CA that failed to come through fails verification instead of trusting them.
  15425. // (wolfSSL does not list the system CAs it loaded.)
  15426. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15427. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15428. ASSERT_TRUE(svr.is_valid());
  15429. auto port = svr.bind_to_any_port("127.0.0.1");
  15430. ASSERT_LT(0, port);
  15431. thread t = thread([&] { svr.listen_after_bind(); });
  15432. auto se = detail::scope_exit([&] {
  15433. svr.stop();
  15434. t.join();
  15435. ASSERT_FALSE(svr.is_running());
  15436. });
  15437. svr.wait_until_ready();
  15438. // The CAs a client trusts once its first request has loaded them
  15439. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15440. Client cli("https://127.0.0.1:" + std::to_string(port));
  15441. setup(cli);
  15442. cli.Get("/");
  15443. return tls::get_ca_names(cli.tls_context()).size();
  15444. };
  15445. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15446. EXPECT_EQ(0u,
  15447. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15448. }
  15449. #endif
  15450. // A PEM given to create_ca_store() needs no NUL after it
  15451. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15452. std::string pem;
  15453. read_file(SERVER_CERT2_FILE, pem);
  15454. auto buf = pem + "X";
  15455. auto store = tls::create_ca_store(buf.data(), pem.size());
  15456. EXPECT_TRUE(store != nullptr);
  15457. SSLClient cli("localhost");
  15458. cli.set_ca_cert_store(store);
  15459. }
  15460. // enable_system_ca(false) prevents system CA loading entirely
  15461. TEST(SSLClientTest, DisableSystemCa_Online) {
  15462. SSLClient cli("google.com");
  15463. cli.enable_system_ca(false);
  15464. cli.enable_server_certificate_verification(true);
  15465. auto res = cli.Get("/");
  15466. ASSERT_FALSE(res);
  15467. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15468. // itself when the CA chain is empty
  15469. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15470. res.error() == Error::SSLConnection);
  15471. }
  15472. // The universal Client forwards enable_system_ca()
  15473. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15474. std::string cert;
  15475. read_file(SERVER_CERT2_FILE, cert);
  15476. Client cli("https://google.com");
  15477. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15478. cli.enable_system_ca(true);
  15479. cli.enable_server_certificate_verification(true);
  15480. auto res = cli.Get("/");
  15481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15482. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15483. }
  15484. // The system CA policy must carry over to the client created internally for
  15485. // following a cross-host HTTPS redirect
  15486. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15487. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15488. ASSERT_TRUE(svr.is_valid());
  15489. svr.Get("/index", [&](const Request &, Response &res) {
  15490. res.set_redirect("https://www.google.com/");
  15491. });
  15492. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15493. auto se = detail::scope_exit([&] {
  15494. svr.stop();
  15495. t.join();
  15496. ASSERT_FALSE(svr.is_running());
  15497. });
  15498. svr.wait_until_ready();
  15499. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15500. std::string cert;
  15501. read_file(SERVER_CERT2_FILE, cert);
  15502. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15503. cli.enable_system_ca(true);
  15504. cli.enable_server_certificate_verification(true);
  15505. cli.set_follow_location(true);
  15506. cli.set_connection_timeout(30);
  15507. // Receiving any response proves the redirect client completed the TLS
  15508. // handshake with a system-CA-signed host
  15509. auto res = cli.Get("/index");
  15510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15511. }
  15512. TEST(MultipartFormDataTest, LargeData) {
  15513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15514. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15515. const ContentReader &content_reader) {
  15516. if (req.is_multipart_form_data()) {
  15517. std::vector<FormData> items;
  15518. content_reader(
  15519. [&](const FormData &file) {
  15520. items.push_back(file);
  15521. return true;
  15522. },
  15523. [&](const char *data, size_t data_length) {
  15524. items.back().content.append(data, data_length);
  15525. return true;
  15526. });
  15527. EXPECT_TRUE(std::string(items[0].name) == "document");
  15528. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15529. EXPECT_TRUE(items[0].filename == "2MB_data");
  15530. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15531. EXPECT_TRUE(items[1].name == "hello");
  15532. EXPECT_TRUE(items[1].content == "world");
  15533. EXPECT_TRUE(items[1].filename == "");
  15534. EXPECT_TRUE(items[1].content_type == "");
  15535. } else {
  15536. std::string body;
  15537. content_reader([&](const char *data, size_t data_length) {
  15538. body.append(data, data_length);
  15539. return true;
  15540. });
  15541. }
  15542. });
  15543. auto port = svr.bind_to_any_port(HOST);
  15544. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15545. auto se = detail::scope_exit([&] {
  15546. svr.stop();
  15547. t.join();
  15548. ASSERT_FALSE(svr.is_running());
  15549. });
  15550. svr.wait_until_ready();
  15551. {
  15552. std::string data(1024 * 1024 * 2, '.');
  15553. std::stringstream buffer;
  15554. buffer << data;
  15555. SSLClient cli(HOST, port);
  15556. cli.enable_server_certificate_verification(false);
  15557. UploadFormDataItems items{
  15558. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15559. {"hello", "world", "", ""},
  15560. };
  15561. auto res = cli.Post("/post", items);
  15562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15563. ASSERT_EQ(StatusCode::OK_200, res->status);
  15564. }
  15565. }
  15566. TEST(MultipartFormDataTest, DataProviderItems) {
  15567. std::random_device seed_gen;
  15568. std::mt19937 random(seed_gen());
  15569. std::string rand1;
  15570. rand1.resize(1000);
  15571. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15572. std::string rand2;
  15573. rand2.resize(3000);
  15574. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15576. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15577. const ContentReader &content_reader) {
  15578. ASSERT_FALSE(req.is_multipart_form_data());
  15579. std::string body;
  15580. content_reader([&](const char *data, size_t data_length) {
  15581. body.append(data, data_length);
  15582. return true;
  15583. });
  15584. EXPECT_EQ(body, "");
  15585. });
  15586. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15587. const ContentReader &content_reader) {
  15588. ASSERT_TRUE(req.is_multipart_form_data());
  15589. std::vector<FormData> items;
  15590. content_reader(
  15591. [&](const FormData &file) {
  15592. items.push_back(file);
  15593. return true;
  15594. },
  15595. [&](const char *data, size_t data_length) {
  15596. items.back().content.append(data, data_length);
  15597. return true;
  15598. });
  15599. ASSERT_TRUE(items.size() == 2);
  15600. EXPECT_EQ(std::string(items[0].name), "name1");
  15601. EXPECT_EQ(items[0].content, "Testing123");
  15602. EXPECT_EQ(items[0].filename, "filename1");
  15603. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15604. EXPECT_EQ(items[1].name, "name2");
  15605. EXPECT_EQ(items[1].content, "Testing456");
  15606. EXPECT_EQ(items[1].filename, "");
  15607. EXPECT_EQ(items[1].content_type, "");
  15608. });
  15609. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15610. const ContentReader &content_reader) {
  15611. ASSERT_TRUE(req.is_multipart_form_data());
  15612. std::vector<FormData> items;
  15613. content_reader(
  15614. [&](const FormData &file) {
  15615. items.push_back(file);
  15616. return true;
  15617. },
  15618. [&](const char *data, size_t data_length) {
  15619. items.back().content.append(data, data_length);
  15620. return true;
  15621. });
  15622. ASSERT_TRUE(items.size() == 2);
  15623. EXPECT_EQ(items[0].name, "name3");
  15624. EXPECT_EQ(items[0].content, rand1);
  15625. EXPECT_EQ(items[0].filename, "filename3");
  15626. EXPECT_EQ(items[0].content_type, "");
  15627. EXPECT_EQ(items[1].name, "name4");
  15628. EXPECT_EQ(items[1].content, rand2);
  15629. EXPECT_EQ(items[1].filename, "filename4");
  15630. EXPECT_EQ(items[1].content_type, "");
  15631. });
  15632. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15633. const ContentReader &content_reader) {
  15634. ASSERT_TRUE(req.is_multipart_form_data());
  15635. std::vector<FormData> items;
  15636. content_reader(
  15637. [&](const FormData &file) {
  15638. items.push_back(file);
  15639. return true;
  15640. },
  15641. [&](const char *data, size_t data_length) {
  15642. items.back().content.append(data, data_length);
  15643. return true;
  15644. });
  15645. ASSERT_TRUE(items.size() == 4);
  15646. EXPECT_EQ(std::string(items[0].name), "name1");
  15647. EXPECT_EQ(items[0].content, "Testing123");
  15648. EXPECT_EQ(items[0].filename, "filename1");
  15649. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15650. EXPECT_EQ(items[1].name, "name2");
  15651. EXPECT_EQ(items[1].content, "Testing456");
  15652. EXPECT_EQ(items[1].filename, "");
  15653. EXPECT_EQ(items[1].content_type, "");
  15654. EXPECT_EQ(items[2].name, "name3");
  15655. EXPECT_EQ(items[2].content, rand1);
  15656. EXPECT_EQ(items[2].filename, "filename3");
  15657. EXPECT_EQ(items[2].content_type, "");
  15658. EXPECT_EQ(items[3].name, "name4");
  15659. EXPECT_EQ(items[3].content, rand2);
  15660. EXPECT_EQ(items[3].filename, "filename4");
  15661. EXPECT_EQ(items[3].content_type, "");
  15662. });
  15663. auto port = svr.bind_to_any_port("localhost");
  15664. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15665. auto se = detail::scope_exit([&] {
  15666. svr.stop();
  15667. t.join();
  15668. ASSERT_FALSE(svr.is_running());
  15669. });
  15670. svr.wait_until_ready();
  15671. {
  15672. SSLClient cli("localhost", port);
  15673. cli.enable_server_certificate_verification(false);
  15674. UploadFormDataItems items{
  15675. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15676. {"name2", "Testing456", "", ""}, // not a file
  15677. };
  15678. {
  15679. auto res = cli.Post("/post-none", {}, {}, {});
  15680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15681. ASSERT_EQ(StatusCode::OK_200, res->status);
  15682. }
  15683. FormDataProviderItems providers;
  15684. {
  15685. auto res =
  15686. cli.Post("/post-items", {}, items, providers); // empty providers
  15687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15688. ASSERT_EQ(StatusCode::OK_200, res->status);
  15689. }
  15690. providers.push_back({"name3",
  15691. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15692. // test the offset is given correctly at each step
  15693. if (!offset)
  15694. sink.os.write(rand1.data(), 30);
  15695. else if (offset == 30)
  15696. sink.os.write(rand1.data() + 30, 300);
  15697. else if (offset == 330)
  15698. sink.os.write(rand1.data() + 330, 670);
  15699. else if (offset == rand1.size())
  15700. sink.done();
  15701. return true;
  15702. },
  15703. "filename3",
  15704. {}});
  15705. providers.push_back({"name4",
  15706. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15707. // test the offset is given correctly at each step
  15708. if (!offset)
  15709. sink.os.write(rand2.data(), 2000);
  15710. else if (offset == 2000)
  15711. sink.os.write(rand2.data() + 2000, 1);
  15712. else if (offset == 2001)
  15713. sink.os.write(rand2.data() + 2001, 999);
  15714. else if (offset == rand2.size())
  15715. sink.done();
  15716. return true;
  15717. },
  15718. "filename4",
  15719. {}});
  15720. {
  15721. auto res = cli.Post("/post-providers", {}, {}, providers);
  15722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15723. ASSERT_EQ(StatusCode::OK_200, res->status);
  15724. }
  15725. {
  15726. auto res = cli.Post("/post-both", {}, items, providers);
  15727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15728. ASSERT_EQ(StatusCode::OK_200, res->status);
  15729. }
  15730. }
  15731. }
  15732. TEST(MultipartFormDataTest, BadHeader) {
  15733. Server svr;
  15734. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15735. res.set_content("ok", "text/plain");
  15736. });
  15737. thread t = thread([&] { svr.listen(HOST, PORT); });
  15738. auto se = detail::scope_exit([&] {
  15739. svr.stop();
  15740. t.join();
  15741. ASSERT_FALSE(svr.is_running());
  15742. });
  15743. svr.wait_until_ready();
  15744. const std::string body =
  15745. "This is the preamble. It is to be ignored, though it\r\n"
  15746. "is a handy place for composition agents to include an\r\n"
  15747. "explanatory note to non-MIME conformant readers.\r\n"
  15748. "\r\n"
  15749. "\r\n"
  15750. "--simple boundary\r\n"
  15751. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15752. ": BAD...\r\n"
  15753. "\r\n"
  15754. "value1\r\n"
  15755. "--simple boundary\r\n"
  15756. "Content-Disposition: form-data; name=\"field2\"; "
  15757. "filename=\"example.txt\"\r\n"
  15758. "\r\n"
  15759. "value2\r\n"
  15760. "--simple boundary--\r\n"
  15761. "This is the epilogue. It is also to be ignored.\r\n";
  15762. std::string content_type =
  15763. R"(multipart/form-data; boundary="simple boundary")";
  15764. Client cli(HOST, PORT);
  15765. auto res = cli.Post("/post", body, content_type.c_str());
  15766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15767. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15768. }
  15769. TEST(MultipartFormDataTest, WithPreamble) {
  15770. Server svr;
  15771. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15772. res.set_content("ok", "text/plain");
  15773. });
  15774. thread t = thread([&] { svr.listen(HOST, PORT); });
  15775. auto se = detail::scope_exit([&] {
  15776. svr.stop();
  15777. t.join();
  15778. ASSERT_FALSE(svr.is_running());
  15779. });
  15780. svr.wait_until_ready();
  15781. const std::string body =
  15782. "This is the preamble. It is to be ignored, though it\r\n"
  15783. "is a handy place for composition agents to include an\r\n"
  15784. "explanatory note to non-MIME conformant readers.\r\n"
  15785. "\r\n"
  15786. "\r\n"
  15787. "--simple boundary\r\n"
  15788. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15789. "\r\n"
  15790. "value1\r\n"
  15791. "--simple boundary\r\n"
  15792. "Content-Disposition: form-data; name=\"field2\"; "
  15793. "filename=\"example.txt\"\r\n"
  15794. "\r\n"
  15795. "value2\r\n"
  15796. "--simple boundary--\r\n"
  15797. "This is the epilogue. It is also to be ignored.\r\n";
  15798. std::string content_type =
  15799. R"(multipart/form-data; boundary="simple boundary")";
  15800. Client cli(HOST, PORT);
  15801. auto res = cli.Post("/post", body, content_type.c_str());
  15802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15803. EXPECT_EQ(StatusCode::OK_200, res->status);
  15804. }
  15805. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15807. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15808. const ContentReader &content_reader) {
  15809. if (req.is_multipart_form_data()) {
  15810. std::vector<FormData> items;
  15811. content_reader(
  15812. [&](const FormData &file) {
  15813. items.push_back(file);
  15814. return true;
  15815. },
  15816. [&](const char *data, size_t data_length) {
  15817. items.back().content.append(data, data_length);
  15818. return true;
  15819. });
  15820. EXPECT_TRUE(std::string(items[0].name) == "document");
  15821. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15822. EXPECT_TRUE(items[0].filename == "2MB_data");
  15823. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15824. EXPECT_TRUE(items[1].name == "hello");
  15825. EXPECT_TRUE(items[1].content == "world");
  15826. EXPECT_TRUE(items[1].filename == "");
  15827. EXPECT_TRUE(items[1].content_type == "");
  15828. } else {
  15829. std::string body;
  15830. content_reader([&](const char *data, size_t data_length) {
  15831. body.append(data, data_length);
  15832. return true;
  15833. });
  15834. }
  15835. });
  15836. auto port = svr.bind_to_any_port("localhost");
  15837. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15838. auto se = detail::scope_exit([&] {
  15839. svr.stop();
  15840. t.join();
  15841. ASSERT_FALSE(svr.is_running());
  15842. });
  15843. svr.wait_until_ready();
  15844. {
  15845. std::string data(1024 * 1024 * 2, '.');
  15846. std::stringstream buffer;
  15847. buffer << data;
  15848. SSLClient cli("localhost", port);
  15849. cli.enable_server_certificate_verification(false);
  15850. UploadFormDataItems items{
  15851. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15852. {"hello", "world", "", ""},
  15853. };
  15854. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15856. ASSERT_EQ(StatusCode::OK_200, res->status);
  15857. }
  15858. }
  15859. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15860. std::string data(1024 * 1024 * 2, '&');
  15861. std::stringstream buffer;
  15862. buffer << data;
  15863. Client cli("https://localhost:8080");
  15864. UploadFormDataItems items{
  15865. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15866. {"hello", "world", "", ""},
  15867. };
  15868. for (const char &c : " \t\r\n") {
  15869. auto res =
  15870. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15871. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15872. ASSERT_FALSE(res);
  15873. }
  15874. }
  15875. TEST(MultipartFormDataTest, PutFormData) {
  15876. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15877. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15878. const ContentReader &content_reader) {
  15879. if (req.is_multipart_form_data()) {
  15880. std::vector<FormData> items;
  15881. content_reader(
  15882. [&](const FormData &file) {
  15883. items.push_back(file);
  15884. return true;
  15885. },
  15886. [&](const char *data, size_t data_length) {
  15887. items.back().content.append(data, data_length);
  15888. return true;
  15889. });
  15890. EXPECT_TRUE(std::string(items[0].name) == "document");
  15891. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15892. EXPECT_TRUE(items[0].filename == "2MB_data");
  15893. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15894. EXPECT_TRUE(items[1].name == "hello");
  15895. EXPECT_TRUE(items[1].content == "world");
  15896. EXPECT_TRUE(items[1].filename == "");
  15897. EXPECT_TRUE(items[1].content_type == "");
  15898. } else {
  15899. std::string body;
  15900. content_reader([&](const char *data, size_t data_length) {
  15901. body.append(data, data_length);
  15902. return true;
  15903. });
  15904. }
  15905. });
  15906. auto port = svr.bind_to_any_port("localhost");
  15907. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15908. auto se = detail::scope_exit([&] {
  15909. svr.stop();
  15910. t.join();
  15911. ASSERT_FALSE(svr.is_running());
  15912. });
  15913. svr.wait_until_ready();
  15914. {
  15915. std::string data(1024 * 1024 * 2, '&');
  15916. std::stringstream buffer;
  15917. buffer << data;
  15918. SSLClient cli("localhost", port);
  15919. cli.enable_server_certificate_verification(false);
  15920. UploadFormDataItems items{
  15921. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15922. {"hello", "world", "", ""},
  15923. };
  15924. auto res = cli.Put("/put", items);
  15925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15926. ASSERT_EQ(StatusCode::OK_200, res->status);
  15927. }
  15928. }
  15929. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15931. svr.Put("/put_customboundary",
  15932. [&](const Request &req, const Response & /*res*/,
  15933. const ContentReader &content_reader) {
  15934. if (req.is_multipart_form_data()) {
  15935. std::vector<FormData> items;
  15936. content_reader(
  15937. [&](const FormData &file) {
  15938. items.push_back(file);
  15939. return true;
  15940. },
  15941. [&](const char *data, size_t data_length) {
  15942. items.back().content.append(data, data_length);
  15943. return true;
  15944. });
  15945. EXPECT_TRUE(std::string(items[0].name) == "document");
  15946. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15947. EXPECT_TRUE(items[0].filename == "2MB_data");
  15948. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15949. EXPECT_TRUE(items[1].name == "hello");
  15950. EXPECT_TRUE(items[1].content == "world");
  15951. EXPECT_TRUE(items[1].filename == "");
  15952. EXPECT_TRUE(items[1].content_type == "");
  15953. } else {
  15954. std::string body;
  15955. content_reader([&](const char *data, size_t data_length) {
  15956. body.append(data, data_length);
  15957. return true;
  15958. });
  15959. }
  15960. });
  15961. auto port = svr.bind_to_any_port("localhost");
  15962. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15963. auto se = detail::scope_exit([&] {
  15964. svr.stop();
  15965. t.join();
  15966. ASSERT_FALSE(svr.is_running());
  15967. });
  15968. svr.wait_until_ready();
  15969. {
  15970. std::string data(1024 * 1024 * 2, '&');
  15971. std::stringstream buffer;
  15972. buffer << data;
  15973. SSLClient cli("localhost", port);
  15974. cli.enable_server_certificate_verification(false);
  15975. UploadFormDataItems items{
  15976. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15977. {"hello", "world", "", ""},
  15978. };
  15979. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15981. ASSERT_EQ(StatusCode::OK_200, res->status);
  15982. }
  15983. }
  15984. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15985. std::string data(1024 * 1024 * 2, '&');
  15986. std::stringstream buffer;
  15987. buffer << data;
  15988. Client cli("https://localhost:8080");
  15989. cli.enable_server_certificate_verification(false);
  15990. UploadFormDataItems items{
  15991. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15992. {"hello", "world", "", ""},
  15993. };
  15994. for (const char &c : " \t\r\n") {
  15995. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15996. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15997. ASSERT_FALSE(res);
  15998. }
  15999. }
  16000. TEST(MultipartFormDataTest, AlternateFilename) {
  16001. auto handled = false;
  16002. Server svr;
  16003. svr.Post("/test", [&](const Request &req, Response &res) {
  16004. ASSERT_EQ(2u, req.form.files.size());
  16005. ASSERT_EQ(1u, req.form.fields.size());
  16006. // Test files
  16007. const auto &file1 = req.form.get_file("file1");
  16008. ASSERT_EQ("file1", file1.name);
  16009. ASSERT_EQ("A.txt", file1.filename);
  16010. ASSERT_EQ("text/plain", file1.content_type);
  16011. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16012. const auto &file2 = req.form.get_file("file2");
  16013. ASSERT_EQ("file2", file2.name);
  16014. ASSERT_EQ("a.html", file2.filename);
  16015. ASSERT_EQ("text/html", file2.content_type);
  16016. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16017. file2.content);
  16018. // Test text field
  16019. const auto &text = req.form.get_field("text");
  16020. ASSERT_EQ("text default", text);
  16021. res.set_content("ok", "text/plain");
  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: 399\r\n"
  16036. "\r\n"
  16037. "----------\r\n"
  16038. "Content-Disposition: form-data; name=\"text\"\r\n"
  16039. "\r\n"
  16040. "text default\r\n"
  16041. "----------\r\n"
  16042. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16043. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16044. "Content-Type: text/plain\r\n"
  16045. "\r\n"
  16046. "Content of a.txt.\r\n"
  16047. "\r\n"
  16048. "----------\r\n"
  16049. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16050. "\"a.html\"\r\n"
  16051. "Content-Type: text/html\r\n"
  16052. "\r\n"
  16053. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16054. "\r\n"
  16055. "------------\r\n";
  16056. ASSERT_TRUE(send_request(1, req));
  16057. }
  16058. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16059. auto handled = false;
  16060. Server svr;
  16061. svr.Post("/test", [&](const Request &req, Response &res) {
  16062. // Case-insensitive "utf-8''" prefix with a long value
  16063. const auto &file = req.form.get_file("file1");
  16064. ASSERT_EQ("file1", file.name);
  16065. // 8000 chars exercises both the Content-Disposition parser and the
  16066. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16067. // Prior to the fix, std::regex_match on this header would cause O(N)
  16068. // stack recursion in libstdc++, leading to SIGSEGV.
  16069. std::string expected_filename(8000, 'A');
  16070. ASSERT_EQ(expected_filename, file.filename);
  16071. res.set_content("ok", "text/plain");
  16072. handled = true;
  16073. });
  16074. thread t = thread([&] { svr.listen(HOST, PORT); });
  16075. auto se = detail::scope_exit([&] {
  16076. svr.stop();
  16077. t.join();
  16078. ASSERT_FALSE(svr.is_running());
  16079. ASSERT_TRUE(handled);
  16080. });
  16081. svr.wait_until_ready();
  16082. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16083. // Regression test for GHSA-qq6v-r583-3h69
  16084. std::string long_filename(8000, 'A');
  16085. std::string body = "----------\r\n"
  16086. "Content-Disposition: form-data; name=\"file1\"; "
  16087. "filename*=\"Utf-8''" +
  16088. long_filename +
  16089. "\"\r\n"
  16090. "\r\n"
  16091. "hello\r\n"
  16092. "------------\r\n";
  16093. auto req = "POST /test HTTP/1.1\r\n"
  16094. "Host: localhost\r\n"
  16095. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16096. "Content-Length: " +
  16097. std::to_string(body.size()) + "\r\n\r\n" + body;
  16098. ASSERT_TRUE(send_request(1, req));
  16099. }
  16100. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16101. auto handled = false;
  16102. Server svr;
  16103. svr.Post("/test", [&](const Request &req, Response &) {
  16104. ASSERT_EQ(2u, req.form.fields.size());
  16105. const auto &text1 = req.form.get_field("text1");
  16106. ASSERT_EQ("text1", text1);
  16107. const auto &text2 = req.form.get_field("text2");
  16108. ASSERT_EQ("text2", text2);
  16109. handled = true;
  16110. });
  16111. thread t = thread([&] { svr.listen(HOST, PORT); });
  16112. auto se = detail::scope_exit([&] {
  16113. svr.stop();
  16114. t.join();
  16115. ASSERT_FALSE(svr.is_running());
  16116. ASSERT_TRUE(handled);
  16117. });
  16118. svr.wait_until_ready();
  16119. auto req = "POST /test HTTP/1.1\r\n"
  16120. "Host: localhost\r\n"
  16121. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16122. "Content-Length: 146\r\n"
  16123. "\r\n----------\r\n"
  16124. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16125. "\r\n"
  16126. "text1"
  16127. "\r\n----------\r\n"
  16128. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16129. "\r\n"
  16130. "text2"
  16131. "\r\n------------";
  16132. std::string response;
  16133. ASSERT_TRUE(send_request(1, req, &response));
  16134. ASSERT_EQ("200", response.substr(9, 3));
  16135. }
  16136. TEST(MultipartFormDataTest, ContentLength) {
  16137. auto handled = false;
  16138. Server svr;
  16139. svr.Post("/test", [&](const Request &req, Response &) {
  16140. ASSERT_EQ(2u, req.form.fields.size());
  16141. const auto &text1 = req.form.get_field("text1");
  16142. ASSERT_EQ("text1", text1);
  16143. const auto &text2 = req.form.get_field("text2");
  16144. ASSERT_EQ("text2", text2);
  16145. handled = true;
  16146. });
  16147. thread t = thread([&] { svr.listen(HOST, PORT); });
  16148. auto se = detail::scope_exit([&] {
  16149. svr.stop();
  16150. t.join();
  16151. ASSERT_FALSE(svr.is_running());
  16152. ASSERT_TRUE(handled);
  16153. });
  16154. svr.wait_until_ready();
  16155. auto req = "POST /test HTTP/1.1\r\n"
  16156. "Host: localhost\r\n"
  16157. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16158. "Content-Length: 167\r\n"
  16159. "\r\n----------\r\n"
  16160. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16161. "Content-Length: 5\r\n"
  16162. "\r\n"
  16163. "text1"
  16164. "\r\n----------\r\n"
  16165. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16166. "\r\n"
  16167. "text2"
  16168. "\r\n------------\r\n";
  16169. std::string response;
  16170. ASSERT_TRUE(send_request(1, req, &response));
  16171. ASSERT_EQ("200", response.substr(9, 3));
  16172. }
  16173. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16174. auto handled = false;
  16175. Server svr;
  16176. svr.Post("/test", [&](const Request &req, Response &) {
  16177. ASSERT_EQ(2u, req.form.fields.size());
  16178. const auto &text1 = req.form.get_field("text1");
  16179. ASSERT_EQ("text1", text1);
  16180. // TODO: Add header access for text fields if needed
  16181. const auto &text2 = req.form.get_field("text2");
  16182. ASSERT_EQ("text2", text2);
  16183. // TODO: Header access for text fields needs to be implemented
  16184. // auto &headers = it->second.headers;
  16185. // ASSERT_EQ(3U, headers.size());
  16186. // auto custom_header = headers.find("x-whatever");
  16187. // ASSERT_TRUE(custom_header != headers.end());
  16188. // ASSERT_NE("customvalue", custom_header->second);
  16189. // ASSERT_EQ("CustomValue", custom_header->second);
  16190. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16191. handled = true;
  16192. });
  16193. thread t = thread([&] { svr.listen(HOST, PORT); });
  16194. auto se = detail::scope_exit([&] {
  16195. svr.stop();
  16196. t.join();
  16197. ASSERT_FALSE(svr.is_running());
  16198. ASSERT_TRUE(handled);
  16199. });
  16200. svr.wait_until_ready();
  16201. auto req = "POST /test HTTP/1.1\r\n"
  16202. "Host: localhost\r\n"
  16203. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16204. "Content-Length: 232\r\n"
  16205. "\r\n----------\r\n"
  16206. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16207. "Content-Length: 5\r\n"
  16208. "X-Test: 1\r\n"
  16209. "\r\n"
  16210. "text1"
  16211. "\r\n----------\r\n"
  16212. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16213. "Content-Type: text/plain\r\n"
  16214. "X-Whatever: CustomValue\r\n"
  16215. "\r\n"
  16216. "text2"
  16217. "\r\n------------\r\n"
  16218. "That should be disregarded. Not even read";
  16219. std::string response;
  16220. ASSERT_TRUE(send_request(1, req, &response));
  16221. ASSERT_EQ("200", response.substr(9, 3));
  16222. }
  16223. TEST(MultipartFormDataTest, LargeHeader) {
  16224. auto handled = false;
  16225. Server svr;
  16226. svr.Post("/test", [&](const Request &req, Response &) {
  16227. ASSERT_EQ(1u, req.form.fields.size());
  16228. const auto &text = req.form.get_field("name1");
  16229. ASSERT_EQ("text1", text);
  16230. handled = true;
  16231. });
  16232. thread t = thread([&] { svr.listen(HOST, PORT); });
  16233. auto se = detail::scope_exit([&] {
  16234. svr.stop();
  16235. t.join();
  16236. ASSERT_FALSE(svr.is_running());
  16237. ASSERT_TRUE(handled);
  16238. });
  16239. svr.wait_until_ready();
  16240. auto boundary = std::string("cpp-httplib-multipart-data");
  16241. std::string content = "--" + boundary +
  16242. "\r\n"
  16243. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16244. "\r\n"
  16245. "text1\r\n"
  16246. "--" +
  16247. boundary + "--\r\n";
  16248. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16249. "Host: localhost\r\n"
  16250. "Content-Type: multipart/form-data;boundary=" +
  16251. boundary +
  16252. "\r\n"
  16253. "Content-Length: " +
  16254. std::to_string(content.size()) +
  16255. "\r\n"
  16256. "Dummy-Header: ";
  16257. std::string header_suffix = "\r\n"
  16258. "\r\n";
  16259. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16260. size_t header_dummy_size =
  16261. read_buff_size -
  16262. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16263. auto header_dummy = std::string(header_dummy_size, '@');
  16264. auto req = header_prefix + header_dummy + header_suffix + content;
  16265. std::string response;
  16266. ASSERT_TRUE(send_request(1, req, &response));
  16267. ASSERT_EQ("200", response.substr(9, 3));
  16268. }
  16269. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16270. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16271. // (not chunked Transfer-Encoding) after the streaming refactor.
  16272. auto handled = false;
  16273. Server svr;
  16274. svr.Post("/upload", [&](const Request &req, Response &res) {
  16275. auto cl_it = req.headers.find("Content-Length");
  16276. EXPECT_TRUE(cl_it != req.headers.end());
  16277. auto te_it = req.headers.find("Transfer-Encoding");
  16278. EXPECT_TRUE(te_it == req.headers.end());
  16279. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16280. res.set_content("ok", "text/plain");
  16281. handled = true;
  16282. });
  16283. auto port = svr.bind_to_any_port(HOST);
  16284. auto t = thread([&] { svr.listen_after_bind(); });
  16285. auto se = detail::scope_exit([&] {
  16286. svr.stop();
  16287. t.join();
  16288. ASSERT_FALSE(svr.is_running());
  16289. ASSERT_TRUE(handled);
  16290. });
  16291. svr.wait_until_ready();
  16292. UploadFormDataItems items = {
  16293. {"field1", "hello", "", "text/plain"},
  16294. {"file1", "world", "test.txt", "application/octet-stream"},
  16295. };
  16296. Client cli(HOST, port);
  16297. auto res = cli.Post("/upload", {}, items);
  16298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16299. EXPECT_EQ(StatusCode::OK_200, res->status);
  16300. }
  16301. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16302. // Verify that make_multipart_content_provider coalesces many small segments
  16303. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16304. constexpr size_t kItemCount = 1000;
  16305. UploadFormDataItems items;
  16306. items.reserve(kItemCount);
  16307. for (size_t i = 0; i < kItemCount; i++) {
  16308. items.push_back(
  16309. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16310. }
  16311. const std::string boundary = "----test-boundary";
  16312. auto content_length = detail::get_multipart_content_length(items, boundary);
  16313. auto provider = detail::make_multipart_content_provider(items, boundary);
  16314. // Drive the provider the same way write_content_with_progress does
  16315. size_t write_count = 0;
  16316. size_t total_bytes = 0;
  16317. DataSink sink;
  16318. size_t offset = 0;
  16319. sink.write = [&](const char *d, size_t l) -> bool {
  16320. (void)d;
  16321. write_count++;
  16322. total_bytes += l;
  16323. offset += l;
  16324. return true;
  16325. };
  16326. sink.is_writable = []() -> bool { return true; };
  16327. while (offset < content_length) {
  16328. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16329. }
  16330. EXPECT_EQ(content_length, total_bytes);
  16331. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16332. // With buffering into 64KB blocks, write_count should be much smaller.
  16333. auto segment_count = 3 * kItemCount + 1;
  16334. EXPECT_LT(write_count, segment_count / 10);
  16335. }
  16336. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16337. // Integration test: send many UploadFormDataItems and verify the server
  16338. // receives all of them correctly (#2410).
  16339. constexpr size_t kItemCount = 500;
  16340. auto handled = false;
  16341. Server svr;
  16342. svr.Post("/upload", [&](const Request &req, Response &res) {
  16343. EXPECT_EQ(kItemCount, req.form.fields.size());
  16344. for (size_t i = 0; i < kItemCount; i++) {
  16345. auto key = "field" + std::to_string(i);
  16346. auto val = "value" + std::to_string(i);
  16347. auto it = req.form.fields.find(key);
  16348. if (it != req.form.fields.end()) {
  16349. EXPECT_EQ(val, it->second.content);
  16350. } else {
  16351. ADD_FAILURE() << "Missing field: " << key;
  16352. }
  16353. }
  16354. res.set_content("ok", "text/plain");
  16355. handled = true;
  16356. });
  16357. auto port = svr.bind_to_any_port(HOST);
  16358. auto t = thread([&] { svr.listen_after_bind(); });
  16359. auto se = detail::scope_exit([&] {
  16360. svr.stop();
  16361. t.join();
  16362. ASSERT_FALSE(svr.is_running());
  16363. ASSERT_TRUE(handled);
  16364. });
  16365. svr.wait_until_ready();
  16366. UploadFormDataItems items;
  16367. items.reserve(kItemCount);
  16368. for (size_t i = 0; i < kItemCount; i++) {
  16369. items.push_back(
  16370. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16371. }
  16372. Client cli(HOST, port);
  16373. auto res = cli.Post("/upload", items);
  16374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16375. EXPECT_EQ(StatusCode::OK_200, res->status);
  16376. }
  16377. TEST(MultipartFormDataTest, MakeFileProvider) {
  16378. // Verify make_file_provider sends a file's contents correctly.
  16379. const std::string file_content(4096, 'Z');
  16380. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16381. {
  16382. std::ofstream ofs(tmp_path, std::ios::binary);
  16383. ofs.write(file_content.data(),
  16384. static_cast<std::streamsize>(file_content.size()));
  16385. }
  16386. auto handled = false;
  16387. Server svr;
  16388. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16389. const ContentReader &content_reader) {
  16390. ASSERT_TRUE(req.is_multipart_form_data());
  16391. std::vector<FormData> items;
  16392. content_reader(
  16393. [&](const FormData &file) {
  16394. items.push_back(file);
  16395. return true;
  16396. },
  16397. [&](const char *data, size_t data_length) {
  16398. items.back().content.append(data, data_length);
  16399. return true;
  16400. });
  16401. ASSERT_EQ(1u, items.size());
  16402. EXPECT_EQ("myfile", items[0].name);
  16403. EXPECT_EQ("data.bin", items[0].filename);
  16404. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16405. EXPECT_EQ(file_content, items[0].content);
  16406. handled = true;
  16407. });
  16408. auto port = svr.bind_to_any_port(HOST);
  16409. auto t = thread([&] { svr.listen_after_bind(); });
  16410. auto se = detail::scope_exit([&] {
  16411. svr.stop();
  16412. t.join();
  16413. ASSERT_FALSE(svr.is_running());
  16414. ASSERT_TRUE(handled);
  16415. std::remove(tmp_path.c_str());
  16416. });
  16417. svr.wait_until_ready();
  16418. FormDataProviderItems providers;
  16419. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16420. "application/octet-stream"));
  16421. Client cli(HOST, port);
  16422. auto res = cli.Post("/upload", {}, {}, providers);
  16423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16424. EXPECT_EQ(StatusCode::OK_200, res->status);
  16425. }
  16426. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16427. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16428. // (100) headers is rejected with a 400 Bad Request response.
  16429. Server svr;
  16430. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16431. res.set_content("ok", "text/plain");
  16432. });
  16433. thread t = thread([&] { svr.listen(HOST, PORT); });
  16434. auto se = detail::scope_exit([&] {
  16435. svr.stop();
  16436. t.join();
  16437. ASSERT_FALSE(svr.is_running());
  16438. });
  16439. svr.wait_until_ready();
  16440. // Build a multipart part with 101 custom headers (exceeding
  16441. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16442. std::stringstream body;
  16443. body << "--simpleboundary\r\n"
  16444. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16445. for (int i = 0; i < 101; i++) {
  16446. body << "X-Custom-Header-" << i << ": value\r\n";
  16447. }
  16448. body << "\r\n"
  16449. << "value1\r\n"
  16450. << "--simpleboundary--\r\n";
  16451. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16452. Client cli(HOST, PORT);
  16453. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16455. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16456. }
  16457. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16458. // A body that never contains the declared boundary must not be accumulated
  16459. // while the parser waits for it. Buffering it would also make every read
  16460. // rescan everything seen so far, which is quadratic in the body size.
  16461. Server svr;
  16462. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16463. res.set_content("ok", "text/plain");
  16464. });
  16465. auto port = svr.bind_to_any_port(HOST);
  16466. thread t = thread([&] { svr.listen_after_bind(); });
  16467. auto se = detail::scope_exit([&] {
  16468. svr.stop();
  16469. t.join();
  16470. ASSERT_FALSE(svr.is_running());
  16471. });
  16472. svr.wait_until_ready();
  16473. Client cli(HOST, port);
  16474. cli.set_read_timeout(60, 0);
  16475. cli.set_write_timeout(60, 0);
  16476. // '-' is the worst case: it matches the first character of the boundary, so
  16477. // every position has to be checked against it.
  16478. auto post_dashes = [&](size_t size) {
  16479. const std::string body(size, '-');
  16480. auto start = std::chrono::steady_clock::now();
  16481. auto res =
  16482. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16483. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16484. std::chrono::steady_clock::now() - start)
  16485. .count();
  16486. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16487. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16488. return ms;
  16489. };
  16490. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16491. // Windows.
  16492. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16493. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16494. // Comparing the two sizes rather than checking an absolute duration keeps
  16495. // this meaningful across build types and CI load, both of which move the
  16496. // absolute numbers by more than an order of magnitude. Four times the bytes
  16497. // costs about four times the time when parsing is linear, and about sixteen
  16498. // times when the body is buffered and rescanned.
  16499. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16500. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16501. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16502. << "ms, which suggests the body is being buffered and rescanned";
  16503. }
  16504. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16505. // A boundary can only be followed by CRLF or by "--", so anything else is
  16506. // malformed no matter what comes next. The parser must say so right away
  16507. // instead of buffering the rest of the declared body.
  16508. Server svr;
  16509. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16510. res.set_content("ok", "text/plain");
  16511. });
  16512. auto port = svr.bind_to_any_port(HOST);
  16513. thread t = thread([&] { svr.listen_after_bind(); });
  16514. auto se = detail::scope_exit([&] {
  16515. svr.stop();
  16516. t.join();
  16517. ASSERT_FALSE(svr.is_running());
  16518. });
  16519. svr.wait_until_ready();
  16520. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16521. // buffers instead of failing would still be waiting for the remaining bytes.
  16522. const std::string body = "--zzzz\r\n"
  16523. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16524. "\r\n"
  16525. "text1"
  16526. "\r\n--zzzzXX";
  16527. const std::string req = "POST /post HTTP/1.1\r\n"
  16528. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16529. "Content-Length: 1048576\r\n"
  16530. "\r\n" +
  16531. body;
  16532. std::string response;
  16533. ASSERT_TRUE(send_request(3, req, &response, port));
  16534. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16535. EXPECT_EQ("400", response.substr(9, 3));
  16536. }
  16537. // Posts a multipart body split into two writes, so that the server sees the
  16538. // split at whatever offset the caller chose, and expects the single "text1"
  16539. // field to come through.
  16540. static void expect_split_multipart_ok(const std::string &body1,
  16541. const std::string &body2) {
  16542. auto handled = false;
  16543. Server svr;
  16544. svr.Post("/post", [&](const Request &req, Response &) {
  16545. EXPECT_EQ(1u, req.form.fields.size());
  16546. EXPECT_EQ("text1", req.form.get_field("text1"));
  16547. handled = true;
  16548. });
  16549. auto port = svr.bind_to_any_port(HOST);
  16550. thread t = thread([&] { svr.listen_after_bind(); });
  16551. auto se = detail::scope_exit([&] {
  16552. svr.stop();
  16553. t.join();
  16554. ASSERT_FALSE(svr.is_running());
  16555. ASSERT_TRUE(handled);
  16556. });
  16557. svr.wait_until_ready();
  16558. // "Connection: close" makes the server close once it has answered, so the
  16559. // response drain ends immediately instead of idling until the read timeout.
  16560. const std::string head =
  16561. "POST /post HTTP/1.1\r\n"
  16562. "Host: localhost\r\n"
  16563. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16564. "Connection: close\r\n"
  16565. "Content-Length: " +
  16566. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16567. std::string response;
  16568. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16569. ASSERT_GE(response.size(), 12u) << "no response";
  16570. EXPECT_EQ("200", response.substr(9, 3));
  16571. }
  16572. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16573. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16574. // ignored, including when it does not arrive in the same read as the
  16575. // close-delimiter itself.
  16576. expect_split_multipart_ok("--zzzz\r\n"
  16577. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16578. "\r\n"
  16579. "text1"
  16580. "\r\n--zzzz--",
  16581. "\r\nthis epilogue must be ignored\r\n");
  16582. }
  16583. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16584. // The initial boundary may be preceded by a preamble of any length and may
  16585. // straddle a read boundary. Discarding data while waiting for it must not
  16586. // throw away a partial boundary sitting at the end of the buffer.
  16587. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16588. "zz\r\n"
  16589. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16590. "\r\n"
  16591. "text1"
  16592. "\r\n--zzzz--\r\n");
  16593. }
  16594. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16595. // The received boundary was only checked for being non-empty, so it could be
  16596. // as long as a header is allowed to be. The parser scans the body for
  16597. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16598. // costs a nearly full comparison at nearly every position, making the
  16599. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16600. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16601. Server svr;
  16602. svr.Post("/post", [](const Request &req, Response &res) {
  16603. EXPECT_EQ(1u, req.form.fields.size());
  16604. EXPECT_EQ("text1", req.form.get_field("text1"));
  16605. res.set_content("ok", "text/plain");
  16606. });
  16607. auto port = svr.bind_to_any_port(HOST);
  16608. thread t = thread([&] { svr.listen_after_bind(); });
  16609. auto se = detail::scope_exit([&] {
  16610. svr.stop();
  16611. t.join();
  16612. ASSERT_FALSE(svr.is_running());
  16613. });
  16614. svr.wait_until_ready();
  16615. Client cli(HOST, port);
  16616. auto post_with_boundary_of_length = [&](size_t len) {
  16617. const std::string boundary(len, 'a');
  16618. const std::string body =
  16619. "--" + boundary +
  16620. "\r\n"
  16621. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16622. "\r\n"
  16623. "text1"
  16624. "\r\n--" +
  16625. boundary + "--\r\n";
  16626. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16627. };
  16628. auto res = post_with_boundary_of_length(70);
  16629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16630. EXPECT_EQ(StatusCode::OK_200, res->status);
  16631. res = post_with_boundary_of_length(71);
  16632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16633. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16634. }
  16635. TEST(MakeFileBodyTest, Basic) {
  16636. const std::string file_content(4096, 'Z');
  16637. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16638. {
  16639. std::ofstream ofs(tmp_path, std::ios::binary);
  16640. ofs.write(file_content.data(),
  16641. static_cast<std::streamsize>(file_content.size()));
  16642. }
  16643. auto handled = false;
  16644. Server svr;
  16645. svr.Post("/upload", [&](const Request &req, Response &res) {
  16646. EXPECT_EQ(file_content, req.body);
  16647. handled = true;
  16648. res.status = StatusCode::OK_200;
  16649. });
  16650. auto port = svr.bind_to_any_port(HOST);
  16651. auto t = thread([&] { svr.listen_after_bind(); });
  16652. auto se = detail::scope_exit([&] {
  16653. svr.stop();
  16654. t.join();
  16655. ASSERT_FALSE(svr.is_running());
  16656. ASSERT_TRUE(handled);
  16657. std::remove(tmp_path.c_str());
  16658. });
  16659. svr.wait_until_ready();
  16660. auto fb = make_file_body(tmp_path);
  16661. ASSERT_GT(fb.first, 0u);
  16662. Client cli(HOST, port);
  16663. auto res =
  16664. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16666. EXPECT_EQ(StatusCode::OK_200, res->status);
  16667. }
  16668. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16669. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16670. {
  16671. std::ofstream ofs(path, std::ios::binary);
  16672. const std::string content(100, 'A');
  16673. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16674. }
  16675. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16676. auto body = make_file_body(path);
  16677. ASSERT_EQ(100u, body.first);
  16678. ASSERT_TRUE(static_cast<bool>(body.second));
  16679. // Rewritten shorter after its length was measured - and, on a server, after
  16680. // that length has already gone out as Content-Length.
  16681. {
  16682. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16683. const std::string content(10, 'A');
  16684. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16685. }
  16686. std::string written;
  16687. DataSink sink;
  16688. sink.write = [&](const char *d, size_t l) {
  16689. written.append(d, l);
  16690. return true;
  16691. };
  16692. // The provider has to report failure. write_content_with_progress() advances
  16693. // its offset only by what was written, so a provider that returns true
  16694. // without completing the length it promised is called again straight away,
  16695. // and again.
  16696. EXPECT_FALSE(body.second(0, body.first, sink));
  16697. EXPECT_EQ(std::string(10, 'A'), written);
  16698. }
  16699. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16700. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16701. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16702. {
  16703. std::ofstream ofs(path, std::ios::binary);
  16704. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16705. }
  16706. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16707. auto body = make_file_body(path);
  16708. ASSERT_EQ(content.size(), body.first);
  16709. ASSERT_TRUE(static_cast<bool>(body.second));
  16710. std::string written;
  16711. DataSink sink;
  16712. sink.write = [&](const char *d, size_t l) {
  16713. written.append(d, l);
  16714. return true;
  16715. };
  16716. EXPECT_TRUE(body.second(0, body.first, sink));
  16717. EXPECT_EQ(content, written);
  16718. }
  16719. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16720. static constexpr unsigned int number_of_tasks{1000000};
  16721. std::atomic_uint count{0};
  16722. std::unique_ptr<TaskQueue> task_queue{
  16723. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16724. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16725. auto queued = task_queue->enqueue(
  16726. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16727. EXPECT_TRUE(queued);
  16728. }
  16729. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16730. task_queue->shutdown();
  16731. #else
  16732. EXPECT_NO_THROW(task_queue->shutdown());
  16733. #endif
  16734. EXPECT_EQ(number_of_tasks, count.load());
  16735. }
  16736. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16737. static constexpr unsigned int number_of_tasks{1000000};
  16738. static constexpr unsigned int qlimit{2};
  16739. unsigned int queued_count{0};
  16740. std::atomic_uint count{0};
  16741. std::unique_ptr<TaskQueue> task_queue{
  16742. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16743. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16744. if (task_queue->enqueue(
  16745. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16746. queued_count++;
  16747. }
  16748. }
  16749. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16750. task_queue->shutdown();
  16751. #else
  16752. EXPECT_NO_THROW(task_queue->shutdown());
  16753. #endif
  16754. EXPECT_EQ(queued_count, count.load());
  16755. EXPECT_TRUE(queued_count <= number_of_tasks);
  16756. EXPECT_TRUE(queued_count >= qlimit);
  16757. }
  16758. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16759. // Use a short idle timeout so a dynamic thread spawns, times out and
  16760. // exits during the test, and the pool keeps working afterwards.
  16761. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16762. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16763. /*idle_timeout_sec=*/1}};
  16764. std::atomic_uint count{0};
  16765. std::condition_variable cv;
  16766. std::mutex mtx;
  16767. bool release = false;
  16768. // Block the base thread so the second task spawns a dynamic thread.
  16769. EXPECT_TRUE(task_queue->enqueue([&] {
  16770. std::unique_lock<std::mutex> lock(mtx);
  16771. while (!release) {
  16772. cv.wait(lock);
  16773. }
  16774. count++;
  16775. }));
  16776. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16777. // Let the dynamic thread finish its task and exceed the idle timeout.
  16778. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16779. {
  16780. std::unique_lock<std::mutex> lock(mtx);
  16781. release = true;
  16782. }
  16783. cv.notify_all();
  16784. // The pool must still accept and run tasks after the dynamic thread exited.
  16785. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16786. task_queue->shutdown();
  16787. EXPECT_EQ(3u, count.load());
  16788. }
  16789. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16790. static constexpr size_t number_of_tasks{32};
  16791. std::unique_ptr<TaskQueue> task_queue{
  16792. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16793. // Let the base threads go idle so the burst below finds them waiting.
  16794. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16795. std::mutex mtx;
  16796. std::condition_variable cv;
  16797. size_t running = 0;
  16798. bool release = false;
  16799. for (size_t i = 0; i < number_of_tasks; i++) {
  16800. EXPECT_TRUE(task_queue->enqueue([&] {
  16801. std::unique_lock<std::mutex> lock(mtx);
  16802. running++;
  16803. cv.notify_all();
  16804. cv.wait(lock, [&] { return release; });
  16805. }));
  16806. }
  16807. {
  16808. std::unique_lock<std::mutex> lock(mtx);
  16809. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16810. [&] { return running == number_of_tasks; }));
  16811. release = true;
  16812. }
  16813. cv.notify_all();
  16814. task_queue->shutdown();
  16815. }
  16816. TEST(TaskQueueTest, MaxQueuedRequests) {
  16817. static constexpr unsigned int qlimit{3};
  16818. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16819. std::condition_variable sem_cv;
  16820. std::mutex sem_mtx;
  16821. int credits = 0;
  16822. bool queued;
  16823. /* Fill up the queue with tasks that will block until we give them credits to
  16824. * complete. */
  16825. for (unsigned int n = 0; n <= qlimit;) {
  16826. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16827. std::unique_lock<std::mutex> lock(sem_mtx);
  16828. while (credits <= 0) {
  16829. sem_cv.wait(lock);
  16830. }
  16831. /* Consume the credit and signal the test code if they are all gone. */
  16832. if (--credits == 0) { sem_cv.notify_one(); }
  16833. });
  16834. if (n < qlimit) {
  16835. /* The first qlimit enqueues must succeed. */
  16836. EXPECT_TRUE(queued);
  16837. } else {
  16838. /* The last one will succeed only when the worker thread
  16839. * starts and dequeues the first blocking task. Although
  16840. * not necessary for the correctness of this test, we sleep for
  16841. * a short while to avoid busy waiting. */
  16842. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16843. }
  16844. if (queued) { n++; }
  16845. }
  16846. /* Further enqueues must fail since the queue is full. */
  16847. for (auto i = 0; i < 4; i++) {
  16848. queued = task_queue->enqueue([] {});
  16849. EXPECT_FALSE(queued);
  16850. }
  16851. /* Give the credits to allow the previous tasks to complete. */
  16852. {
  16853. std::unique_lock<std::mutex> lock(sem_mtx);
  16854. credits += qlimit + 1;
  16855. }
  16856. sem_cv.notify_all();
  16857. /* Wait for all the credits to be consumed. */
  16858. {
  16859. std::unique_lock<std::mutex> lock(sem_mtx);
  16860. while (credits > 0) {
  16861. sem_cv.wait(lock);
  16862. }
  16863. }
  16864. /* Check that we are able again to enqueue at least qlimit tasks. */
  16865. for (unsigned int i = 0; i < qlimit; i++) {
  16866. queued = task_queue->enqueue([] {});
  16867. EXPECT_TRUE(queued);
  16868. }
  16869. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16870. task_queue->shutdown();
  16871. #else
  16872. EXPECT_NO_THROW(task_queue->shutdown());
  16873. #endif
  16874. }
  16875. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16876. Server svr;
  16877. std::string method;
  16878. std::string body;
  16879. auto has_content_length = false;
  16880. auto has_transfer_encoding = false;
  16881. std::atomic<int> bad_requests{0};
  16882. // Leftover body bytes get parsed as a malformed request and answered with
  16883. // 400
  16884. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16885. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16886. });
  16887. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16888. res.set_redirect("/down", StatusCode::SeeOther_303);
  16889. });
  16890. svr.Get("/down", [&](const Request &req, Response &res) {
  16891. method = req.method;
  16892. body = req.body;
  16893. has_content_length = req.has_header("Content-Length");
  16894. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16895. res.set_content("ok", "text/plain");
  16896. });
  16897. auto port = svr.bind_to_any_port(HOST);
  16898. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16899. auto se = detail::scope_exit([&] {
  16900. svr.stop();
  16901. thread.join();
  16902. ASSERT_FALSE(svr.is_running());
  16903. });
  16904. svr.wait_until_ready();
  16905. const std::string payload = "SECRET-BODY";
  16906. auto check = [&](Client &cli, const Result &res) {
  16907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16908. EXPECT_EQ(StatusCode::OK_200, res->status);
  16909. EXPECT_EQ("ok", res->body);
  16910. EXPECT_EQ("GET", method);
  16911. EXPECT_TRUE(body.empty());
  16912. EXPECT_FALSE(has_content_length);
  16913. EXPECT_FALSE(has_transfer_encoding);
  16914. // Nothing of the original body may be left on the connection
  16915. auto res2 = cli.Get("/down");
  16916. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16917. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16918. EXPECT_EQ("ok", res2->body);
  16919. EXPECT_EQ(0, bad_requests);
  16920. };
  16921. // With content length
  16922. {
  16923. Client cli(HOST, port);
  16924. cli.set_keep_alive(true);
  16925. cli.set_follow_location(true);
  16926. auto res = cli.Post(
  16927. "/up", payload.size(),
  16928. [&](size_t offset, size_t length, DataSink &sink) {
  16929. return sink.write(payload.data() + offset, length);
  16930. },
  16931. "text/plain");
  16932. check(cli, res);
  16933. }
  16934. // Without content length (chunked)
  16935. {
  16936. Client cli(HOST, port);
  16937. cli.set_keep_alive(true);
  16938. cli.set_follow_location(true);
  16939. auto res = cli.Post(
  16940. "/up",
  16941. [&](size_t /*offset*/, DataSink &sink) {
  16942. sink.write(payload.data(), payload.size());
  16943. sink.done();
  16944. return true;
  16945. },
  16946. "text/plain");
  16947. check(cli, res);
  16948. }
  16949. }
  16950. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16951. Server svr;
  16952. std::string target;
  16953. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16954. // Echo the still-encoded name back in the Location
  16955. const std::string prefix = "/start/";
  16956. res.status = StatusCode::Found_302;
  16957. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16958. });
  16959. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16960. target = req.target;
  16961. res.set_content("ok", "text/plain");
  16962. });
  16963. auto port = svr.bind_to_any_port(HOST);
  16964. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16965. auto se = detail::scope_exit([&] {
  16966. svr.stop();
  16967. thread.join();
  16968. ASSERT_FALSE(svr.is_running());
  16969. });
  16970. svr.wait_until_ready();
  16971. // Decoding the Location path would turn the first four into a path
  16972. // separator, a query delimiter, a fragment delimiter and a different
  16973. // percent-encoded octet. The rest must keep reaching the server as they are.
  16974. const std::vector<std::string> names = {
  16975. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16976. };
  16977. for (auto path_encode : {true, false}) {
  16978. Client cli(HOST, port);
  16979. cli.set_follow_location(true);
  16980. cli.set_path_encode(path_encode);
  16981. for (const auto &name : names) {
  16982. target.clear();
  16983. auto res = cli.Get("/start/" + name);
  16984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16985. EXPECT_EQ(StatusCode::OK_200, res->status);
  16986. EXPECT_EQ("/dest/" + name, target);
  16987. }
  16988. }
  16989. }
  16990. TEST(RedirectTest, NotModifiedIsReturned) {
  16991. Server svr;
  16992. svr.Get("/cached", [](const Request &, Response &res) {
  16993. res.status = StatusCode::NotModified_304;
  16994. });
  16995. auto port = svr.bind_to_any_port(HOST);
  16996. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16997. auto se = detail::scope_exit([&] {
  16998. svr.stop();
  16999. thread.join();
  17000. ASSERT_FALSE(svr.is_running());
  17001. });
  17002. svr.wait_until_ready();
  17003. Client cli(HOST, port);
  17004. cli.set_follow_location(true);
  17005. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17007. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17008. }
  17009. TEST(RedirectTest, NoLocationIsReturned) {
  17010. Server svr;
  17011. svr.Get("/no-location", [](const Request &, Response &res) {
  17012. res.status = StatusCode::Found_302;
  17013. res.set_content("no location", "text/plain");
  17014. });
  17015. auto port = svr.bind_to_any_port(HOST);
  17016. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17017. auto se = detail::scope_exit([&] {
  17018. svr.stop();
  17019. thread.join();
  17020. ASSERT_FALSE(svr.is_running());
  17021. });
  17022. svr.wait_until_ready();
  17023. Client cli(HOST, port);
  17024. cli.set_follow_location(true);
  17025. auto res = cli.Get("/no-location");
  17026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17027. EXPECT_EQ(StatusCode::Found_302, res->status);
  17028. EXPECT_EQ("no location", res->body);
  17029. // The callbacks see the body of the response that is returned
  17030. auto handler_called = false;
  17031. auto progress_called = false;
  17032. std::string body;
  17033. auto res2 = cli.Get(
  17034. "/no-location",
  17035. [&](const Response &) {
  17036. handler_called = true;
  17037. return true;
  17038. },
  17039. [&](const char *data, size_t data_length) {
  17040. body.append(data, data_length);
  17041. return true;
  17042. },
  17043. [&](size_t, size_t) {
  17044. progress_called = true;
  17045. return true;
  17046. });
  17047. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17048. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17049. EXPECT_TRUE(handler_called);
  17050. EXPECT_TRUE(progress_called);
  17051. EXPECT_EQ("no location", body);
  17052. }
  17053. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17054. Server svr;
  17055. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17056. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17057. });
  17058. svr.Get("/hello", [](const Request &req, Response &res) {
  17059. res.set_content(req.get_param_value("key"), "text/plain");
  17060. });
  17061. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17062. auto se = detail::scope_exit([&] {
  17063. svr.stop();
  17064. thread.join();
  17065. ASSERT_FALSE(svr.is_running());
  17066. });
  17067. svr.wait_until_ready();
  17068. {
  17069. Client cli(HOST, PORT);
  17070. cli.set_follow_location(true);
  17071. auto res = cli.Get("/");
  17072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17073. EXPECT_EQ(StatusCode::OK_200, res->status);
  17074. EXPECT_EQ("val&key2=val2", res->body);
  17075. }
  17076. }
  17077. #endif
  17078. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17079. Server svr;
  17080. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17081. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17082. });
  17083. svr.Get("/hello", [](const Request &req, Response &res) {
  17084. res.set_content(req.get_param_value("key"), "text/plain");
  17085. });
  17086. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17087. auto se = detail::scope_exit([&] {
  17088. svr.stop();
  17089. thread.join();
  17090. ASSERT_FALSE(svr.is_running());
  17091. });
  17092. svr.wait_until_ready();
  17093. {
  17094. Client cli(HOST, PORT);
  17095. cli.set_follow_location(true);
  17096. auto res = cli.Get("/");
  17097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17098. EXPECT_EQ(StatusCode::OK_200, res->status);
  17099. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17100. }
  17101. }
  17102. TEST(RedirectTest, RedirectWithPlusInPath) {
  17103. Server svr;
  17104. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17105. res.set_redirect("/a+b");
  17106. });
  17107. // Route pattern uses regex; escape + as \\+
  17108. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17109. res.set_content(req.path, "text/plain");
  17110. });
  17111. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17112. auto se = detail::scope_exit([&] {
  17113. svr.stop();
  17114. thread.join();
  17115. ASSERT_FALSE(svr.is_running());
  17116. });
  17117. svr.wait_until_ready();
  17118. {
  17119. Client cli(HOST, PORT);
  17120. cli.set_follow_location(true);
  17121. auto res = cli.Get("/");
  17122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17123. EXPECT_EQ(StatusCode::OK_200, res->status);
  17124. EXPECT_EQ("/a+b", res->body);
  17125. }
  17126. }
  17127. TEST(RedirectTest, ResolveRelativeLocation) {
  17128. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17129. const std::vector<std::pair<std::string, std::string>> cases = {
  17130. {"g", "/b/c/g"},
  17131. {"./g", "/b/c/g"},
  17132. {"g/", "/b/c/g/"},
  17133. {"?y", "/b/c/d;p?y"},
  17134. {"g?y", "/b/c/g?y"},
  17135. {"#s", "/b/c/d;p?q#s"},
  17136. {"g#s", "/b/c/g#s"},
  17137. {"g?y#s", "/b/c/g?y#s"},
  17138. {";x", "/b/c/;x"},
  17139. {"g;x", "/b/c/g;x"},
  17140. {".", "/b/c/"},
  17141. {"./", "/b/c/"},
  17142. {"..", "/b/"},
  17143. {"../", "/b/"},
  17144. {"../g", "/b/g"},
  17145. {"../..", "/"},
  17146. {"../../", "/"},
  17147. {"../../g", "/g"},
  17148. {"../../../g", "/g"},
  17149. {"g.", "/b/c/g."},
  17150. {".g", "/b/c/.g"},
  17151. {"g..", "/b/c/g.."},
  17152. {"..g", "/b/c/..g"},
  17153. {"./../g", "/b/g"},
  17154. {"./g/.", "/b/c/g/"},
  17155. {"g/./h", "/b/c/g/h"},
  17156. {"g/../h", "/b/c/h"},
  17157. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17158. {"g;x=1/../y", "/b/c/y"},
  17159. {"g?y/./x", "/b/c/g?y/./x"},
  17160. {"g#s/../x", "/b/c/g#s/../x"},
  17161. // Not relative-path references, so left for parse_url.
  17162. {"/g", "/g"},
  17163. {"//g", "//g"},
  17164. {"http://g/x", "http://g/x"},
  17165. {"g:h", "g:h"},
  17166. };
  17167. for (const auto &c : cases) {
  17168. EXPECT_EQ(c.second,
  17169. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17170. << c.first;
  17171. }
  17172. }
  17173. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17174. Server svr;
  17175. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17176. res.set_redirect(req.get_param_value("to"));
  17177. });
  17178. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17179. res.set_content(req.target, "text/plain");
  17180. });
  17181. svr.Get("/other", [](const Request &req, Response &res) {
  17182. res.set_content(req.target, "text/plain");
  17183. });
  17184. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17185. auto se = detail::scope_exit([&] {
  17186. svr.stop();
  17187. thread.join();
  17188. ASSERT_FALSE(svr.is_running());
  17189. });
  17190. svr.wait_until_ready();
  17191. const std::vector<std::pair<std::string, std::string>> cases = {
  17192. {"next", "/dir/next"},
  17193. {"./next?x=1", "/dir/next?x=1"},
  17194. {"../other", "/other"},
  17195. };
  17196. for (const auto &c : cases) {
  17197. Client cli(HOST, PORT);
  17198. cli.set_follow_location(true);
  17199. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17200. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17201. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17202. EXPECT_EQ(c.second, res->body) << c.first;
  17203. }
  17204. }
  17205. #ifdef CPPHTTPLIB_SSL_ENABLED
  17206. TEST(RedirectTest, Issue2185_Online) {
  17207. SSLClient client("github.com");
  17208. client.set_follow_location(true);
  17209. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17210. "Coollab-Windows.zip");
  17211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17212. EXPECT_EQ(StatusCode::OK_200, res->status);
  17213. EXPECT_EQ(9920427U, res->body.size());
  17214. }
  17215. #endif
  17216. TEST(VulnerabilityTest, CRLFInjection) {
  17217. Server svr;
  17218. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17219. res.set_content("Hello 1", "text/plain");
  17220. });
  17221. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17222. res.set_content("Hello 2", "text/plain");
  17223. });
  17224. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17225. res.set_content("Hello 3", "text/plain");
  17226. });
  17227. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17228. res.set_content("Hello 4", "text/plain");
  17229. });
  17230. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17231. for (const auto &x : req.headers) {
  17232. auto key = x.first;
  17233. EXPECT_STRNE("evil", key.c_str());
  17234. }
  17235. });
  17236. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17237. auto se = detail::scope_exit([&] {
  17238. svr.stop();
  17239. thread.join();
  17240. ASSERT_FALSE(svr.is_running());
  17241. });
  17242. svr.wait_until_ready();
  17243. {
  17244. Client cli(HOST, PORT);
  17245. cli.Post("/test1", "A=B",
  17246. "application/x-www-form-urlencoded\r\nevil: hello1");
  17247. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17248. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17249. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17250. }
  17251. }
  17252. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17253. auto server_thread = std::thread([] {
  17254. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17255. default_socket_options(srv);
  17256. sockaddr_in addr{};
  17257. addr.sin_family = AF_INET;
  17258. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17259. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17260. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17261. ::listen(srv, 1);
  17262. sockaddr_in cli_addr{};
  17263. socklen_t cli_len = sizeof(cli_addr);
  17264. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17265. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17266. std::string buf_all;
  17267. char buf[2048];
  17268. ssize_t n;
  17269. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17270. buf_all.append(buf, static_cast<size_t>(n));
  17271. size_t pos;
  17272. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17273. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17274. auto e = request_block.find("\r\n");
  17275. if (e != std::string::npos) {
  17276. auto request_line = request_block.substr(0, e);
  17277. std::string msg =
  17278. "CRLF injection detected in request line: '" + request_line + "'";
  17279. EXPECT_FALSE(true) << msg;
  17280. }
  17281. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17282. ::send(cli,
  17283. #ifdef _WIN32
  17284. static_cast<const char *>(resp.c_str()),
  17285. static_cast<int>(resp.size()),
  17286. #else
  17287. resp.c_str(), resp.size(),
  17288. #endif
  17289. 0);
  17290. buf_all.erase(0, pos + 4);
  17291. }
  17292. }
  17293. detail::close_socket(cli);
  17294. detail::close_socket(srv);
  17295. });
  17296. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17297. auto cli = Client("127.0.0.1", PORT + 1);
  17298. auto headers = Headers{
  17299. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17300. {"Connection", "keep-alive"}};
  17301. auto res = cli.Get("/hi", headers);
  17302. EXPECT_FALSE(res);
  17303. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17304. server_thread.join();
  17305. }
  17306. // A request rejected before any byte reaches the socket must fail right away
  17307. // instead of waiting for a response the server will never send.
  17308. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17309. // The kernel completes the TCP handshake from the listen backlog, so the
  17310. // client connects, but nothing ever reads, responds or closes.
  17311. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17312. default_socket_options(srv);
  17313. sockaddr_in addr{};
  17314. addr.sin_family = AF_INET;
  17315. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17316. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17317. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17318. ASSERT_EQ(0, ::listen(srv, 8));
  17319. auto cli = Client("127.0.0.1", PORT + 1);
  17320. cli.set_read_timeout(10, 0);
  17321. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17322. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17323. std::chrono::steady_clock::now() - start)
  17324. .count();
  17325. };
  17326. {
  17327. Request req;
  17328. req.method = "GE T";
  17329. req.path = "/";
  17330. auto start = std::chrono::steady_clock::now();
  17331. auto res = cli.send(req);
  17332. EXPECT_FALSE(res);
  17333. EXPECT_EQ(Error::Write, res.error());
  17334. EXPECT_LT(elapsed_ms(start), 1000);
  17335. }
  17336. {
  17337. auto start = std::chrono::steady_clock::now();
  17338. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17339. EXPECT_FALSE(res);
  17340. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17341. EXPECT_LT(elapsed_ms(start), 1000);
  17342. }
  17343. EXPECT_FALSE(cli.is_socket_open());
  17344. detail::close_socket(srv);
  17345. }
  17346. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17347. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17348. default_socket_options(srv);
  17349. sockaddr_in addr{};
  17350. addr.sin_family = AF_INET;
  17351. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17352. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17353. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17354. ASSERT_EQ(0, ::listen(srv, 1));
  17355. std::string received;
  17356. auto server_thread = std::thread([&] {
  17357. auto sock = ::accept(srv, nullptr, nullptr);
  17358. if (sock == INVALID_SOCKET) { return; }
  17359. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17360. char buf[2048];
  17361. ssize_t n;
  17362. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17363. received.append(buf, static_cast<size_t>(n));
  17364. }
  17365. detail::close_socket(sock);
  17366. });
  17367. {
  17368. auto cli = Client("127.0.0.1", PORT + 1);
  17369. // "Z" sorts after the default headers, so writing straight to the socket
  17370. // would have sent the request line and those headers before the rejection.
  17371. auto handle =
  17372. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17373. EXPECT_FALSE(handle.is_valid());
  17374. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17375. }
  17376. server_thread.join();
  17377. detail::close_socket(srv);
  17378. EXPECT_TRUE(received.empty()) << received;
  17379. }
  17380. TEST(PathParamsTest, StaticMatch) {
  17381. const auto pattern = "/users/all";
  17382. detail::PathParamsMatcher matcher(pattern);
  17383. Request request;
  17384. request.path = "/users/all";
  17385. ASSERT_TRUE(matcher.match(request));
  17386. std::unordered_map<std::string, std::string> expected_params = {};
  17387. EXPECT_EQ(request.path_params, expected_params);
  17388. }
  17389. TEST(PathParamsTest, StaticMismatch) {
  17390. const auto pattern = "/users/all";
  17391. detail::PathParamsMatcher matcher(pattern);
  17392. Request request;
  17393. request.path = "/users/1";
  17394. ASSERT_FALSE(matcher.match(request));
  17395. }
  17396. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17397. const auto pattern = "/users/:id/subscriptions";
  17398. detail::PathParamsMatcher matcher(pattern);
  17399. Request request;
  17400. request.path = "/users/42/subscriptions";
  17401. ASSERT_TRUE(matcher.match(request));
  17402. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17403. EXPECT_EQ(request.path_params, expected_params);
  17404. }
  17405. TEST(PathParamsTest, SingleParamInTheEnd) {
  17406. const auto pattern = "/users/:id";
  17407. detail::PathParamsMatcher matcher(pattern);
  17408. Request request;
  17409. request.path = "/users/24";
  17410. ASSERT_TRUE(matcher.match(request));
  17411. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17412. EXPECT_EQ(request.path_params, expected_params);
  17413. }
  17414. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17415. const auto pattern = "/users/:id/";
  17416. detail::PathParamsMatcher matcher(pattern);
  17417. Request request;
  17418. request.path = "/users/42/";
  17419. ASSERT_TRUE(matcher.match(request));
  17420. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17421. EXPECT_EQ(request.path_params, expected_params);
  17422. }
  17423. TEST(PathParamsTest, EmptyParam) {
  17424. const auto pattern = "/users/:id/";
  17425. detail::PathParamsMatcher matcher(pattern);
  17426. Request request;
  17427. request.path = "/users//";
  17428. ASSERT_TRUE(matcher.match(request));
  17429. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17430. EXPECT_EQ(request.path_params, expected_params);
  17431. }
  17432. TEST(PathParamsTest, FragmentMismatch) {
  17433. const auto pattern = "/users/:id/";
  17434. detail::PathParamsMatcher matcher(pattern);
  17435. Request request;
  17436. request.path = "/admins/24/";
  17437. ASSERT_FALSE(matcher.match(request));
  17438. }
  17439. TEST(PathParamsTest, ExtraFragments) {
  17440. const auto pattern = "/users/:id";
  17441. detail::PathParamsMatcher matcher(pattern);
  17442. Request request;
  17443. request.path = "/users/42/subscriptions";
  17444. ASSERT_FALSE(matcher.match(request));
  17445. }
  17446. TEST(PathParamsTest, MissingTrailingParam) {
  17447. const auto pattern = "/users/:id";
  17448. detail::PathParamsMatcher matcher(pattern);
  17449. Request request;
  17450. request.path = "/users";
  17451. ASSERT_FALSE(matcher.match(request));
  17452. }
  17453. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17454. const auto pattern = "/users/:id/subscriptions";
  17455. detail::PathParamsMatcher matcher(pattern);
  17456. Request request;
  17457. request.path = "/users/subscriptions";
  17458. ASSERT_FALSE(matcher.match(request));
  17459. }
  17460. TEST(PathParamsTest, MultipleParams) {
  17461. const auto pattern = "/users/:userid/subscriptions/:subid";
  17462. detail::PathParamsMatcher matcher(pattern);
  17463. Request request;
  17464. request.path = "/users/42/subscriptions/2";
  17465. ASSERT_TRUE(matcher.match(request));
  17466. std::unordered_map<std::string, std::string> expected_params = {
  17467. {"userid", "42"}, {"subid", "2"}};
  17468. EXPECT_EQ(request.path_params, expected_params);
  17469. }
  17470. TEST(PathParamsTest, SequenceOfParams) {
  17471. const auto pattern = "/values/:x/:y/:z";
  17472. detail::PathParamsMatcher matcher(pattern);
  17473. Request request;
  17474. request.path = "/values/1/2/3";
  17475. ASSERT_TRUE(matcher.match(request));
  17476. std::unordered_map<std::string, std::string> expected_params = {
  17477. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17478. EXPECT_EQ(request.path_params, expected_params);
  17479. }
  17480. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17481. const auto pattern = "/prefix:suffix";
  17482. detail::PathParamsMatcher matcher(pattern);
  17483. Request request;
  17484. request.path = "/prefix:suffix";
  17485. ASSERT_TRUE(matcher.match(request));
  17486. const std::unordered_map<std::string, std::string> expected_params = {};
  17487. EXPECT_EQ(request.path_params, expected_params);
  17488. }
  17489. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17490. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17491. // calling thread's stack on a long enough path for a quantified pattern;
  17492. // RegexMatcher must refuse to run regex matching on paths beyond
  17493. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17494. detail::RegexMatcher matcher("/files/(.*)");
  17495. Request within_limit;
  17496. within_limit.path = "/files/" + std::string(10, 'A');
  17497. EXPECT_TRUE(matcher.match(within_limit));
  17498. Request over_limit;
  17499. over_limit.path =
  17500. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17501. EXPECT_FALSE(matcher.match(over_limit));
  17502. }
  17503. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17504. Server svr;
  17505. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17506. res.set_content("ok", "text/plain");
  17507. });
  17508. auto port = svr.bind_to_any_port(HOST);
  17509. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17510. auto se = detail::scope_exit([&] {
  17511. svr.stop();
  17512. thread.join();
  17513. ASSERT_FALSE(svr.is_running());
  17514. });
  17515. svr.wait_until_ready();
  17516. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17517. // request URI limit; this used to be able to crash the process.
  17518. std::string path =
  17519. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17520. std::string req = "GET " + path +
  17521. " HTTP/1.1\r\n"
  17522. "Host: " +
  17523. std::string(HOST) + ":" + std::to_string(port) +
  17524. "\r\n"
  17525. "Connection: close\r\n"
  17526. "\r\n";
  17527. std::string response;
  17528. ASSERT_TRUE(send_request(5, req, &response, port));
  17529. EXPECT_NE(std::string::npos, response.find("404"));
  17530. }
  17531. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17532. Server svr;
  17533. auto handler = [](const Request & /*req*/, Response &res) {
  17534. res.set_content("hit", "text/plain");
  17535. };
  17536. // No regex metacharacter, so this one is compared literally
  17537. svr.Get("/literal/route", handler);
  17538. // '.' is a regex metacharacter, so this one must keep regex semantics
  17539. svr.Get("/a.c", handler);
  17540. auto port = svr.bind_to_any_port(HOST);
  17541. std::thread t([&]() { svr.listen_after_bind(); });
  17542. auto se = detail::scope_exit([&] {
  17543. svr.stop();
  17544. t.join();
  17545. ASSERT_FALSE(svr.is_running());
  17546. });
  17547. svr.wait_until_ready();
  17548. Client cli(HOST, port);
  17549. struct {
  17550. const char *path;
  17551. int status;
  17552. } cases[] = {
  17553. {"/literal/route", StatusCode::OK_200},
  17554. {"/literal/routes", StatusCode::NotFound_404},
  17555. {"/literal/rout", StatusCode::NotFound_404},
  17556. {"/abc", StatusCode::OK_200},
  17557. {"/a.c", StatusCode::OK_200},
  17558. };
  17559. for (const auto &x : cases) {
  17560. auto res = cli.Get(x.path);
  17561. ASSERT_TRUE(res) << x.path;
  17562. EXPECT_EQ(x.status, res->status) << x.path;
  17563. }
  17564. }
  17565. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17566. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17567. // from exhausting the stack, so it must only constrain routes that actually
  17568. // run a regular expression. A literal route is matched by comparison and
  17569. // stays usable at any length.
  17570. Server svr;
  17571. const std::string pattern =
  17572. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17573. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17574. res.set_content("hit", "text/plain");
  17575. });
  17576. auto port = svr.bind_to_any_port(HOST);
  17577. std::thread t([&]() { svr.listen_after_bind(); });
  17578. auto se = detail::scope_exit([&] {
  17579. svr.stop();
  17580. t.join();
  17581. ASSERT_FALSE(svr.is_running());
  17582. });
  17583. svr.wait_until_ready();
  17584. Client cli(HOST, port);
  17585. auto res = cli.Get(pattern);
  17586. ASSERT_TRUE(res);
  17587. EXPECT_EQ(StatusCode::OK_200, res->status);
  17588. }
  17589. TEST(ParseUrlTest, VariousPatterns) {
  17590. {
  17591. detail::UrlComponents uc;
  17592. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17593. EXPECT_EQ("http", uc.scheme);
  17594. EXPECT_EQ("example.com", uc.host);
  17595. EXPECT_EQ("8080", uc.port);
  17596. EXPECT_EQ("/path", uc.path);
  17597. EXPECT_EQ("?q=1", uc.query);
  17598. }
  17599. {
  17600. detail::UrlComponents uc;
  17601. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17602. EXPECT_EQ("https", uc.scheme);
  17603. EXPECT_EQ("example.com", uc.host);
  17604. EXPECT_TRUE(uc.port.empty());
  17605. EXPECT_EQ("/path", uc.path);
  17606. }
  17607. {
  17608. detail::UrlComponents uc;
  17609. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17610. EXPECT_EQ("::1", uc.host);
  17611. EXPECT_EQ("8080", uc.port);
  17612. EXPECT_EQ("/path", uc.path);
  17613. }
  17614. {
  17615. detail::UrlComponents uc;
  17616. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17617. }
  17618. {
  17619. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17620. // the path while the connection still targets the bracketed host.
  17621. detail::UrlComponents uc;
  17622. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17623. }
  17624. {
  17625. detail::UrlComponents uc;
  17626. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17627. }
  17628. {
  17629. detail::UrlComponents uc;
  17630. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17631. EXPECT_EQ("::1", uc.host);
  17632. EXPECT_TRUE(uc.port.empty());
  17633. EXPECT_EQ("/path", uc.path);
  17634. }
  17635. {
  17636. detail::UrlComponents uc;
  17637. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17638. EXPECT_TRUE(uc.scheme.empty());
  17639. EXPECT_EQ("example.com", uc.host);
  17640. EXPECT_EQ("/path", uc.path);
  17641. EXPECT_EQ("?q=1", uc.query);
  17642. }
  17643. {
  17644. detail::UrlComponents uc;
  17645. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17646. EXPECT_TRUE(uc.host.empty());
  17647. EXPECT_EQ("/path", uc.path);
  17648. EXPECT_EQ("?q=1", uc.query);
  17649. }
  17650. {
  17651. detail::UrlComponents uc;
  17652. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17653. EXPECT_EQ("example.com", uc.host);
  17654. EXPECT_EQ("8080", uc.port);
  17655. }
  17656. {
  17657. // Unix socket path — must not be parsed as host
  17658. detail::UrlComponents uc;
  17659. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17660. EXPECT_TRUE(uc.host.empty());
  17661. }
  17662. {
  17663. detail::UrlComponents uc;
  17664. ASSERT_TRUE(detail::parse_url("", uc));
  17665. EXPECT_TRUE(uc.host.empty());
  17666. EXPECT_TRUE(uc.path.empty());
  17667. }
  17668. {
  17669. detail::UrlComponents uc;
  17670. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17671. }
  17672. {
  17673. detail::UrlComponents uc;
  17674. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17675. }
  17676. {
  17677. // Accepted by parse_url; callers restrict to http/https
  17678. detail::UrlComponents uc;
  17679. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17680. EXPECT_EQ("ftp", uc.scheme);
  17681. }
  17682. {
  17683. detail::UrlComponents uc;
  17684. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17685. }
  17686. {
  17687. detail::UrlComponents uc;
  17688. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17689. }
  17690. }
  17691. TEST(ParseUrlTest, FragmentHandling) {
  17692. {
  17693. detail::UrlComponents uc;
  17694. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17695. EXPECT_EQ("/path", uc.path);
  17696. EXPECT_TRUE(uc.query.empty());
  17697. }
  17698. {
  17699. detail::UrlComponents uc;
  17700. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17701. EXPECT_TRUE(uc.path.empty());
  17702. EXPECT_TRUE(uc.query.empty());
  17703. }
  17704. }
  17705. TEST(ParseUrlTest, UserinfoHandling) {
  17706. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17707. // parsers would see evil.com as the host.
  17708. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17709. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17710. for (auto url : urls) {
  17711. detail::UrlComponents uc;
  17712. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17713. }
  17714. }
  17715. TEST(ParseUrlTest, IPv6EdgeCases) {
  17716. {
  17717. detail::UrlComponents uc;
  17718. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17719. EXPECT_TRUE(uc.scheme.empty());
  17720. EXPECT_EQ("::1", uc.host);
  17721. EXPECT_EQ("8080", uc.port);
  17722. }
  17723. {
  17724. // Zone ID '%25' is not in [a-fA-F0-9:]
  17725. detail::UrlComponents uc;
  17726. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17727. }
  17728. }
  17729. TEST(ParseUrlTest, SchemeEdgeCases) {
  17730. {
  17731. detail::UrlComponents uc;
  17732. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17733. }
  17734. {
  17735. detail::UrlComponents uc;
  17736. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17737. }
  17738. {
  17739. detail::UrlComponents uc;
  17740. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17741. }
  17742. }
  17743. TEST(ParseUrlTest, PortEdgeCases) {
  17744. {
  17745. detail::UrlComponents uc;
  17746. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17747. EXPECT_TRUE(uc.port.empty());
  17748. EXPECT_EQ("/path", uc.path);
  17749. }
  17750. {
  17751. // parse_url accepts any port string; validation is done by parse_port
  17752. detail::UrlComponents uc;
  17753. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17754. EXPECT_EQ("abc", uc.port);
  17755. }
  17756. }
  17757. TEST(ParseUrlTest, WebSocketPatterns) {
  17758. {
  17759. detail::UrlComponents uc;
  17760. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17761. EXPECT_EQ("ws", uc.scheme);
  17762. EXPECT_EQ("echo.example.com", uc.host);
  17763. EXPECT_EQ("8080", uc.port);
  17764. EXPECT_EQ("/ws", uc.path);
  17765. }
  17766. {
  17767. detail::UrlComponents uc;
  17768. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17769. EXPECT_EQ("wss", uc.scheme);
  17770. EXPECT_EQ("echo.example.com", uc.host);
  17771. EXPECT_TRUE(uc.port.empty());
  17772. EXPECT_EQ("/ws", uc.path);
  17773. }
  17774. }
  17775. TEST(ParseUrlTest, QueryOnly) {
  17776. detail::UrlComponents uc;
  17777. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17778. EXPECT_TRUE(uc.host.empty());
  17779. EXPECT_TRUE(uc.path.empty());
  17780. EXPECT_EQ("?q=1&r=2", uc.query);
  17781. }
  17782. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17783. detail::UrlComponents uc;
  17784. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17785. EXPECT_TRUE(uc.scheme.empty());
  17786. EXPECT_EQ("example.com", uc.host);
  17787. EXPECT_EQ("443", uc.port);
  17788. EXPECT_EQ("/path", uc.path);
  17789. }
  17790. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17791. // If ipv6 regex working, regex match codepath is taken.
  17792. // else port will default to 80 in Client impl
  17793. int clientImplMagicPort = 80;
  17794. int port = 4321;
  17795. // above ports must be different to avoid false negative
  17796. EXPECT_NE(clientImplMagicPort, port);
  17797. std::string ipV6TestURL = "http://[ff06::c3]";
  17798. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17799. CLIENT_PRIVATE_KEY_FILE);
  17800. EXPECT_EQ(cli.port(), port);
  17801. }
  17802. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17803. auto file_path = "./www/dir/index.html";
  17804. auto dir_path = "./www/dir";
  17805. detail::FileStat stat_file(file_path);
  17806. EXPECT_TRUE(stat_file.is_file());
  17807. EXPECT_FALSE(stat_file.is_dir());
  17808. detail::FileStat stat_dir(dir_path);
  17809. EXPECT_FALSE(stat_dir.is_file());
  17810. EXPECT_TRUE(stat_dir.is_dir());
  17811. }
  17812. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17813. // IPv4 with default HTTP port (80)
  17814. EXPECT_EQ("example.com",
  17815. detail::make_host_and_port_string("example.com", 80, false));
  17816. // IPv4 with default HTTPS port (443)
  17817. EXPECT_EQ("example.com",
  17818. detail::make_host_and_port_string("example.com", 443, true));
  17819. // IPv4 with non-default HTTP port
  17820. EXPECT_EQ("example.com:8080",
  17821. detail::make_host_and_port_string("example.com", 8080, false));
  17822. // IPv4 with non-default HTTPS port
  17823. EXPECT_EQ("example.com:8443",
  17824. detail::make_host_and_port_string("example.com", 8443, true));
  17825. // IPv6 with default HTTP port (80)
  17826. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17827. // IPv6 with default HTTPS port (443)
  17828. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17829. // IPv6 with non-default HTTP port
  17830. EXPECT_EQ("[::1]:8080",
  17831. detail::make_host_and_port_string("::1", 8080, false));
  17832. // IPv6 with non-default HTTPS port
  17833. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17834. // IPv6 full address with default port
  17835. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17836. detail::make_host_and_port_string(
  17837. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17838. // IPv6 full address with non-default port
  17839. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17840. detail::make_host_and_port_string(
  17841. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17842. // IPv6 localhost with non-default port
  17843. EXPECT_EQ("[::1]:3000",
  17844. detail::make_host_and_port_string("::1", 3000, false));
  17845. // IPv6 with zone ID (link-local address) with default port
  17846. EXPECT_EQ("[fe80::1%eth0]",
  17847. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17848. // IPv6 with zone ID (link-local address) with non-default port
  17849. EXPECT_EQ("[fe80::1%eth0]:8080",
  17850. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17851. // Edge case: Port 443 with is_ssl=false (should add port)
  17852. EXPECT_EQ("example.com:443",
  17853. detail::make_host_and_port_string("example.com", 443, false));
  17854. // Edge case: Port 80 with is_ssl=true (should add port)
  17855. EXPECT_EQ("example.com:80",
  17856. detail::make_host_and_port_string("example.com", 80, true));
  17857. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17858. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17859. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17860. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17861. // Security fix: Already bracketed IPv6 should not get double brackets
  17862. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17863. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17864. EXPECT_EQ("[::1]:8080",
  17865. detail::make_host_and_port_string("[::1]", 8080, false));
  17866. EXPECT_EQ("[2001:db8::1]:8080",
  17867. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17868. EXPECT_EQ("[fe80::1%eth0]",
  17869. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17870. EXPECT_EQ("[fe80::1%eth0]:8080",
  17871. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17872. // Edge case: Empty host (should return as-is)
  17873. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17874. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17875. // This is a known limitation but shouldn't crash
  17876. EXPECT_EQ("[host:name]",
  17877. detail::make_host_and_port_string("host:name", 80, false));
  17878. // Port number edge cases (no validation, but should not crash)
  17879. EXPECT_EQ("example.com:0",
  17880. detail::make_host_and_port_string("example.com", 0, false));
  17881. EXPECT_EQ("example.com:-1",
  17882. detail::make_host_and_port_string("example.com", -1, false));
  17883. EXPECT_EQ("example.com:65535",
  17884. detail::make_host_and_port_string("example.com", 65535, false));
  17885. EXPECT_EQ("example.com:65536",
  17886. detail::make_host_and_port_string("example.com", 65536, false));
  17887. }
  17888. #ifdef CPPHTTPLIB_SSL_ENABLED
  17889. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17890. httplib::SSLClient cli("roblox.com", 443);
  17891. cli.set_follow_location(true);
  17892. auto res = cli.Get("/");
  17893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17894. EXPECT_EQ(StatusCode::OK_200, res->status);
  17895. }
  17896. #endif
  17897. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17898. Server svr;
  17899. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17900. EXPECT_EQ(res.status, 400);
  17901. });
  17902. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17903. auto se = detail::scope_exit([&] {
  17904. svr.stop();
  17905. thread.join();
  17906. ASSERT_FALSE(svr.is_running());
  17907. });
  17908. svr.wait_until_ready();
  17909. Client cli(HOST, PORT);
  17910. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17911. }
  17912. TEST(InvalidHeaderCharsTest, is_field_name) {
  17913. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17914. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17915. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17916. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17917. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17918. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17919. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17920. EXPECT_FALSE(detail::fields::is_field_name(""));
  17921. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17922. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17923. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17924. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17925. }
  17926. TEST(InvalidHeaderCharsTest, is_field_value) {
  17927. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17928. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17929. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17930. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17931. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17932. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17933. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17934. EXPECT_TRUE(detail::fields::is_field_value(""));
  17935. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17936. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17937. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17938. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17939. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17940. }
  17941. TEST(InvalidHeaderCharsTest, OnServer) {
  17942. Server svr;
  17943. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17944. std::string header = "Not Set";
  17945. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17946. res.set_header(header, "value");
  17947. res.set_content("Page Content Page Content", "text/plain");
  17948. });
  17949. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17950. std::string header = "Not Set";
  17951. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17952. res.set_header("X-Test", header);
  17953. res.set_content("Page Content Page Content", "text/plain");
  17954. });
  17955. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17956. auto se = detail::scope_exit([&] {
  17957. svr.stop();
  17958. thread.join();
  17959. ASSERT_FALSE(svr.is_running());
  17960. });
  17961. svr.wait_until_ready();
  17962. Client cli(HOST, PORT);
  17963. {
  17964. auto res = cli.Get(
  17965. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17967. EXPECT_EQ("Page Content Page Content", res->body);
  17968. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17969. }
  17970. {
  17971. auto res = cli.Get(
  17972. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17974. EXPECT_EQ("Page Content Page Content", res->body);
  17975. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17976. }
  17977. }
  17978. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17979. auto handled = false;
  17980. Server svr;
  17981. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17982. thread t = thread([&] { svr.listen(HOST, PORT); });
  17983. auto se = detail::scope_exit([&] {
  17984. svr.stop();
  17985. t.join();
  17986. ASSERT_FALSE(svr.is_running());
  17987. ASSERT_FALSE(handled);
  17988. });
  17989. svr.wait_until_ready();
  17990. auto req = "POST /test HTTP/1.1\r\n"
  17991. "Content-Length: x\r\n"
  17992. "\r\n";
  17993. std::string response;
  17994. ASSERT_TRUE(send_request(1, req, &response));
  17995. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17996. response.substr(0, response.find("\r\n")));
  17997. }
  17998. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17999. // case-insensitive, and a server that receives a 100-continue expectation in
  18000. // an HTTP/1.0 request MUST ignore it.
  18001. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18002. std::string response;
  18003. ASSERT_TRUE(send_request(1, req, &response, port));
  18004. *got_100 = response.find("100 Continue") != std::string::npos;
  18005. }
  18006. class ExpectTokenTest : public ::testing::Test {
  18007. protected:
  18008. void SetUp() override {
  18009. svr_.Post("/p", [](const Request &, Response &res) {
  18010. res.set_content("ok", "text/plain");
  18011. });
  18012. port_ = svr_.bind_to_any_port(HOST);
  18013. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18014. svr_.wait_until_ready();
  18015. }
  18016. void TearDown() override {
  18017. svr_.stop();
  18018. if (thread_.joinable()) { thread_.join(); }
  18019. }
  18020. std::string request(const char *version, const char *expect_value) const {
  18021. return std::string("POST /p ") + version +
  18022. "\r\n"
  18023. "Host: localhost\r\n"
  18024. "Content-Length: 2\r\n"
  18025. "Connection: close\r\n"
  18026. "Expect: " +
  18027. expect_value +
  18028. "\r\n"
  18029. "\r\n"
  18030. "hi";
  18031. }
  18032. Server svr_;
  18033. int port_ = 0;
  18034. thread thread_;
  18035. };
  18036. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18037. bool got_100 = false;
  18038. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18039. EXPECT_TRUE(got_100);
  18040. }
  18041. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18042. bool got_100 = true;
  18043. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18044. EXPECT_FALSE(got_100);
  18045. }
  18046. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18047. bool got_100 = false;
  18048. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18049. EXPECT_TRUE(got_100);
  18050. }
  18051. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18052. bool got_100 = false;
  18053. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18054. EXPECT_TRUE(got_100);
  18055. }
  18056. // `100 Continue` is sent only when the server starts reading the body, so a
  18057. // request rejected before that never invites the client to send it. The
  18058. // requests below carry the expectation but withhold the body, as a client
  18059. // waiting for `100 Continue` would.
  18060. // A POST that expects `100 Continue` and withholds its two-byte body.
  18061. static std::string expect_headers_only(const std::string &path) {
  18062. return "POST " + path +
  18063. " HTTP/1.1\r\n"
  18064. "Host: localhost\r\n"
  18065. "Content-Length: 2\r\n"
  18066. "Expect: 100-continue\r\n"
  18067. "\r\n";
  18068. }
  18069. class ExpectLazyContinueTest : public ::testing::Test {
  18070. protected:
  18071. void SetUp() override {
  18072. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18073. if (req.path == "/pre-routing") {
  18074. res.status = StatusCode::Unauthorized_401;
  18075. return Server::HandlerResponse::Handled;
  18076. }
  18077. return Server::HandlerResponse::Unhandled;
  18078. });
  18079. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18080. if (req.matched_route == "/pre-request") {
  18081. res.status = StatusCode::Forbidden_403;
  18082. return Server::HandlerResponse::Handled;
  18083. }
  18084. return Server::HandlerResponse::Unhandled;
  18085. });
  18086. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18087. res.set_content("ok", "text/plain");
  18088. });
  18089. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18090. res.set_content("ok", "text/plain");
  18091. });
  18092. svr_.Post("/reader-used", [](const Request &, Response &res,
  18093. const ContentReader &content_reader) {
  18094. std::string body;
  18095. content_reader([&](const char *data, size_t len) {
  18096. body.append(data, len);
  18097. return true;
  18098. });
  18099. res.set_content(body, "text/plain");
  18100. });
  18101. svr_.Post("/reader-unused",
  18102. [](const Request &, Response &res, const ContentReader &) {
  18103. res.set_content("ignored", "text/plain");
  18104. });
  18105. port_ = svr_.bind_to_any_port(HOST);
  18106. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18107. svr_.wait_until_ready();
  18108. }
  18109. void TearDown() override {
  18110. svr_.stop();
  18111. if (thread_.joinable()) { thread_.join(); }
  18112. }
  18113. // Sends `req` and reads until the server closes the connection. Returns
  18114. // false if the read had to wait for the client-side timeout instead.
  18115. bool send_until_closed(const std::string &req, std::string *resp) const {
  18116. auto start = std::chrono::steady_clock::now();
  18117. if (!send_request(3, req, resp, port_)) { return false; }
  18118. auto elapsed = std::chrono::steady_clock::now() - start;
  18119. return elapsed < std::chrono::seconds(2);
  18120. }
  18121. // The final response comes without `100 Continue`, and the server closes
  18122. // the connection since the body may or may not follow.
  18123. void expect_final_without_interim(const std::string &path,
  18124. const char *status_line) const {
  18125. std::string resp;
  18126. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18127. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18128. EXPECT_EQ(0u, resp.find(status_line));
  18129. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18130. }
  18131. Server svr_;
  18132. int port_ = 0;
  18133. thread thread_;
  18134. };
  18135. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18136. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18137. }
  18138. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18139. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18140. }
  18141. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18142. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18143. }
  18144. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18145. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18146. }
  18147. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18148. // The body follows once `100 Continue` has had time to arrive.
  18149. auto req = expect_headers_only("/reader-used");
  18150. req.insert(req.size() - 2, "Connection: close\r\n");
  18151. std::string resp;
  18152. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18153. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18154. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18155. EXPECT_NE(std::string::npos, resp.find("hi"));
  18156. }
  18157. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18158. // Large enough for the client to add `Expect: 100-continue` itself.
  18159. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18160. std::atomic<bool> body_sent{false};
  18161. Client cli(HOST, port_);
  18162. auto res = cli.Post(
  18163. "/pre-request", length,
  18164. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18165. body_sent = true;
  18166. std::string chunk(len, 'x');
  18167. sink.write(chunk.data(), chunk.size());
  18168. return true;
  18169. },
  18170. "application/octet-stream");
  18171. ASSERT_TRUE(res);
  18172. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18173. EXPECT_FALSE(body_sent);
  18174. }
  18175. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18176. Server svr;
  18177. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18178. return StatusCode::ExpectationFailed_417;
  18179. });
  18180. svr.Post("/p", [](const Request &, Response &res) {
  18181. res.set_content("ok", "text/plain");
  18182. });
  18183. auto port = svr.bind_to_any_port(HOST);
  18184. thread t = thread([&] { svr.listen_after_bind(); });
  18185. auto se = detail::scope_exit([&] {
  18186. svr.stop();
  18187. t.join();
  18188. });
  18189. svr.wait_until_ready();
  18190. std::string resp;
  18191. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18192. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18193. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18194. // Exactly one response: the route handler must not run after the 417.
  18195. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18196. }
  18197. #ifndef _WIN32
  18198. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18199. static constexpr char reject[] = "Unauthorized";
  18200. static constexpr char accept[] = "Upload accepted";
  18201. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18202. Server svr;
  18203. svr.set_expect_100_continue_handler(
  18204. [](const Request & /*req*/, Response &res) {
  18205. res.status = StatusCode::Unauthorized_401;
  18206. res.set_content(reject, "text/plain");
  18207. return res.status;
  18208. });
  18209. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18210. res.set_content(accept, "text/plain");
  18211. });
  18212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18213. auto se = detail::scope_exit([&] {
  18214. svr.stop();
  18215. thread.join();
  18216. ASSERT_FALSE(svr.is_running());
  18217. });
  18218. svr.wait_until_ready();
  18219. {
  18220. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18221. curl_easy_init(), &curl_easy_cleanup};
  18222. ASSERT_NE(curl, nullptr);
  18223. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18224. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18225. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18226. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18227. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18228. &curl_slist_free_all};
  18229. ASSERT_NE(list, nullptr);
  18230. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18231. struct read_data {
  18232. uint64_t read_size;
  18233. uint64_t total_size;
  18234. } data = {0, total_size};
  18235. using read_callback_t =
  18236. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18237. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18238. void *userdata) -> size_t {
  18239. read_data *d = (read_data *)userdata;
  18240. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18241. std::fill_n(ptr, size * nmemb, 'A');
  18242. d->read_size += size * nmemb;
  18243. return size * nmemb;
  18244. };
  18245. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18246. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18247. std::vector<char> buffer;
  18248. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18249. using write_callback_t =
  18250. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18251. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18252. void *userdata) -> size_t {
  18253. std::vector<char> *buf = (std::vector<char> *)userdata;
  18254. buf->reserve(buf->size() + size * nmemb + 1);
  18255. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18256. return size * nmemb;
  18257. };
  18258. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18259. {
  18260. const auto res = curl_easy_perform(curl.get());
  18261. ASSERT_EQ(res, CURLE_OK);
  18262. }
  18263. {
  18264. auto response_code = long{};
  18265. const auto res =
  18266. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18267. ASSERT_EQ(res, CURLE_OK);
  18268. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18269. }
  18270. {
  18271. auto dl = curl_off_t{};
  18272. const auto res =
  18273. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18274. ASSERT_EQ(res, CURLE_OK);
  18275. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18276. }
  18277. {
  18278. buffer.push_back('\0');
  18279. ASSERT_STRCASEEQ(buffer.data(), reject);
  18280. }
  18281. }
  18282. }
  18283. #endif
  18284. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18285. // Regression test for #2458.
  18286. //
  18287. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18288. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18289. // ticket can make the client socket spuriously readable during the
  18290. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18291. // the client withholds the body and then blocks reading a response that never
  18292. // comes, failing with `Failed to read connection`.
  18293. //
  18294. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18295. // within the timeout. This raw OpenSSL server deliberately never sends
  18296. // `100 Continue`; the client must still deliver the body and receive 200.
  18297. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18298. signal(SIGPIPE, SIG_IGN);
  18299. const auto port = PORT + 4;
  18300. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18301. ASSERT_NE(srv, INVALID_SOCKET);
  18302. int opt = 1;
  18303. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18304. sockaddr_in addr{};
  18305. addr.sin_family = AF_INET;
  18306. addr.sin_port = htons(static_cast<uint16_t>(port));
  18307. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18308. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18309. ASSERT_EQ(0, ::listen(srv, 1));
  18310. std::atomic<size_t> server_body_bytes{0};
  18311. auto server_thread = std::thread([&] {
  18312. sockaddr_in cli_addr{};
  18313. socklen_t cli_len = sizeof(cli_addr);
  18314. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18315. if (cli == INVALID_SOCKET) { return; }
  18316. // Bound the lifetime of the server side so a buggy client (which never
  18317. // sends the body) cannot make this thread block forever on join.
  18318. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18319. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18320. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18321. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18322. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18323. SSL *ssl = SSL_new(ctx);
  18324. SSL_set_fd(ssl, static_cast<int>(cli));
  18325. if (SSL_accept(ssl) > 0) {
  18326. // Read the request headers. Reading here also flushes the TLS 1.3
  18327. // session tickets to the client. Deliberately do NOT send
  18328. // `100 Continue`.
  18329. std::string buf;
  18330. char tmp[1024];
  18331. while (buf.find("\r\n\r\n") == std::string::npos) {
  18332. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18333. if (n <= 0) { break; }
  18334. buf.append(tmp, static_cast<size_t>(n));
  18335. }
  18336. // A correct client sends the body now; count what arrives.
  18337. auto pos = buf.find("\r\n\r\n");
  18338. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18339. while (body < 4096) {
  18340. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18341. if (n <= 0) { break; }
  18342. body += static_cast<size_t>(n);
  18343. }
  18344. server_body_bytes = body;
  18345. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18346. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18347. SSL_shutdown(ssl);
  18348. }
  18349. SSL_free(ssl);
  18350. detail::close_socket(cli);
  18351. SSL_CTX_free(ctx);
  18352. });
  18353. auto se = detail::scope_exit([&] {
  18354. server_thread.join();
  18355. detail::close_socket(srv);
  18356. });
  18357. SSLClient cli("127.0.0.1", port);
  18358. cli.enable_server_certificate_verification(false);
  18359. cli.set_connection_timeout(5, 0);
  18360. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18361. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18362. std::string body(4096, 'A');
  18363. auto res = cli.Put("/api/test", body, "application/json");
  18364. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18365. EXPECT_EQ(StatusCode::OK_200, res->status);
  18366. EXPECT_EQ(body.size(), server_body_bytes.load());
  18367. }
  18368. #endif
  18369. template <typename S, typename C>
  18370. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18371. svr.Get("/stream", [&](const Request &, Response &res) {
  18372. auto data = new std::string("01234567890123456789");
  18373. res.set_content_provider(
  18374. data->size(), "text/plain",
  18375. [&, data](size_t offset, size_t length, DataSink &sink) {
  18376. const size_t DATA_CHUNK_SIZE = 4;
  18377. const auto &d = *data;
  18378. std::this_thread::sleep_for(std::chrono::seconds(1));
  18379. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18380. return true;
  18381. },
  18382. [data](bool success) {
  18383. EXPECT_FALSE(success);
  18384. delete data;
  18385. });
  18386. });
  18387. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18388. auto i = new size_t(0);
  18389. res.set_content_provider(
  18390. "text/plain",
  18391. [i](size_t, DataSink &sink) {
  18392. if (*i < 5) {
  18393. std::this_thread::sleep_for(std::chrono::seconds(1));
  18394. sink.write("abcd", 4);
  18395. (*i)++;
  18396. } else {
  18397. sink.done();
  18398. }
  18399. return true;
  18400. },
  18401. [i](bool success) {
  18402. EXPECT_FALSE(success);
  18403. delete i;
  18404. });
  18405. });
  18406. svr.Get("/chunked", [&](const Request &, Response &res) {
  18407. auto i = new size_t(0);
  18408. res.set_chunked_content_provider(
  18409. "text/plain",
  18410. [i](size_t, DataSink &sink) {
  18411. if (*i < 5) {
  18412. std::this_thread::sleep_for(std::chrono::seconds(1));
  18413. sink.os << "abcd";
  18414. (*i)++;
  18415. } else {
  18416. sink.done();
  18417. }
  18418. return true;
  18419. },
  18420. [i](bool success) {
  18421. EXPECT_FALSE(success);
  18422. delete i;
  18423. });
  18424. });
  18425. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18426. auto se = detail::scope_exit([&] {
  18427. svr.stop();
  18428. listen_thread.join();
  18429. ASSERT_FALSE(svr.is_running());
  18430. });
  18431. svr.wait_until_ready();
  18432. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18433. {
  18434. auto start = std::chrono::steady_clock::now();
  18435. auto res = cli.Get("/stream");
  18436. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18437. std::chrono::steady_clock::now() - start)
  18438. .count();
  18439. ASSERT_FALSE(res);
  18440. EXPECT_EQ(Error::Read, res.error());
  18441. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18442. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18443. }
  18444. {
  18445. auto start = std::chrono::steady_clock::now();
  18446. auto res = cli.Get("/stream_without_length");
  18447. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18448. std::chrono::steady_clock::now() - start)
  18449. .count();
  18450. ASSERT_FALSE(res);
  18451. EXPECT_EQ(Error::Read, res.error());
  18452. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18453. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18454. }
  18455. {
  18456. auto start = std::chrono::steady_clock::now();
  18457. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18458. EXPECT_EQ("abcd", string(data, data_length));
  18459. return true;
  18460. });
  18461. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18462. std::chrono::steady_clock::now() - start)
  18463. .count();
  18464. ASSERT_FALSE(res);
  18465. EXPECT_EQ(Error::Read, res.error());
  18466. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18467. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18468. }
  18469. }
  18470. TEST(MaxTimeoutTest, ContentStream) {
  18471. time_t timeout = 2000;
  18472. time_t threshold = 200;
  18473. Server svr;
  18474. Client cli("localhost", PORT);
  18475. max_timeout_test(svr, cli, timeout, threshold);
  18476. }
  18477. #ifdef CPPHTTPLIB_SSL_ENABLED
  18478. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18479. time_t timeout = 2000;
  18480. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18482. SSLClient cli("localhost", PORT);
  18483. cli.enable_server_certificate_verification(false);
  18484. max_timeout_test(svr, cli, timeout, threshold);
  18485. }
  18486. #endif
  18487. class EventDispatcher {
  18488. public:
  18489. EventDispatcher() {}
  18490. bool wait_event(DataSink *sink) {
  18491. unique_lock<mutex> lk(m_);
  18492. int id = id_;
  18493. // Wait with timeout to prevent hanging if client disconnects
  18494. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18495. [&] { return cid_ == id; })) {
  18496. return false; // Timeout occurred
  18497. }
  18498. sink->write(message_.data(), message_.size());
  18499. return true;
  18500. }
  18501. void send_event(const string &message) {
  18502. lock_guard<mutex> lk(m_);
  18503. cid_ = id_++;
  18504. message_ = message;
  18505. cv_.notify_all();
  18506. }
  18507. private:
  18508. mutex m_;
  18509. condition_variable cv_;
  18510. atomic_int id_{0};
  18511. atomic_int cid_{-1};
  18512. string message_;
  18513. };
  18514. TEST(ClientInThreadTest, Issue2068) {
  18515. EventDispatcher ed;
  18516. Server svr;
  18517. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18518. res.set_chunked_content_provider("text/event-stream",
  18519. [&](size_t /*offset*/, DataSink &sink) {
  18520. return ed.wait_event(&sink);
  18521. });
  18522. });
  18523. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18524. svr.wait_until_ready();
  18525. thread event_thread([&] {
  18526. int id = 0;
  18527. while (svr.is_running()) {
  18528. this_thread::sleep_for(chrono::milliseconds(500));
  18529. std::stringstream ss;
  18530. ss << "data: " << id << "\n\n";
  18531. ed.send_event(ss.str());
  18532. id++;
  18533. }
  18534. });
  18535. auto se = detail::scope_exit([&] {
  18536. svr.stop();
  18537. listen_thread.join();
  18538. event_thread.join();
  18539. ASSERT_FALSE(svr.is_running());
  18540. });
  18541. {
  18542. auto client = detail::make_unique<Client>(HOST, PORT);
  18543. client->set_read_timeout(std::chrono::minutes(10));
  18544. std::atomic<bool> stop{false};
  18545. std::thread t([&] {
  18546. client->Get("/event1",
  18547. [&](const char *, size_t) -> bool { return !stop; });
  18548. });
  18549. std::this_thread::sleep_for(std::chrono::seconds(2));
  18550. stop = true;
  18551. client->stop();
  18552. t.join();
  18553. // Reset client after thread has finished
  18554. client.reset();
  18555. }
  18556. }
  18557. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18558. auto handled = false;
  18559. Server svr;
  18560. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18561. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18562. auto se = detail::scope_exit([&] {
  18563. svr.stop();
  18564. t.join();
  18565. ASSERT_FALSE(svr.is_running());
  18566. ASSERT_FALSE(handled);
  18567. });
  18568. svr.wait_until_ready();
  18569. // Two Content-Length headers with different values — must be rejected
  18570. auto req = "POST /test HTTP/1.1\r\n"
  18571. "Content-Length: 5\r\n"
  18572. "Content-Length: 10\r\n"
  18573. "\r\n"
  18574. "hello";
  18575. std::string response;
  18576. ASSERT_TRUE(send_request(1, req, &response));
  18577. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18578. response.substr(0, response.find("\r\n")));
  18579. }
  18580. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18581. auto handled = false;
  18582. Server svr;
  18583. svr.Post("/test", [&](const Request &, Response &res) {
  18584. handled = true;
  18585. res.set_content("ok", "text/plain");
  18586. });
  18587. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18588. auto se = detail::scope_exit([&] {
  18589. svr.stop();
  18590. t.join();
  18591. ASSERT_FALSE(svr.is_running());
  18592. ASSERT_TRUE(handled);
  18593. });
  18594. svr.wait_until_ready();
  18595. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18596. auto req = "POST /test HTTP/1.1\r\n"
  18597. "Host: localhost\r\n"
  18598. "Content-Length: 5\r\n"
  18599. "Content-Length: 5\r\n"
  18600. "\r\n"
  18601. "hello";
  18602. std::string response;
  18603. ASSERT_TRUE(send_request(1, req, &response));
  18604. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18605. }
  18606. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18607. Server svr;
  18608. svr.Get("/test", [](const Request &, Response &res) {
  18609. res.set_content("ok", "text/plain");
  18610. });
  18611. auto port = svr.bind_to_any_port(HOST);
  18612. thread t = thread([&] { svr.listen_after_bind(); });
  18613. auto se = detail::scope_exit([&] {
  18614. svr.stop();
  18615. t.join();
  18616. ASSERT_FALSE(svr.is_running());
  18617. });
  18618. svr.wait_until_ready();
  18619. auto status_line = [&](const std::string &host_lines) {
  18620. std::string res;
  18621. send_request(
  18622. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18623. &res, port);
  18624. return res.substr(0, res.find("\r\n"));
  18625. };
  18626. const char *accepted[] = {
  18627. "Host: localhost\r\n",
  18628. "Host: a.example:8080\r\n",
  18629. "Host: my_service\r\n",
  18630. "Host: [::1]:8080\r\n",
  18631. "Host: [fe80::1%25eth0]\r\n",
  18632. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18633. };
  18634. for (auto host_lines : accepted) {
  18635. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18636. }
  18637. const char *rejected[] = {
  18638. "Host: a.example\r\nHost: b.example\r\n",
  18639. "Host: a.example\r\nHost: a.example\r\n",
  18640. "Host: a@b.example\r\n",
  18641. "Host: a.example/b\r\n",
  18642. "Host: a.example\\b\r\n",
  18643. "Host: a.example?b\r\n",
  18644. "Host: a.example#b\r\n",
  18645. "Host: a.example b.example\r\n",
  18646. };
  18647. for (auto host_lines : rejected) {
  18648. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18649. << host_lines;
  18650. }
  18651. }
  18652. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18653. Server svr;
  18654. svr.Get("/", [](const Request &req, Response &res) {
  18655. EXPECT_EQ(2U, req.trailers.size());
  18656. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18657. // Denied
  18658. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18659. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18660. // Accepted
  18661. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18662. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18663. EXPECT_TRUE(req.has_trailer("X-World"));
  18664. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18665. res.set_content("ok", "text/plain");
  18666. });
  18667. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18668. auto se = detail::scope_exit([&] {
  18669. svr.stop();
  18670. t.join();
  18671. ASSERT_FALSE(svr.is_running());
  18672. });
  18673. svr.wait_until_ready();
  18674. const std::string req = "GET / HTTP/1.1\r\n"
  18675. "Transfer-Encoding: chunked\r\n"
  18676. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18677. "\r\n"
  18678. "0\r\n"
  18679. "Content-Length: 10\r\n"
  18680. "Host: internal.local\r\n"
  18681. "Content-Type: malicious/content\r\n"
  18682. "Cookie: any\r\n"
  18683. "Set-Cookie: any\r\n"
  18684. "X-Forwarded-For: attacker.com\r\n"
  18685. "X-Real-Ip: 1.1.1.1\r\n"
  18686. "X-Hello: hello\r\n"
  18687. "X-World: world\r\n"
  18688. "\r\n";
  18689. std::string res;
  18690. ASSERT_TRUE(send_request(1, req, &res));
  18691. }
  18692. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18693. // several field lines, and the combined value is what has to be parsed. A
  18694. // Trailer field split across lines therefore declares every name it lists;
  18695. // reading only the first line silently drops the trailers the later lines
  18696. // declare. The prohibited-trailer filter still applies to every line.
  18697. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18698. Server svr;
  18699. size_t observed_trailer_count = 0;
  18700. std::string observed_hello;
  18701. std::string observed_world;
  18702. bool observed_content_length = true;
  18703. svr.Get("/", [&](const Request &req, Response &res) {
  18704. observed_trailer_count = req.trailers.size();
  18705. observed_hello = req.get_trailer_value("X-Hello");
  18706. observed_world = req.get_trailer_value("X-World");
  18707. observed_content_length = req.has_trailer("Content-Length");
  18708. res.set_content("ok", "text/plain");
  18709. });
  18710. auto port = svr.bind_to_any_port(HOST);
  18711. thread t = thread([&]() { svr.listen_after_bind(); });
  18712. auto se = detail::scope_exit([&] {
  18713. svr.stop();
  18714. t.join();
  18715. ASSERT_FALSE(svr.is_running());
  18716. });
  18717. svr.wait_until_ready();
  18718. const std::string req = "GET / HTTP/1.1\r\n"
  18719. "Host: localhost\r\n"
  18720. "Transfer-Encoding: chunked\r\n"
  18721. "Trailer: X-Hello\r\n"
  18722. "Trailer: X-World, Content-Length\r\n"
  18723. "\r\n"
  18724. "0\r\n"
  18725. "X-Hello: hello\r\n"
  18726. "X-World: world\r\n"
  18727. "Content-Length: 10\r\n"
  18728. "\r\n";
  18729. std::string res;
  18730. ASSERT_TRUE(send_request(1, req, &res, port));
  18731. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18732. // Accepted: both field lines contribute to the declared set
  18733. EXPECT_EQ(2U, observed_trailer_count);
  18734. EXPECT_EQ(observed_hello, "hello");
  18735. EXPECT_EQ(observed_world, "world");
  18736. // Denied: a prohibited name stays prohibited on a later field line
  18737. EXPECT_FALSE(observed_content_length);
  18738. }
  18739. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18740. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18741. // unbounded run of fields that are never declared, because the counter would
  18742. // only advance for declared fields.
  18743. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18744. Server svr;
  18745. bool handler_called = false;
  18746. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18747. handler_called = true;
  18748. res.set_content("ok", "text/plain");
  18749. });
  18750. auto port = svr.bind_to_any_port(HOST);
  18751. thread t = thread([&]() { svr.listen_after_bind(); });
  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. // Declare nothing, then send far more undeclared trailer fields than the
  18759. // header-count limit. Parsing must stop and reject the request rather than
  18760. // read every line.
  18761. std::string req = "GET / HTTP/1.1\r\n"
  18762. "Transfer-Encoding: chunked\r\n"
  18763. "\r\n"
  18764. "0\r\n";
  18765. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18766. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18767. }
  18768. req += "\r\n";
  18769. std::string res;
  18770. ASSERT_TRUE(send_request(1, req, &res, port));
  18771. // The request is rejected before the handler runs.
  18772. EXPECT_FALSE(handler_called);
  18773. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18774. }
  18775. // The set of declared trailer names is capped so a peer cannot grow it without
  18776. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18777. // declared past the cap is not honored, even if the field is actually sent.
  18778. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18779. Server svr;
  18780. // One name inside the cap and one past it, so the test tracks the cap rather
  18781. // than a fixed count.
  18782. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18783. const std::string within_cap_name = "X-T-0";
  18784. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18785. bool observed_within_cap = false;
  18786. bool observed_past_cap = false;
  18787. svr.Get("/", [&](const Request &req, Response &res) {
  18788. observed_within_cap = req.has_trailer(within_cap_name);
  18789. observed_past_cap = req.has_trailer(past_cap_name);
  18790. res.set_content("ok", "text/plain");
  18791. });
  18792. auto port = svr.bind_to_any_port(HOST);
  18793. thread t = thread([&]() { svr.listen_after_bind(); });
  18794. auto se = detail::scope_exit([&] {
  18795. svr.stop();
  18796. t.join();
  18797. ASSERT_FALSE(svr.is_running());
  18798. });
  18799. svr.wait_until_ready();
  18800. // Declare more trailer names than the cap in a single Trailer field, then
  18801. // actually send the first (within the cap) and the last (past it).
  18802. std::string trailer_decl = "Trailer: ";
  18803. for (int i = 0; i < declared_count; i++) {
  18804. if (i != 0) { trailer_decl += ", "; }
  18805. trailer_decl += "X-T-" + std::to_string(i);
  18806. }
  18807. trailer_decl += "\r\n";
  18808. const std::string req = "GET / HTTP/1.1\r\n"
  18809. "Host: localhost\r\n"
  18810. "Transfer-Encoding: chunked\r\n" +
  18811. trailer_decl +
  18812. "\r\n"
  18813. "0\r\n" +
  18814. within_cap_name + ": a\r\n" + past_cap_name +
  18815. ": b\r\n"
  18816. "\r\n";
  18817. std::string res;
  18818. ASSERT_TRUE(send_request(1, req, &res, port));
  18819. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18820. // A name within the cap is honored; one declared past the cap is dropped.
  18821. EXPECT_TRUE(observed_within_cap);
  18822. EXPECT_FALSE(observed_past_cap);
  18823. }
  18824. // A direct client that is not listed in trusted_proxies must not be able to
  18825. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18826. // the peer address on the actual TCP connection determines whether the
  18827. // header is honored.
  18828. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18829. Server svr;
  18830. // Deliberately does NOT include the loopback address the test client
  18831. // actually connects from, so the direct connection is not a trusted proxy.
  18832. svr.set_trusted_proxies({"203.0.113.66"});
  18833. std::string observed_remote_addr;
  18834. svr.Get("/ip", [&](const Request &req, Response &res) {
  18835. observed_remote_addr = req.remote_addr;
  18836. res.set_content("ok", "text/plain");
  18837. });
  18838. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18839. auto se = detail::scope_exit([&] {
  18840. svr.stop();
  18841. t.join();
  18842. ASSERT_FALSE(svr.is_running());
  18843. });
  18844. svr.wait_until_ready();
  18845. Client cli(HOST, PORT);
  18846. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18848. EXPECT_EQ(StatusCode::OK_200, res->status);
  18849. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18850. // ignored entirely and the real connection-level address retained.
  18851. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18852. observed_remote_addr == "127.0.0.1");
  18853. }
  18854. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18855. Server svr;
  18856. std::string observed_remote_addr;
  18857. std::string observed_xff;
  18858. svr.Get("/ip", [&](const Request &req, Response &res) {
  18859. observed_remote_addr = req.remote_addr;
  18860. observed_xff = req.get_header_value("X-Forwarded-For");
  18861. res.set_content("ok", "text/plain");
  18862. });
  18863. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18864. auto se = detail::scope_exit([&] {
  18865. svr.stop();
  18866. t.join();
  18867. ASSERT_FALSE(svr.is_running());
  18868. });
  18869. svr.wait_until_ready();
  18870. Client cli(HOST, PORT);
  18871. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18873. EXPECT_EQ(StatusCode::OK_200, res->status);
  18874. EXPECT_EQ(observed_xff, "203.0.113.66");
  18875. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18876. observed_remote_addr == "127.0.0.1");
  18877. }
  18878. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18879. Server svr;
  18880. svr.set_trusted_proxies({"203.0.113.66"});
  18881. std::string observed_remote_addr;
  18882. std::string observed_xff;
  18883. svr.Get("/ip", [&](const Request &req, Response &res) {
  18884. observed_remote_addr = req.remote_addr;
  18885. observed_xff = req.get_header_value("X-Forwarded-For");
  18886. res.set_content("ok", "text/plain");
  18887. });
  18888. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18889. auto se = detail::scope_exit([&] {
  18890. svr.stop();
  18891. t.join();
  18892. ASSERT_FALSE(svr.is_running());
  18893. });
  18894. svr.wait_until_ready();
  18895. Client cli(HOST, PORT);
  18896. auto res = cli.Get("/ip");
  18897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18898. EXPECT_EQ(StatusCode::OK_200, res->status);
  18899. EXPECT_EQ(observed_xff, "");
  18900. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18901. observed_remote_addr == "127.0.0.1");
  18902. }
  18903. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18904. Server svr;
  18905. // Include the loopback address the test client actually connects from, so
  18906. // the direct connection itself is recognized as the trusted proxy hop.
  18907. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18908. std::string observed_remote_addr;
  18909. std::string observed_xff;
  18910. svr.Get("/ip", [&](const Request &req, Response &res) {
  18911. observed_remote_addr = req.remote_addr;
  18912. observed_xff = req.get_header_value("X-Forwarded-For");
  18913. res.set_content("ok", "text/plain");
  18914. });
  18915. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18916. auto se = detail::scope_exit([&] {
  18917. svr.stop();
  18918. t.join();
  18919. ASSERT_FALSE(svr.is_running());
  18920. });
  18921. svr.wait_until_ready();
  18922. Client cli(HOST, PORT);
  18923. auto res = cli.Get(
  18924. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18926. EXPECT_EQ(StatusCode::OK_200, res->status);
  18927. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18928. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18929. }
  18930. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18931. Server svr;
  18932. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18933. std::string observed_remote_addr;
  18934. std::string observed_xff;
  18935. svr.Get("/ip", [&](const Request &req, Response &res) {
  18936. observed_remote_addr = req.remote_addr;
  18937. observed_xff = req.get_header_value("X-Forwarded-For");
  18938. res.set_content("ok", "text/plain");
  18939. });
  18940. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18941. auto se = detail::scope_exit([&] {
  18942. svr.stop();
  18943. t.join();
  18944. ASSERT_FALSE(svr.is_running());
  18945. });
  18946. svr.wait_until_ready();
  18947. Client cli(HOST, PORT);
  18948. auto res = cli.Get(
  18949. "/ip",
  18950. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18952. EXPECT_EQ(StatusCode::OK_200, res->status);
  18953. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18954. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18955. }
  18956. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18957. Server svr;
  18958. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18959. std::string observed_remote_addr;
  18960. std::string observed_xff;
  18961. svr.Get("/ip", [&](const Request &req, Response &res) {
  18962. observed_remote_addr = req.remote_addr;
  18963. observed_xff = req.get_header_value("X-Forwarded-For");
  18964. res.set_content("ok", "text/plain");
  18965. });
  18966. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18967. auto se = detail::scope_exit([&] {
  18968. svr.stop();
  18969. t.join();
  18970. ASSERT_FALSE(svr.is_running());
  18971. });
  18972. svr.wait_until_ready();
  18973. Client cli(HOST, PORT);
  18974. auto res = cli.Get(
  18975. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18977. EXPECT_EQ(StatusCode::OK_200, res->status);
  18978. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18979. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18980. // and must not be selected.
  18981. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18982. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18983. }
  18984. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18985. Server svr;
  18986. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18987. std::string observed_remote_addr;
  18988. svr.Get("/ip", [&](const Request &req, Response &res) {
  18989. observed_remote_addr = req.remote_addr;
  18990. res.set_content("ok", "text/plain");
  18991. });
  18992. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18993. auto se = detail::scope_exit([&] {
  18994. svr.stop();
  18995. t.join();
  18996. ASSERT_FALSE(svr.is_running());
  18997. });
  18998. svr.wait_until_ready();
  18999. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19000. // a forged address and the trusted proxy's own address; the forged value must
  19001. // not win over the address the trusted proxy actually recorded.
  19002. Client cli(HOST, PORT);
  19003. auto res = cli.Get(
  19004. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19006. EXPECT_EQ(StatusCode::OK_200, res->status);
  19007. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19008. }
  19009. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19010. Server svr;
  19011. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19012. std::string observed_remote_addr;
  19013. std::string observed_xff;
  19014. svr.Get("/ip", [&](const Request &req, Response &res) {
  19015. observed_remote_addr = req.remote_addr;
  19016. observed_xff = req.get_header_value("X-Forwarded-For");
  19017. res.set_content("ok", "text/plain");
  19018. });
  19019. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19020. auto se = detail::scope_exit([&] {
  19021. svr.stop();
  19022. t.join();
  19023. ASSERT_FALSE(svr.is_running());
  19024. });
  19025. svr.wait_until_ready();
  19026. Client cli(HOST, PORT);
  19027. auto res = cli.Get(
  19028. "/ip",
  19029. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19031. EXPECT_EQ(StatusCode::OK_200, res->status);
  19032. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19033. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19034. }
  19035. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19036. Server svr;
  19037. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19038. std::string observed_remote_addr;
  19039. std::string observed_xff;
  19040. svr.Get("/ip", [&](const Request &req, Response &res) {
  19041. observed_remote_addr = req.remote_addr;
  19042. observed_xff = req.get_header_value("X-Forwarded-For");
  19043. res.set_content("ok", "text/plain");
  19044. });
  19045. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19046. auto se = detail::scope_exit([&] {
  19047. svr.stop();
  19048. t.join();
  19049. ASSERT_FALSE(svr.is_running());
  19050. });
  19051. svr.wait_until_ready();
  19052. std::string raw_req =
  19053. "GET /ip HTTP/1.1\r\n"
  19054. "Host: localhost\r\n"
  19055. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19056. "Connection: close\r\n"
  19057. "\r\n";
  19058. std::string out;
  19059. ASSERT_TRUE(send_request(5, raw_req, &out));
  19060. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19061. // Header parser trims surrounding whitespace of the header value
  19062. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19063. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19064. }
  19065. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19066. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19067. // their own X-Forwarded-For as a separate field line rather than extending the
  19068. // one the client sent, so every occurrence has to be taken into account.
  19069. // Reading only the first one hands back the address the client chose.
  19070. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19071. Server svr;
  19072. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19073. std::string observed_remote_addr;
  19074. size_t observed_xff_count = 0;
  19075. svr.Get("/ip", [&](const Request &req, Response &res) {
  19076. observed_remote_addr = req.remote_addr;
  19077. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19078. res.set_content("ok", "text/plain");
  19079. });
  19080. auto port = svr.bind_to_any_port(HOST);
  19081. thread t = thread([&]() { svr.listen_after_bind(); });
  19082. auto se = detail::scope_exit([&] {
  19083. svr.stop();
  19084. t.join();
  19085. ASSERT_FALSE(svr.is_running());
  19086. });
  19087. svr.wait_until_ready();
  19088. // The client supplies the first field line; the trusted proxy appends the
  19089. // address it observed as a second one.
  19090. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19091. "Host: localhost\r\n"
  19092. "X-Forwarded-For: 1.2.3.4\r\n"
  19093. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19094. "Connection: close\r\n"
  19095. "\r\n";
  19096. std::string out;
  19097. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19098. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19099. EXPECT_EQ(observed_xff_count, 2U);
  19100. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19101. // The same chain spread over one field line per hop derives the same client
  19102. // address, i.e. the split and the comma-joined representations agree.
  19103. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19104. "Host: localhost\r\n"
  19105. "X-Forwarded-For: 1.2.3.4\r\n"
  19106. "X-Forwarded-For: 198.51.100.23\r\n"
  19107. "X-Forwarded-For: 192.0.2.45\r\n"
  19108. "Connection: close\r\n"
  19109. "\r\n";
  19110. out.clear();
  19111. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19112. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19113. EXPECT_EQ(observed_xff_count, 3U);
  19114. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19115. }
  19116. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19117. // crash the server (it used to call front() on an empty vector inside
  19118. // get_client_ip). The connection-level remote address must be retained instead.
  19119. static void run_malformed_xff_test(const std::string &xff_value) {
  19120. Server svr;
  19121. svr.set_trusted_proxies({"192.0.2.45"});
  19122. std::string observed_remote_addr;
  19123. svr.Get("/ip", [&](const Request &req, Response &res) {
  19124. observed_remote_addr = req.remote_addr;
  19125. res.set_content("ok", "text/plain");
  19126. });
  19127. int port = 0;
  19128. thread t = thread([&]() {
  19129. port = svr.bind_to_any_port(HOST);
  19130. svr.listen_after_bind();
  19131. });
  19132. auto se = detail::scope_exit([&] {
  19133. svr.stop();
  19134. t.join();
  19135. ASSERT_FALSE(svr.is_running());
  19136. });
  19137. svr.wait_until_ready();
  19138. Client cli(HOST, port);
  19139. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19141. EXPECT_EQ(StatusCode::OK_200, res->status);
  19142. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19143. observed_remote_addr == "127.0.0.1");
  19144. }
  19145. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19146. run_malformed_xff_test("");
  19147. }
  19148. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19149. run_malformed_xff_test(",");
  19150. }
  19151. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19152. run_malformed_xff_test(", , ,");
  19153. }
  19154. // The same rule applies to Accept: a request whose acceptable types are spread
  19155. // over several field lines must be negotiated against all of them.
  19156. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19157. // case-insensitive connection options. Comparing the whole field value against
  19158. // one option misses a client that sends several of them, and misses every
  19159. // casing but the one written in the comparison.
  19160. //
  19161. // Sends req, reads the response, then reuses the same socket for a second
  19162. // request to find out whether the server kept the connection.
  19163. static void probe_connection_reuse(int port, const std::string &req,
  19164. bool *announced_close, bool *reusable) {
  19165. auto error = Error::Success;
  19166. auto sock = detail::create_client_socket(
  19167. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19168. /*connection_timeout_sec=*/5, 0,
  19169. /*read_timeout_sec=*/1, 0,
  19170. /*write_timeout_sec=*/5, 0, std::string(), error);
  19171. ASSERT_NE(sock, INVALID_SOCKET);
  19172. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19173. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19174. "Host: localhost\r\n"
  19175. "Connection: close\r\n"
  19176. "\r\n";
  19177. std::string first_response;
  19178. std::string second_response;
  19179. detail::process_client_socket(
  19180. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19181. [&](Stream &strm) {
  19182. if (strm.write(req.data(), req.size()) !=
  19183. static_cast<ssize_t>(req.size())) {
  19184. return false;
  19185. }
  19186. char buf[512];
  19187. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19188. // Headers plus the two-byte body of the handler below
  19189. while (reader.getline()) {
  19190. first_response += reader.ptr();
  19191. if (first_response.find("ok") != std::string::npos) { break; }
  19192. }
  19193. if (strm.write(second.data(), second.size()) !=
  19194. static_cast<ssize_t>(second.size())) {
  19195. return true;
  19196. }
  19197. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19198. while (reader2.getline()) {
  19199. second_response += reader2.ptr();
  19200. if (second_response.find("ok") != std::string::npos) { break; }
  19201. }
  19202. return true;
  19203. });
  19204. *announced_close =
  19205. first_response.find("Connection: close") != std::string::npos;
  19206. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19207. }
  19208. class ConnectionTokenTest : public ::testing::Test {
  19209. protected:
  19210. void SetUp() override {
  19211. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19212. res.set_content("ok", "text/plain");
  19213. });
  19214. port_ = svr_.bind_to_any_port(HOST);
  19215. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19216. svr_.wait_until_ready();
  19217. }
  19218. void TearDown() override {
  19219. svr_.stop();
  19220. if (thread_.joinable()) { thread_.join(); }
  19221. }
  19222. Server svr_;
  19223. int port_ = 0;
  19224. thread thread_;
  19225. };
  19226. // "close" alongside another option still closes the connection, and the
  19227. // response says so rather than leaving the peer to discover it.
  19228. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19229. bool announced_close = false;
  19230. bool reusable = true;
  19231. probe_connection_reuse(port_,
  19232. "GET /keepalive HTTP/1.1\r\n"
  19233. "Host: localhost\r\n"
  19234. "Connection: keep-alive, close\r\n"
  19235. "\r\n",
  19236. &announced_close, &reusable);
  19237. EXPECT_TRUE(announced_close);
  19238. EXPECT_FALSE(reusable);
  19239. }
  19240. // "close" split over two field lines is the same list, so it is honored too.
  19241. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19242. bool announced_close = false;
  19243. bool reusable = true;
  19244. probe_connection_reuse(port_,
  19245. "GET /keepalive HTTP/1.1\r\n"
  19246. "Host: localhost\r\n"
  19247. "Connection: keep-alive\r\n"
  19248. "Connection: close\r\n"
  19249. "\r\n",
  19250. &announced_close, &reusable);
  19251. EXPECT_TRUE(announced_close);
  19252. EXPECT_FALSE(reusable);
  19253. }
  19254. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19255. // keep-alive in the spelling everyone actually sends keeps its connection.
  19256. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19257. bool announced_close = false;
  19258. bool reusable = false;
  19259. probe_connection_reuse(port_,
  19260. "GET /keepalive HTTP/1.0\r\n"
  19261. "Host: localhost\r\n"
  19262. "Connection: keep-alive\r\n"
  19263. "\r\n",
  19264. &announced_close, &reusable);
  19265. EXPECT_FALSE(announced_close);
  19266. EXPECT_TRUE(reusable);
  19267. }
  19268. // A token the value merely contains is not the token itself.
  19269. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19270. bool announced_close = false;
  19271. bool reusable = false;
  19272. probe_connection_reuse(port_,
  19273. "GET /keepalive HTTP/1.1\r\n"
  19274. "Host: localhost\r\n"
  19275. "Connection: notclose\r\n"
  19276. "\r\n",
  19277. &announced_close, &reusable);
  19278. EXPECT_FALSE(announced_close);
  19279. EXPECT_TRUE(reusable);
  19280. }
  19281. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19282. Server svr;
  19283. std::vector<std::string> observed_types;
  19284. svr.Get("/", [&](const Request &req, Response &res) {
  19285. observed_types = req.accept_content_types;
  19286. res.set_content("ok", "text/plain");
  19287. });
  19288. auto port = svr.bind_to_any_port(HOST);
  19289. thread t = thread([&]() { svr.listen_after_bind(); });
  19290. auto se = detail::scope_exit([&] {
  19291. svr.stop();
  19292. t.join();
  19293. ASSERT_FALSE(svr.is_running());
  19294. });
  19295. svr.wait_until_ready();
  19296. Client cli(HOST, port);
  19297. Headers headers;
  19298. headers.emplace("Accept", "text/plain;q=0.5");
  19299. headers.emplace("Accept", "application/json");
  19300. auto res = cli.Get("/", headers);
  19301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19302. EXPECT_EQ(StatusCode::OK_200, res->status);
  19303. // Sorted by q-value, so the second field line's type comes first
  19304. ASSERT_EQ(2U, observed_types.size());
  19305. EXPECT_EQ("application/json", observed_types[0]);
  19306. EXPECT_EQ("text/plain", observed_types[1]);
  19307. }
  19308. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19309. // empty field line must not contribute a bare comma to the combined value.
  19310. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19311. Server svr;
  19312. std::vector<std::string> observed_types;
  19313. svr.Get("/", [&](const Request &req, Response &res) {
  19314. observed_types = req.accept_content_types;
  19315. res.set_content("ok", "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. // Empty first field line, then a real one
  19326. std::string raw_req = "GET / HTTP/1.1\r\n"
  19327. "Host: localhost\r\n"
  19328. "Accept:\r\n"
  19329. "Accept: application/json\r\n"
  19330. "Connection: close\r\n"
  19331. "\r\n";
  19332. std::string out;
  19333. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19334. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19335. ASSERT_EQ(1U, observed_types.size());
  19336. EXPECT_EQ("application/json", observed_types[0]);
  19337. }
  19338. // The skip in get_combined_header_value() is what keeps an empty field line
  19339. // from contributing a bare comma. Only a trailing empty field line exercises
  19340. // it: a leading one is already covered by the "combined is still empty" check,
  19341. // and parse_accept_header() now ignores the empty element either way, so the
  19342. // request-level test above can no longer tell the two apart.
  19343. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19344. Headers headers;
  19345. headers.emplace("Accept", "text/html");
  19346. headers.emplace("Accept", "");
  19347. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19348. headers.clear();
  19349. headers.emplace("Accept", "");
  19350. headers.emplace("Accept", "application/json");
  19351. EXPECT_EQ("application/json",
  19352. detail::get_combined_header_value(headers, "Accept"));
  19353. }
  19354. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19355. // An encoding offered on a later Accept-Encoding field line is still offered.
  19356. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19357. Server svr;
  19358. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19359. res.set_content(std::string(1024, 'x'), "text/plain");
  19360. });
  19361. auto port = svr.bind_to_any_port(HOST);
  19362. thread t = thread([&]() { svr.listen_after_bind(); });
  19363. auto se = detail::scope_exit([&] {
  19364. svr.stop();
  19365. t.join();
  19366. ASSERT_FALSE(svr.is_running());
  19367. });
  19368. svr.wait_until_ready();
  19369. Client cli(HOST, port);
  19370. cli.set_decompress(false);
  19371. Headers headers;
  19372. headers.emplace("Accept-Encoding", "identity");
  19373. headers.emplace("Accept-Encoding", "gzip");
  19374. auto res = cli.Get("/", headers);
  19375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19376. EXPECT_EQ(StatusCode::OK_200, res->status);
  19377. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19378. }
  19379. #endif
  19380. #ifndef _WIN32
  19381. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19382. Server svr;
  19383. svr.Post("/post", [&](const Request &req, Response &res) {
  19384. res.set_content(req.body, "text/plain");
  19385. });
  19386. svr.Put("/put", [&](const Request &req, Response &res) {
  19387. res.set_content(req.body, "text/plain");
  19388. });
  19389. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19390. res.set_content(req.body, "text/plain");
  19391. });
  19392. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19393. res.set_content(req.body, "text/plain");
  19394. });
  19395. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19396. auto se = detail::scope_exit([&] {
  19397. svr.stop();
  19398. t.join();
  19399. ASSERT_FALSE(svr.is_running());
  19400. });
  19401. svr.wait_until_ready();
  19402. std::string resp;
  19403. // POST without Content-Length
  19404. ASSERT_TRUE(send_request(5,
  19405. "POST /post 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. // PUT without Content-Length
  19412. resp.clear();
  19413. ASSERT_TRUE(send_request(5,
  19414. "PUT /put 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. // PATCH without Content-Length
  19421. resp.clear();
  19422. ASSERT_TRUE(send_request(5,
  19423. "PATCH /patch HTTP/1.1\r\n"
  19424. "Host: localhost\r\n"
  19425. "Connection: close\r\n"
  19426. "\r\n",
  19427. &resp));
  19428. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19429. // DELETE without Content-Length
  19430. resp.clear();
  19431. ASSERT_TRUE(send_request(5,
  19432. "DELETE /delete HTTP/1.1\r\n"
  19433. "Host: localhost\r\n"
  19434. "Connection: close\r\n"
  19435. "\r\n",
  19436. &resp));
  19437. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19438. }
  19439. #endif
  19440. //==============================================================================
  19441. // open_stream() Tests
  19442. //==============================================================================
  19443. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19444. std::string result;
  19445. char buf[8192];
  19446. ssize_t n;
  19447. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19448. result.append(buf, static_cast<size_t>(n));
  19449. }
  19450. return result;
  19451. }
  19452. // Mock stream for unit tests
  19453. class MockStream : public Stream {
  19454. public:
  19455. std::string data;
  19456. size_t pos = 0;
  19457. ssize_t error_after = -1; // -1 = no error
  19458. explicit MockStream(const std::string &d, ssize_t err = -1)
  19459. : data(d), error_after(err) {}
  19460. bool is_readable() const override { return true; }
  19461. bool wait_readable() const override { return true; }
  19462. bool wait_writable() const override { return true; }
  19463. ssize_t read(char *ptr, size_t size) override {
  19464. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19465. if (pos >= data.size()) return 0;
  19466. size_t limit =
  19467. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19468. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19469. std::memcpy(ptr, data.data() + pos, to_read);
  19470. pos += to_read;
  19471. return static_cast<ssize_t>(to_read);
  19472. }
  19473. ssize_t write(const char *, size_t) override { return -1; }
  19474. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19475. ip = "127.0.0.1";
  19476. port = 0;
  19477. }
  19478. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19479. ip = "127.0.0.1";
  19480. port = 0;
  19481. }
  19482. socket_t socket() const override { return INVALID_SOCKET; }
  19483. time_t duration() const override { return 0; }
  19484. };
  19485. TEST(StreamHandleTest, Basic) {
  19486. ClientImpl::StreamHandle handle;
  19487. EXPECT_FALSE(handle.is_valid());
  19488. handle.response = detail::make_unique<Response>();
  19489. handle.error = Error::Connection;
  19490. EXPECT_FALSE(handle.is_valid());
  19491. handle.error = Error::Success;
  19492. EXPECT_TRUE(handle.is_valid());
  19493. }
  19494. TEST(BodyReaderTest, Basic) {
  19495. MockStream stream("Hello, World!");
  19496. detail::BodyReader reader;
  19497. reader.stream = &stream;
  19498. reader.content_length = 13;
  19499. char buf[32];
  19500. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19501. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19502. EXPECT_TRUE(reader.eof);
  19503. }
  19504. TEST(BodyReaderTest, NoStream) {
  19505. detail::BodyReader reader;
  19506. char buf[32];
  19507. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19508. EXPECT_EQ(Error::Connection, reader.last_error);
  19509. }
  19510. TEST(BodyReaderTest, Error) {
  19511. MockStream stream("Hello, World!", 5);
  19512. detail::BodyReader reader;
  19513. reader.stream = &stream;
  19514. reader.content_length = 13;
  19515. char buf[32];
  19516. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19517. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19518. EXPECT_EQ(Error::Read, reader.last_error);
  19519. }
  19520. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19521. // Mock-based StreamHandle tests relying on private internals are removed.
  19522. class OpenStreamTest : public ::testing::Test {
  19523. protected:
  19524. void SetUp() override {
  19525. svr_.Get("/hello", [](const Request &, Response &res) {
  19526. res.set_content("Hello World!", "text/plain");
  19527. });
  19528. svr_.Get("/large", [](const Request &, Response &res) {
  19529. res.set_content(std::string(10000, 'X'), "text/plain");
  19530. });
  19531. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19532. res.set_content("Hello World!", "image/jpeg");
  19533. res.set_header("Content-Encoding", "UTF-8");
  19534. });
  19535. svr_.Get("/chunked", [](const Request &, Response &res) {
  19536. res.set_chunked_content_provider("text/plain",
  19537. [](size_t offset, DataSink &sink) {
  19538. if (offset < 15) {
  19539. sink.write("chunk", 5);
  19540. return true;
  19541. }
  19542. sink.done();
  19543. return true;
  19544. });
  19545. });
  19546. svr_.Get("/compressible", [](const Request &, Response &res) {
  19547. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19548. DataSink &sink) {
  19549. if (offset < 100 * 1024) {
  19550. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19551. sink.write(chunk.data(), chunk.size());
  19552. return true;
  19553. }
  19554. sink.done();
  19555. return true;
  19556. });
  19557. });
  19558. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19559. [](const Request & /*req*/, Response &res) {
  19560. auto i = new int(0);
  19561. res.set_header("Trailer", "Content-Length, X-Allowed");
  19562. res.set_chunked_content_provider(
  19563. "text/plain",
  19564. [i](size_t /*offset*/, DataSink &sink) {
  19565. switch (*i) {
  19566. case 0: sink.os << "123"; break;
  19567. case 1: sink.os << "456"; break;
  19568. case 2: sink.os << "789"; break;
  19569. case 3: {
  19570. sink.done_with_trailer(
  19571. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19572. } break;
  19573. }
  19574. (*i)++;
  19575. return true;
  19576. },
  19577. [i](bool success) {
  19578. EXPECT_TRUE(success);
  19579. delete i;
  19580. });
  19581. });
  19582. // Echo headers endpoint for header-related tests
  19583. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19584. std::string body;
  19585. for (const auto &h : req.headers) {
  19586. body.append(h.first);
  19587. body.push_back(':');
  19588. body.append(h.second);
  19589. body.push_back('\n');
  19590. }
  19591. res.set_content(body, "text/plain");
  19592. });
  19593. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19594. std::string body;
  19595. for (const auto &h : req.headers) {
  19596. body.append(h.first);
  19597. body.push_back(':');
  19598. body.append(h.second);
  19599. body.push_back('\n');
  19600. }
  19601. res.set_content(body, "text/plain");
  19602. });
  19603. port_ = svr_.bind_to_any_port("127.0.0.1");
  19604. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19605. svr_.wait_until_ready();
  19606. }
  19607. void TearDown() override {
  19608. svr_.stop();
  19609. if (thread_.joinable()) thread_.join();
  19610. }
  19611. Server svr_;
  19612. std::thread thread_;
  19613. int port_ = 0;
  19614. };
  19615. TEST_F(OpenStreamTest, Basic) {
  19616. Client cli("127.0.0.1", port_);
  19617. auto handle = cli.open_stream("GET", "/hello");
  19618. EXPECT_TRUE(handle.is_valid());
  19619. EXPECT_EQ("Hello World!", read_all(handle));
  19620. }
  19621. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19622. Client cli("127.0.0.1", port_);
  19623. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19624. ASSERT_TRUE(handle.is_valid());
  19625. EXPECT_EQ("Hello World!", read_all(handle));
  19626. }
  19627. TEST_F(OpenStreamTest, SmallBuffer) {
  19628. Client cli("127.0.0.1", port_);
  19629. auto handle = cli.open_stream("GET", "/hello");
  19630. std::string result;
  19631. char buf[4];
  19632. ssize_t n;
  19633. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19634. result.append(buf, static_cast<size_t>(n));
  19635. EXPECT_EQ("Hello World!", result);
  19636. }
  19637. TEST_F(OpenStreamTest, DefaultHeaders) {
  19638. Client cli("127.0.0.1", port_);
  19639. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19640. {
  19641. auto handle = cli.open_stream("GET", "/echo-headers");
  19642. ASSERT_TRUE(handle.is_valid());
  19643. auto body = read_all(handle);
  19644. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19645. std::string::npos);
  19646. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19647. std::string::npos);
  19648. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19649. }
  19650. // open_stream POST with body and no explicit content_type should NOT add
  19651. // text/plain Content-Type (behavior differs from non-streaming path), but
  19652. // should include Content-Length
  19653. {
  19654. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19655. ASSERT_TRUE(handle.is_valid());
  19656. auto body = read_all(handle);
  19657. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19658. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19659. }
  19660. // open_stream POST with explicit Content-Type should preserve it
  19661. {
  19662. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19663. {{"Content-Type", "application/custom"}},
  19664. "{}", "application/custom");
  19665. ASSERT_TRUE(handle.is_valid());
  19666. auto body = read_all(handle);
  19667. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19668. }
  19669. // User-specified User-Agent must not be overwritten for stream API
  19670. {
  19671. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19672. {{"User-Agent", "MyAgent/1.2"}});
  19673. ASSERT_TRUE(handle.is_valid());
  19674. auto body = read_all(handle);
  19675. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19676. }
  19677. }
  19678. TEST_F(OpenStreamTest, Large) {
  19679. Client cli("127.0.0.1", port_);
  19680. auto handle = cli.open_stream("GET", "/large");
  19681. EXPECT_EQ(10000u, read_all(handle).size());
  19682. }
  19683. TEST_F(OpenStreamTest, ConnectionError) {
  19684. Client cli("127.0.0.1", 9999);
  19685. auto handle = cli.open_stream("GET", "/hello");
  19686. EXPECT_FALSE(handle.is_valid());
  19687. }
  19688. TEST_F(OpenStreamTest, Chunked) {
  19689. Client cli("127.0.0.1", port_);
  19690. auto handle = cli.open_stream("GET", "/chunked");
  19691. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19692. "Transfer-Encoding") == "chunked");
  19693. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19694. }
  19695. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19696. Client cli("127.0.0.1", port_);
  19697. auto handle =
  19698. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19699. ASSERT_TRUE(handle.is_valid());
  19700. // Consume body to allow trailers to be received/parsed
  19701. auto body = read_all(handle);
  19702. // Explicitly parse trailers (ensure trailers are available for assertion)
  19703. handle.parse_trailers_if_needed();
  19704. EXPECT_EQ(std::string("123456789"), body);
  19705. // The response should include a Trailer header declaring both names
  19706. ASSERT_TRUE(handle.response);
  19707. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19708. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19709. handle.response->get_header_value("Trailer"));
  19710. // Prohibited trailer must not be present
  19711. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19712. // Allowed trailer should be present
  19713. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19714. EXPECT_EQ(std::string("yes"),
  19715. handle.response->get_trailer_value("X-Allowed"));
  19716. // Verify trailers are NOT present as regular headers
  19717. EXPECT_EQ(std::string(""),
  19718. handle.response->get_header_value("Content-Length"));
  19719. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19720. }
  19721. // Accepts one connection on an OS-assigned port, which it hands over through
  19722. // port_promise, reads the request head and sends back response. after_send,
  19723. // if given, runs on the connection before it is closed.
  19724. static std::thread
  19725. serve_single_response(std::promise<int> &port_promise,
  19726. const std::string &response,
  19727. std::function<void(socket_t)> after_send = nullptr) {
  19728. return std::thread([&port_promise, response, after_send] {
  19729. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19730. default_socket_options(srv);
  19731. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19732. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19733. sockaddr_in addr{};
  19734. addr.sin_family = AF_INET;
  19735. addr.sin_port = htons(0); // Let OS assign a free port
  19736. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19737. int opt = 1;
  19738. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19739. #ifdef _WIN32
  19740. reinterpret_cast<const char *>(&opt),
  19741. #else
  19742. &opt,
  19743. #endif
  19744. sizeof(opt));
  19745. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19746. ::listen(srv, 1) != 0) {
  19747. port_promise.set_value(-1);
  19748. detail::close_socket(srv);
  19749. return;
  19750. }
  19751. socklen_t addr_len = sizeof(addr);
  19752. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19753. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19754. sockaddr_in cli_addr{};
  19755. socklen_t cli_len = sizeof(cli_addr);
  19756. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19757. if (cli != INVALID_SOCKET) {
  19758. // Read the complete HTTP request (until the blank line that terminates
  19759. // headers) before sending the response. If the server closes the socket
  19760. // while the client's request data is still unread in the kernel receive
  19761. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19762. // connection on both sides: it discards the client's receive buffer
  19763. // (which already holds our response) and causes any in-progress write on
  19764. // the client to fail with ECONNRESET. Reading all request data first
  19765. // ensures close() emits a graceful FIN.
  19766. {
  19767. char rbuf[256];
  19768. std::string req;
  19769. while (req.find("\r\n\r\n") == std::string::npos) {
  19770. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19771. if (n <= 0) { break; }
  19772. req.append(rbuf, static_cast<size_t>(n));
  19773. }
  19774. }
  19775. ::send(cli,
  19776. #ifdef _WIN32
  19777. static_cast<const char *>(response.c_str()),
  19778. static_cast<int>(response.size()),
  19779. #else
  19780. response.c_str(), response.size(),
  19781. #endif
  19782. 0);
  19783. if (after_send) { after_send(cli); }
  19784. detail::close_socket(cli);
  19785. }
  19786. detail::close_socket(srv);
  19787. });
  19788. }
  19789. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19790. #ifndef _WIN32
  19791. signal(SIGPIPE, SIG_IGN);
  19792. #endif
  19793. std::promise<int> port_promise;
  19794. auto port_future = port_promise.get_future();
  19795. auto server_thread =
  19796. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19797. "Content-Type: text/plain\r\n"
  19798. "Content-Length: not-a-number\r\n"
  19799. "Connection: close\r\n"
  19800. "\r\n"
  19801. "hello");
  19802. auto port = port_future.get();
  19803. ASSERT_GT(port, 0);
  19804. Client cli("127.0.0.1", port);
  19805. auto handle = cli.open_stream("GET", "/");
  19806. EXPECT_FALSE(handle.is_valid());
  19807. server_thread.join();
  19808. }
  19809. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19810. #ifndef _WIN32
  19811. signal(SIGPIPE, SIG_IGN);
  19812. #endif
  19813. std::promise<int> port_promise;
  19814. auto port_future = port_promise.get_future();
  19815. auto server_thread = serve_single_response(
  19816. port_promise, "HTTP/1.1 200 OK\r\n"
  19817. "Content-Type: text/plain\r\n"
  19818. "Content-Length: 99999999999999999999999999\r\n"
  19819. "Connection: close\r\n"
  19820. "\r\n"
  19821. "hello");
  19822. auto port = port_future.get();
  19823. ASSERT_GT(port, 0);
  19824. // Historically std::stoull would throw std::out_of_range here and crash
  19825. // the process, then parsing silently clamped to a bogus framing length and
  19826. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19827. // so the stream fails to open, matching the not-a-number case above. The
  19828. // process still must NOT terminate.
  19829. Client cli("127.0.0.1", port);
  19830. auto handle = cli.open_stream("GET", "/");
  19831. EXPECT_FALSE(handle.is_valid());
  19832. server_thread.join();
  19833. }
  19834. // Serves `response` to the single request `fn` makes with a fresh client.
  19835. template <typename Fn>
  19836. static void with_single_response(const std::string &response, Fn fn) {
  19837. #ifndef _WIN32
  19838. signal(SIGPIPE, SIG_IGN);
  19839. #endif
  19840. std::promise<int> port_promise;
  19841. auto port_future = port_promise.get_future();
  19842. auto server_thread = serve_single_response(port_promise, response);
  19843. auto se = detail::scope_exit([&] { server_thread.join(); });
  19844. auto port = port_future.get();
  19845. ASSERT_GT(port, 0);
  19846. Client cli("127.0.0.1", port);
  19847. fn(cli);
  19848. }
  19849. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19850. // Neither Content-Length nor chunked: the body ends at the close
  19851. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19852. "Connection: close\r\n"
  19853. "\r\n"
  19854. "hello";
  19855. with_single_response(close_delimited, [](Client &cli) {
  19856. auto handle = cli.open_stream("GET", "/");
  19857. ASSERT_TRUE(handle.is_valid());
  19858. EXPECT_EQ("hello", read_all(handle));
  19859. EXPECT_FALSE(handle.has_read_error());
  19860. });
  19861. // A close before the end of the Content-Length is still an error
  19862. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19863. "Content-Length: 10\r\n"
  19864. "\r\n"
  19865. "hello";
  19866. with_single_response(short_content_length, [](Client &cli) {
  19867. auto handle = cli.open_stream("GET", "/");
  19868. ASSERT_TRUE(handle.is_valid());
  19869. read_all(handle);
  19870. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19871. });
  19872. // So is a close before the last chunk
  19873. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19874. "Transfer-Encoding: chunked\r\n"
  19875. "\r\n"
  19876. "5\r\nhello\r\n";
  19877. with_single_response(short_chunked, [](Client &cli) {
  19878. auto handle = cli.open_stream("GET", "/");
  19879. ASSERT_TRUE(handle.is_valid());
  19880. read_all(handle);
  19881. EXPECT_TRUE(handle.has_read_error());
  19882. });
  19883. }
  19884. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19885. const char *responses[] = {
  19886. "HTTP/1.1 103 Early Hints\r\n"
  19887. "Link: </style.css>; rel=preload\r\n"
  19888. "\r\n"
  19889. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19890. "HTTP/1.1 100 Continue\r\n"
  19891. "X-Note: interim\r\n"
  19892. "\r\n"
  19893. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19894. };
  19895. for (auto response : responses) {
  19896. with_single_response(response, [](Client &cli) {
  19897. auto res = cli.Get("/");
  19898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19899. EXPECT_EQ(StatusCode::OK_200, res->status);
  19900. EXPECT_EQ("ok", res->body);
  19901. });
  19902. }
  19903. }
  19904. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19905. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19906. const std::string final_response =
  19907. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19908. std::string interims;
  19909. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19910. interims += interim;
  19911. }
  19912. with_single_response(interims + final_response, [](Client &cli) {
  19913. auto res = cli.Get("/");
  19914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19915. EXPECT_EQ("ok", res->body);
  19916. });
  19917. with_single_response(interims + interim + final_response, [](Client &cli) {
  19918. auto res = cli.Get("/");
  19919. ASSERT_FALSE(res);
  19920. EXPECT_EQ(Error::Read, res.error());
  19921. });
  19922. }
  19923. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19924. #ifndef _WIN32
  19925. signal(SIGPIPE, SIG_IGN);
  19926. #endif
  19927. // The server answers the head without asking for the body. Bytes it then
  19928. // reads on the connection would be taken for the body the request declared.
  19929. auto closed_by_client = false;
  19930. std::promise<int> port_promise;
  19931. auto server_thread = serve_single_response(
  19932. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19933. [&](socket_t sock) {
  19934. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19935. char buf[256];
  19936. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19937. });
  19938. Client cli("127.0.0.1", port_promise.get_future().get());
  19939. cli.set_keep_alive(true);
  19940. cli.set_read_timeout(1, 0);
  19941. // Long enough for the client to send Expect: 100-continue.
  19942. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19944. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19945. cli.Get("/second");
  19946. server_thread.join();
  19947. EXPECT_TRUE(closed_by_client);
  19948. }
  19949. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19950. // Long enough for the client to send Expect: 100-continue
  19951. with_single_response(
  19952. "HTTP/1.1 103 Early Hints\r\n"
  19953. "Link: </style.css>; rel=preload\r\n"
  19954. "\r\n"
  19955. "HTTP/1.1 401 Unauthorized\r\n"
  19956. "Content-Length: 0\r\n\r\n",
  19957. [](Client &cli) {
  19958. cli.set_read_timeout(2, 0);
  19959. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19961. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19962. });
  19963. }
  19964. #ifdef CPPHTTPLIB_SSL_ENABLED
  19965. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19966. #ifndef _WIN32
  19967. signal(SIGPIPE, SIG_IGN);
  19968. #endif
  19969. auto reused = false;
  19970. std::promise<int> port_promise;
  19971. auto server_thread = serve_single_response(
  19972. port_promise,
  19973. "HTTP/1.1 401 Unauthorized\r\n"
  19974. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19975. "Content-Length: 0\r\n\r\n",
  19976. [&](socket_t sock) {
  19977. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19978. char buf[256];
  19979. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19980. });
  19981. Client cli("127.0.0.1", port_promise.get_future().get());
  19982. cli.set_keep_alive(true);
  19983. cli.set_digest_auth("user", "pass");
  19984. cli.set_read_timeout(1, 0);
  19985. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19986. server_thread.join();
  19987. EXPECT_FALSE(reused);
  19988. }
  19989. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19990. // Any other answer to CONNECT would read as the origin's response.
  19991. struct {
  19992. const char *response;
  19993. bool passed_on;
  19994. } cases[] = {
  19995. {"HTTP/1.1 201 Created\r\n"
  19996. "Set-Cookie: session=from-proxy\r\n"
  19997. "Content-Length: 0\r\n\r\n",
  19998. false},
  19999. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20000. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20001. "Content-Length: 0\r\n\r\n",
  20002. true},
  20003. };
  20004. for (const auto &c : cases) {
  20005. std::promise<int> port_promise;
  20006. auto server_thread = serve_single_response(port_promise, c.response);
  20007. SSLClient cli("example.com", 443);
  20008. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20009. auto res = cli.Get("/");
  20010. server_thread.join();
  20011. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20012. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20013. if (res) {
  20014. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20015. }
  20016. }
  20017. }
  20018. #endif
  20019. // Records the client's error logger calls as "error METHOD path", or
  20020. // "error null" for a call without a request
  20021. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20022. return [&log](const Error &err, const Request *req) {
  20023. log.push_back(to_string(err) + " " +
  20024. (req ? req->method + " " + req->path : "null"));
  20025. };
  20026. }
  20027. // A failed request is reported once, with the request the caller made
  20028. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20029. Server svr;
  20030. svr.Get("/big", [](const Request &, Response &res) {
  20031. res.set_content(std::string(100000, 'b'), "text/plain");
  20032. });
  20033. auto port = svr.bind_to_any_port(HOST);
  20034. std::thread t([&]() { svr.listen_after_bind(); });
  20035. auto se = detail::scope_exit([&] {
  20036. svr.stop();
  20037. t.join();
  20038. });
  20039. svr.wait_until_ready();
  20040. Client cli(HOST, port);
  20041. std::vector<std::string> log;
  20042. cli.set_error_logger(record_errors(log));
  20043. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20044. cli.Get("/big", [](const char *, size_t) { return false; });
  20045. EXPECT_EQ(expected, log);
  20046. log.clear();
  20047. cli.Get("/big", [](size_t, size_t) { return false; });
  20048. EXPECT_EQ(expected, log);
  20049. }
  20050. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20051. // Fails while the body is read
  20052. auto broken = [](const Request &, Response &res) {
  20053. res.set_content_provider(10, "text/plain",
  20054. [](size_t, size_t, DataSink &) { return false; });
  20055. };
  20056. Server other;
  20057. other.Get("/broken", broken);
  20058. auto other_port = other.bind_to_any_port(HOST);
  20059. std::thread other_t([&]() { other.listen_after_bind(); });
  20060. auto other_se = detail::scope_exit([&] {
  20061. other.stop();
  20062. other_t.join();
  20063. });
  20064. other.wait_until_ready();
  20065. Server svr;
  20066. svr.Get("/broken", broken);
  20067. svr.Get("/same-origin",
  20068. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20069. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20070. res.set_redirect("http://" + std::string(HOST) + ":" +
  20071. std::to_string(other_port) + "/broken");
  20072. });
  20073. auto port = svr.bind_to_any_port(HOST);
  20074. std::thread t([&]() { svr.listen_after_bind(); });
  20075. auto se = detail::scope_exit([&] {
  20076. svr.stop();
  20077. t.join();
  20078. });
  20079. svr.wait_until_ready();
  20080. Client cli(HOST, port);
  20081. cli.set_follow_location(true);
  20082. std::vector<std::string> log;
  20083. cli.set_error_logger(record_errors(log));
  20084. for (auto path : {"/same-origin", "/cross-origin"}) {
  20085. log.clear();
  20086. auto res = cli.Get(path);
  20087. ASSERT_FALSE(res);
  20088. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20089. log);
  20090. }
  20091. }
  20092. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20093. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20094. std::vector<std::string> log;
  20095. cli.set_error_logger(record_errors(log));
  20096. auto handle = cli.open_stream("GET", "/x");
  20097. EXPECT_FALSE(handle.is_valid());
  20098. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20099. log);
  20100. });
  20101. }
  20102. #ifdef CPPHTTPLIB_SSL_ENABLED
  20103. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20104. // Not a TLS server, so the handshake fails. It waits for a request line in
  20105. // the handshake bytes, so a short read timeout lets it close quickly.
  20106. Server svr;
  20107. svr.set_read_timeout(0, 100000);
  20108. svr.Get("/x", [](const Request &, Response &res) {
  20109. res.set_content("x", "text/plain");
  20110. });
  20111. auto port = svr.bind_to_any_port(HOST);
  20112. std::thread t([&]() { svr.listen_after_bind(); });
  20113. auto se = detail::scope_exit([&] {
  20114. svr.stop();
  20115. t.join();
  20116. });
  20117. svr.wait_until_ready();
  20118. std::vector<std::string> log;
  20119. SSLClient cli(HOST, port);
  20120. cli.enable_server_certificate_verification(false);
  20121. cli.set_error_logger(record_errors(log));
  20122. auto res = cli.Get("/x");
  20123. ASSERT_FALSE(res);
  20124. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20125. log.clear();
  20126. auto handle = cli.open_stream("GET", "/x");
  20127. EXPECT_FALSE(handle.is_valid());
  20128. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20129. log.clear();
  20130. SSLClient no_ca(HOST, port);
  20131. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20132. no_ca.set_error_logger(record_errors(log));
  20133. res = no_ca.Get("/x");
  20134. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20135. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20136. }
  20137. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20138. #ifndef _WIN32
  20139. signal(SIGPIPE, SIG_IGN);
  20140. #endif
  20141. // Refused, answered with a challenge, or closed without an answer
  20142. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20143. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20144. "Content-Length: 0\r\n\r\n",
  20145. ""}) {
  20146. std::promise<int> port_promise;
  20147. auto server_thread = serve_single_response(port_promise, response);
  20148. SSLClient cli("example.com", 443);
  20149. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20150. std::vector<std::string> log;
  20151. cli.set_error_logger(record_errors(log));
  20152. auto res = cli.Get("/");
  20153. server_thread.join();
  20154. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20155. << response;
  20156. }
  20157. }
  20158. #endif
  20159. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20160. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20161. // the chunked coding and drop Content-Length, so a front-end that trusts
  20162. // Content-Length would disagree about where the body ends (response
  20163. // smuggling). The client must reject such a response.
  20164. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20165. for (const char *te : {"chunked", "gzip, chunked"}) {
  20166. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20167. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20168. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20169. "5\r\nhello\r\n0\r\n\r\n";
  20170. with_single_response(response, [&](Client &cli) {
  20171. auto res = cli.Get("/");
  20172. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20173. EXPECT_EQ(Error::Read, res.error()) << te;
  20174. });
  20175. with_single_response(response, [&](Client &cli) {
  20176. auto handle = cli.open_stream("GET", "/");
  20177. EXPECT_FALSE(handle.is_valid()) << te;
  20178. EXPECT_EQ(Error::Read, handle.error) << te;
  20179. });
  20180. }
  20181. }
  20182. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20183. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20184. // closing the connection (unlike a request, which must be rejected).
  20185. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20186. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20187. "Transfer-Encoding: chunked\r\n"
  20188. "Connection: close\r\n"
  20189. "\r\n"
  20190. "5\r\nhello\r\n0\r\n\r\n",
  20191. "HTTP/1.1 200 OK\r\n"
  20192. "Transfer-Encoding: gzip\r\n"
  20193. "Connection: close\r\n"
  20194. "\r\n"
  20195. "hello"}) {
  20196. with_single_response(response, [&](Client &cli) {
  20197. auto res = cli.Get("/");
  20198. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20199. EXPECT_EQ("hello", res->body);
  20200. });
  20201. with_single_response(response, [&](Client &cli) {
  20202. auto handle = cli.open_stream("GET", "/");
  20203. ASSERT_TRUE(handle.is_valid()) << response;
  20204. EXPECT_EQ("hello", read_all(handle));
  20205. });
  20206. }
  20207. }
  20208. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20209. // framing headers describe nothing to read and must not be rejected.
  20210. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20211. const std::string framing = "Content-Length: 5\r\n"
  20212. "Transfer-Encoding: chunked\r\n"
  20213. "Connection: close\r\n"
  20214. "\r\n";
  20215. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20216. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20217. });
  20218. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20219. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20220. });
  20221. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20222. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20223. with_single_response(response, [&](Client &cli) {
  20224. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20225. });
  20226. with_single_response(response, [&](Client &cli) {
  20227. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20228. });
  20229. }
  20230. }
  20231. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20232. // header section, so a stream opened on one has nothing to read, whatever
  20233. // framing or coding headers it carries.
  20234. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20235. struct Case {
  20236. const char *method;
  20237. const char *status;
  20238. };
  20239. // A reader of the declared body reports an early close when nothing
  20240. // follows, and hands back what does.
  20241. struct Framing {
  20242. const char *headers;
  20243. const char *after;
  20244. };
  20245. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20246. Case{"GET", "304 Not Modified"}}) {
  20247. for (const auto &f :
  20248. {Framing{"Content-Length: 5\r\n", ""},
  20249. Framing{"Content-Length: 5\r\n", "hello"},
  20250. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20251. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20252. // Not decoded, so a build without Brotli opens it too
  20253. Framing{"Content-Encoding: br\r\n", ""}}) {
  20254. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20255. "Connection: close\r\n"
  20256. "\r\n" +
  20257. f.after;
  20258. with_single_response(response, [&](Client &cli) {
  20259. auto handle = cli.open_stream(c.method, "/");
  20260. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20261. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20262. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20263. });
  20264. }
  20265. }
  20266. }
  20267. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20268. // response, is faulty framing, so the connection is not reused after it.
  20269. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20270. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20271. "Content-Length: 0\r\n"
  20272. "Transfer-Encoding: chunked\r\n"
  20273. "\r\n"
  20274. "5\r\nhello\r\n0\r\n\r\n",
  20275. "HTTP/1.0 200 Connection established\r\n"
  20276. "Connection: keep-alive\r\n"
  20277. "Transfer-Encoding: chunked\r\n"
  20278. "\r\n"
  20279. "5\r\nhello\r\n0\r\n\r\n"}) {
  20280. with_single_response(response, [&](Client &cli) {
  20281. cli.set_keep_alive(true);
  20282. auto res = cli.Get("/");
  20283. ASSERT_TRUE(res) << response;
  20284. EXPECT_EQ("hello", res->body);
  20285. EXPECT_FALSE(cli.is_socket_open()) << response;
  20286. });
  20287. }
  20288. }
  20289. // A payload max length of 0 means no limit, however the body is framed.
  20290. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20291. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20292. "Transfer-Encoding: chunked\r\n"
  20293. "\r\n"
  20294. "5\r\nhello\r\n0\r\n\r\n",
  20295. "HTTP/1.1 200 OK\r\n"
  20296. "Connection: close\r\n"
  20297. "\r\n"
  20298. "hello"}) {
  20299. with_single_response(response, [&](Client &cli) {
  20300. cli.set_payload_max_length(0);
  20301. auto res = cli.Get("/");
  20302. ASSERT_TRUE(res) << response;
  20303. EXPECT_EQ("hello", res->body) << response;
  20304. });
  20305. }
  20306. }
  20307. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20308. Server svr;
  20309. svr.set_payload_max_length(0);
  20310. svr.Post("/echo", [](const Request &req, Response &res) {
  20311. res.set_content(req.body, "text/plain");
  20312. });
  20313. auto port = svr.bind_to_any_port(HOST);
  20314. thread t = thread([&] { svr.listen_after_bind(); });
  20315. auto se = detail::scope_exit([&] {
  20316. svr.stop();
  20317. t.join();
  20318. ASSERT_FALSE(svr.is_running());
  20319. });
  20320. svr.wait_until_ready();
  20321. Client cli(HOST, port);
  20322. auto res = cli.Post(
  20323. "/echo",
  20324. [](size_t /*offset*/, DataSink &sink) {
  20325. sink.write("hello", 5);
  20326. sink.done();
  20327. return true;
  20328. },
  20329. "text/plain");
  20330. ASSERT_TRUE(res);
  20331. EXPECT_EQ(StatusCode::OK_200, res->status);
  20332. EXPECT_EQ("hello", res->body);
  20333. }
  20334. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20335. TEST_F(OpenStreamTest, Gzip) {
  20336. Client cli("127.0.0.1", port_);
  20337. auto handle = cli.open_stream("GET", "/compressible", {},
  20338. {{"Accept-Encoding", "gzip"}});
  20339. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20340. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20341. }
  20342. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20343. Client cli("127.0.0.1", port_);
  20344. auto handle =
  20345. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20346. {{"Accept-Encoding", "gzip"}});
  20347. ASSERT_TRUE(handle.is_valid());
  20348. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20349. EXPECT_EQ("123456789", read_all(handle));
  20350. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20351. }
  20352. #endif
  20353. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20354. TEST_F(OpenStreamTest, Brotli) {
  20355. Client cli("127.0.0.1", port_);
  20356. auto handle =
  20357. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20358. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20359. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20360. }
  20361. #endif
  20362. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20363. TEST_F(OpenStreamTest, Zstd) {
  20364. Client cli("127.0.0.1", port_);
  20365. auto handle = cli.open_stream("GET", "/compressible", {},
  20366. {{"Accept-Encoding", "zstd"}});
  20367. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20368. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20369. }
  20370. #endif
  20371. #ifdef CPPHTTPLIB_SSL_ENABLED
  20372. class SSLOpenStreamTest : public ::testing::Test {
  20373. protected:
  20374. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20375. void SetUp() override {
  20376. svr_.Get("/hello", [](const Request &, Response &res) {
  20377. res.set_content("Hello SSL World!", "text/plain");
  20378. });
  20379. svr_.Get("/chunked", [](const Request &, Response &res) {
  20380. res.set_chunked_content_provider("text/plain",
  20381. [](size_t offset, DataSink &sink) {
  20382. if (offset < 15) {
  20383. sink.write("chunk", 5);
  20384. return true;
  20385. }
  20386. sink.done();
  20387. return true;
  20388. });
  20389. });
  20390. svr_.Post("/echo", [](const Request &req, Response &res) {
  20391. res.set_content(req.body, req.get_header_value("Content-Type"));
  20392. });
  20393. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20394. std::string body = req.body;
  20395. res.set_chunked_content_provider(
  20396. "text/plain", [body](size_t offset, DataSink &sink) {
  20397. if (offset < body.size()) {
  20398. sink.write(body.data() + offset, body.size() - offset);
  20399. }
  20400. sink.done();
  20401. return true;
  20402. });
  20403. });
  20404. port_ = svr_.bind_to_any_port("127.0.0.1");
  20405. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20406. svr_.wait_until_ready();
  20407. }
  20408. void TearDown() override {
  20409. svr_.stop();
  20410. if (thread_.joinable()) thread_.join();
  20411. }
  20412. SSLServer svr_;
  20413. std::thread thread_;
  20414. int port_ = 0;
  20415. };
  20416. TEST_F(SSLOpenStreamTest, Basic) {
  20417. SSLClient cli("127.0.0.1", port_);
  20418. cli.enable_server_certificate_verification(false);
  20419. auto handle = cli.open_stream("GET", "/hello");
  20420. ASSERT_TRUE(handle.is_valid());
  20421. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20422. }
  20423. TEST_F(SSLOpenStreamTest, Chunked) {
  20424. SSLClient cli("127.0.0.1", port_);
  20425. cli.enable_server_certificate_verification(false);
  20426. auto handle = cli.open_stream("GET", "/chunked");
  20427. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20428. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20429. "Transfer-Encoding") == "chunked");
  20430. auto body = read_all(handle);
  20431. EXPECT_EQ("chunkchunkchunk", body);
  20432. }
  20433. TEST_F(SSLOpenStreamTest, Post) {
  20434. SSLClient cli("127.0.0.1", port_);
  20435. cli.enable_server_certificate_verification(false);
  20436. auto handle =
  20437. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20438. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20439. EXPECT_EQ(200, handle.response->status);
  20440. auto body = read_all(handle);
  20441. EXPECT_EQ("Hello SSL POST", body);
  20442. }
  20443. TEST_F(SSLOpenStreamTest, PostChunked) {
  20444. SSLClient cli("127.0.0.1", port_);
  20445. cli.enable_server_certificate_verification(false);
  20446. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20447. "Chunked SSL Data", "text/plain");
  20448. ASSERT_TRUE(handle.is_valid());
  20449. EXPECT_EQ(200, handle.response->status);
  20450. auto body = read_all(handle);
  20451. EXPECT_EQ("Chunked SSL Data", body);
  20452. }
  20453. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20454. // Content-Length is terminated by the server closing the connection. When the
  20455. // SSL peer sends a close_notify after the body, the client must treat it as a
  20456. // clean EOF and return a successful response rather than an error.
  20457. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20458. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20459. ASSERT_TRUE(svr.is_valid());
  20460. svr.set_keep_alive_max_count(1);
  20461. const std::string expected_body = "Hello from connection-close response!";
  20462. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20463. res.set_content_provider("text/plain",
  20464. [&](size_t offset, DataSink &sink) -> bool {
  20465. if (offset < expected_body.size()) {
  20466. sink.write(expected_body.data() + offset,
  20467. expected_body.size() - offset);
  20468. }
  20469. sink.done();
  20470. return true;
  20471. });
  20472. });
  20473. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20474. auto se = detail::scope_exit([&] {
  20475. svr.stop();
  20476. listen_thread.join();
  20477. ASSERT_FALSE(svr.is_running());
  20478. });
  20479. svr.wait_until_ready();
  20480. SSLClient cli(HOST, PORT);
  20481. cli.enable_server_certificate_verification(false);
  20482. auto res = cli.Get("/no-content-length");
  20483. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20484. EXPECT_EQ(StatusCode::OK_200, res->status);
  20485. EXPECT_EQ(expected_body, res->body);
  20486. }
  20487. #endif // CPPHTTPLIB_SSL_ENABLED
  20488. //==============================================================================
  20489. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20490. // results for various scenarios.
  20491. //==============================================================================
  20492. TEST(ParityTest, GetVsOpenStream) {
  20493. Server svr;
  20494. const std::string path = "/parity";
  20495. const std::string content = "Parity test content: hello world";
  20496. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20497. res.set_content(content, "text/plain");
  20498. });
  20499. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20500. auto se = detail::scope_exit([&] {
  20501. svr.stop();
  20502. t.join();
  20503. ASSERT_FALSE(svr.is_running());
  20504. });
  20505. svr.wait_until_ready();
  20506. Client cli(HOST, PORT);
  20507. // Non-stream path
  20508. auto r1 = cli.Get(path);
  20509. ASSERT_TRUE(r1);
  20510. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20511. // Stream path
  20512. auto h = cli.open_stream("GET", path);
  20513. ASSERT_TRUE(h.is_valid());
  20514. EXPECT_EQ(r1->body, read_all(h));
  20515. }
  20516. // Helper to compress data with provided compressor type T
  20517. template <typename Compressor>
  20518. static std::string compress_payload_for_parity(const std::string &in) {
  20519. std::string out;
  20520. Compressor compressor;
  20521. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20522. [&](const char *data, size_t n) {
  20523. out.append(data, n);
  20524. return true;
  20525. });
  20526. EXPECT_TRUE(ok);
  20527. return out;
  20528. }
  20529. // Helper function for compression parity tests
  20530. template <typename Compressor>
  20531. static void test_compression_parity(const std::string &original,
  20532. const std::string &path,
  20533. const std::string &encoding) {
  20534. const std::string compressed =
  20535. compress_payload_for_parity<Compressor>(original);
  20536. Server svr;
  20537. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20538. res.set_content(compressed, "application/octet-stream");
  20539. res.set_header("Content-Encoding", encoding);
  20540. });
  20541. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20542. auto se = detail::scope_exit([&] {
  20543. svr.stop();
  20544. t.join();
  20545. ASSERT_FALSE(svr.is_running());
  20546. });
  20547. svr.wait_until_ready();
  20548. Client cli(HOST, PORT);
  20549. // Non-streaming
  20550. {
  20551. auto res = cli.Get(path);
  20552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20553. EXPECT_EQ(StatusCode::OK_200, res->status);
  20554. EXPECT_EQ(original, res->body);
  20555. }
  20556. // Streaming
  20557. {
  20558. auto h = cli.open_stream("GET", path);
  20559. ASSERT_TRUE(h.is_valid());
  20560. EXPECT_EQ(original, read_all(h));
  20561. }
  20562. }
  20563. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20564. TEST(ParityTest, Gzip) {
  20565. test_compression_parity<detail::gzip_compressor>(
  20566. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20567. }
  20568. #endif
  20569. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20570. TEST(ParityTest, Brotli) {
  20571. test_compression_parity<detail::brotli_compressor>(
  20572. "Hello, brotli parity test payload", "/parity-br", "br");
  20573. }
  20574. #endif
  20575. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20576. TEST(ParityTest, Zstd) {
  20577. test_compression_parity<detail::zstd_compressor>(
  20578. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20579. }
  20580. #endif
  20581. //==============================================================================
  20582. // New Stream API Tests
  20583. //==============================================================================
  20584. inline std::string read_body(httplib::stream::Result &result) {
  20585. std::string body;
  20586. while (result.next()) {
  20587. body.append(result.data(), result.size());
  20588. }
  20589. return body;
  20590. }
  20591. TEST(ClientConnectionTest, Basic) {
  20592. httplib::ClientConnection conn;
  20593. EXPECT_FALSE(conn.is_open());
  20594. conn.sock = 1;
  20595. EXPECT_TRUE(conn.is_open());
  20596. httplib::ClientConnection conn2(std::move(conn));
  20597. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20598. conn2.sock = INVALID_SOCKET;
  20599. }
  20600. // Unified test server for all stream::* tests
  20601. class StreamApiTest : public ::testing::Test {
  20602. protected:
  20603. void SetUp() override {
  20604. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20605. res.set_content("Hello World!", "text/plain");
  20606. });
  20607. svr_.Get("/echo-params",
  20608. [](const httplib::Request &req, httplib::Response &res) {
  20609. std::string r;
  20610. for (const auto &p : req.params) {
  20611. if (!r.empty()) r += "&";
  20612. r += p.first + "=" + p.second;
  20613. }
  20614. res.set_content(r, "text/plain");
  20615. });
  20616. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20617. res.set_content(req.body, req.get_header_value("Content-Type"));
  20618. });
  20619. svr_.Post("/echo-headers",
  20620. [](const httplib::Request &req, httplib::Response &res) {
  20621. std::string r;
  20622. for (const auto &h : req.headers)
  20623. r += h.first + ": " + h.second + "\n";
  20624. res.set_content(r, "text/plain");
  20625. });
  20626. svr_.Post("/echo-params",
  20627. [](const httplib::Request &req, httplib::Response &res) {
  20628. std::string r = "params:";
  20629. for (const auto &p : req.params)
  20630. r += p.first + "=" + p.second + ";";
  20631. res.set_content(r + " body:" + req.body, "text/plain");
  20632. });
  20633. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20634. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20635. });
  20636. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20637. res.set_content("PUT:" + req.body, "text/plain");
  20638. });
  20639. svr_.Patch("/echo",
  20640. [](const httplib::Request &req, httplib::Response &res) {
  20641. res.set_content("PATCH:" + req.body, "text/plain");
  20642. });
  20643. svr_.Delete(
  20644. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20645. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20646. "text/plain");
  20647. });
  20648. svr_.Get("/head-test",
  20649. [](const httplib::Request &, httplib::Response &res) {
  20650. res.set_content("body for HEAD", "text/plain");
  20651. });
  20652. svr_.Options("/options",
  20653. [](const httplib::Request &, httplib::Response &res) {
  20654. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20655. });
  20656. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20657. svr_.wait_until_ready();
  20658. }
  20659. void TearDown() override {
  20660. svr_.stop();
  20661. if (thread_.joinable()) thread_.join();
  20662. }
  20663. httplib::Server svr_;
  20664. std::thread thread_;
  20665. };
  20666. // stream::Get tests
  20667. TEST_F(StreamApiTest, GetBasic) {
  20668. httplib::Client cli(HOST, PORT);
  20669. auto result = httplib::stream::Get(cli, "/hello");
  20670. ASSERT_TRUE(result.is_valid());
  20671. EXPECT_EQ(200, result.status());
  20672. EXPECT_EQ("Hello World!", read_body(result));
  20673. }
  20674. TEST_F(StreamApiTest, GetWithParams) {
  20675. httplib::Client cli(HOST, PORT);
  20676. httplib::Params params{{"foo", "bar"}};
  20677. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20678. ASSERT_TRUE(result.is_valid());
  20679. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20680. }
  20681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20682. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20683. httplib::Client cli(HOST, PORT);
  20684. cli.set_payload_max_length(0);
  20685. auto result = httplib::stream::Get(cli, "/hello");
  20686. ASSERT_TRUE(result.is_valid());
  20687. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20688. EXPECT_EQ("Hello World!", read_body(result));
  20689. }
  20690. #endif
  20691. TEST_F(StreamApiTest, GetConnectionError) {
  20692. httplib::Client cli(HOST, 9999);
  20693. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20694. }
  20695. TEST_F(StreamApiTest, Get404) {
  20696. httplib::Client cli(HOST, PORT);
  20697. auto result = httplib::stream::Get(cli, "/nonexistent");
  20698. EXPECT_TRUE(result.is_valid());
  20699. EXPECT_EQ(404, result.status());
  20700. }
  20701. // stream::Post tests
  20702. TEST_F(StreamApiTest, PostBasic) {
  20703. httplib::Client cli(HOST, PORT);
  20704. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20705. "application/json");
  20706. ASSERT_TRUE(result.is_valid());
  20707. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20708. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20709. }
  20710. TEST_F(StreamApiTest, PostWithHeaders) {
  20711. httplib::Client cli(HOST, PORT);
  20712. httplib::Headers headers{{"X-Custom", "value"}};
  20713. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20714. "text/plain");
  20715. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20716. }
  20717. TEST_F(StreamApiTest, PostWithParams) {
  20718. httplib::Client cli(HOST, PORT);
  20719. httplib::Params params{{"k", "v"}};
  20720. auto result =
  20721. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20722. auto body = read_body(result);
  20723. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20724. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20725. }
  20726. TEST_F(StreamApiTest, PostLarge) {
  20727. httplib::Client cli(HOST, PORT);
  20728. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20729. size_t total = 0;
  20730. while (result.next()) {
  20731. total += result.size();
  20732. }
  20733. EXPECT_EQ(100u * 1024u, total);
  20734. }
  20735. // stream::Put/Patch tests
  20736. TEST_F(StreamApiTest, PutAndPatch) {
  20737. httplib::Client cli(HOST, PORT);
  20738. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20739. EXPECT_EQ("PUT:test", read_body(put));
  20740. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20741. EXPECT_EQ("PATCH:test", read_body(patch));
  20742. }
  20743. // stream::Delete tests
  20744. TEST_F(StreamApiTest, Delete) {
  20745. httplib::Client cli(HOST, PORT);
  20746. auto del1 = httplib::stream::Delete(cli, "/resource");
  20747. EXPECT_EQ("Deleted", read_body(del1));
  20748. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20749. EXPECT_EQ("Deleted:data", read_body(del2));
  20750. }
  20751. // stream::Head/Options tests
  20752. TEST_F(StreamApiTest, HeadAndOptions) {
  20753. httplib::Client cli(HOST, PORT);
  20754. auto head = httplib::stream::Head(cli, "/head-test");
  20755. EXPECT_TRUE(head.is_valid());
  20756. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20757. auto opts = httplib::stream::Options(cli, "/options");
  20758. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20759. }
  20760. // SSL stream::* tests
  20761. #ifdef CPPHTTPLIB_SSL_ENABLED
  20762. class SSLStreamApiTest : public ::testing::Test {
  20763. protected:
  20764. void SetUp() override {
  20765. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20766. res.set_content("Hello SSL!", "text/plain");
  20767. });
  20768. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20769. res.set_content(req.body, "text/plain");
  20770. });
  20771. port_ = svr_.bind_to_any_port("127.0.0.1");
  20772. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20773. svr_.wait_until_ready();
  20774. }
  20775. void TearDown() override {
  20776. svr_.stop();
  20777. if (thread_.joinable()) thread_.join();
  20778. }
  20779. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20780. std::thread thread_;
  20781. int port_ = 0;
  20782. };
  20783. TEST_F(SSLStreamApiTest, GetAndPost) {
  20784. httplib::SSLClient cli("127.0.0.1", port_);
  20785. cli.enable_server_certificate_verification(false);
  20786. auto get = httplib::stream::Get(cli, "/hello");
  20787. EXPECT_EQ("Hello SSL!", read_body(get));
  20788. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20789. EXPECT_EQ("test", read_body(post));
  20790. }
  20791. #endif
  20792. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20793. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20794. // BodyReader
  20795. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20796. // Test that read timeout during streaming is detected
  20797. // Use a large content-length response where server delays mid-stream
  20798. Server svr;
  20799. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20800. // Send a large response with delay in the middle
  20801. res.set_content_provider(
  20802. 1000, // content_length
  20803. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20804. if (offset < 100) {
  20805. // Send first 100 bytes immediately
  20806. std::string data(100, 'A');
  20807. sink.write(data.c_str(), data.size());
  20808. return true;
  20809. }
  20810. // Then delay longer than client timeout
  20811. std::this_thread::sleep_for(std::chrono::seconds(3));
  20812. std::string data(900, 'B');
  20813. sink.write(data.c_str(), data.size());
  20814. return true;
  20815. });
  20816. });
  20817. auto port = 8091;
  20818. std::thread t([&]() { svr.listen("localhost", port); });
  20819. svr.wait_until_ready();
  20820. Client cli("localhost", port);
  20821. cli.set_read_timeout(1, 0); // 1 second timeout
  20822. auto handle = cli.open_stream("GET", "/slow-stream");
  20823. ASSERT_TRUE(handle.is_valid());
  20824. char buf[256];
  20825. ssize_t total = 0;
  20826. ssize_t n;
  20827. bool got_error = false;
  20828. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20829. total += n;
  20830. }
  20831. if (n < 0) {
  20832. got_error = true;
  20833. // Should be timeout or read error
  20834. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20835. handle.get_read_error() == Error::Read)
  20836. << "Actual error: " << to_string(handle.get_read_error());
  20837. }
  20838. // Either we got an error, or we got less data than expected
  20839. EXPECT_TRUE(got_error || total < 1000)
  20840. << "Expected timeout but got all " << total << " bytes";
  20841. svr.stop();
  20842. t.join();
  20843. }
  20844. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20845. // Test connection closed detection via BodyReader
  20846. Server svr;
  20847. std::atomic<bool> close_now{false};
  20848. svr.Get("/will-close", [&](const Request &, Response &res) {
  20849. res.set_content_provider(
  20850. 10000, // Large content_length that we won't fully send
  20851. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20852. if (offset < 100) {
  20853. std::string data(100, 'X');
  20854. sink.write(data.c_str(), data.size());
  20855. return true;
  20856. }
  20857. // Wait for signal then abort
  20858. while (!close_now) {
  20859. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20860. }
  20861. return false; // Abort - server will close connection
  20862. });
  20863. });
  20864. auto port = 8092;
  20865. std::thread t([&]() { svr.listen("localhost", port); });
  20866. svr.wait_until_ready();
  20867. Client cli("localhost", port);
  20868. auto handle = cli.open_stream("GET", "/will-close");
  20869. ASSERT_TRUE(handle.is_valid());
  20870. char buf[256];
  20871. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20872. EXPECT_GT(n, 0) << "First read should succeed";
  20873. // Signal server to close
  20874. close_now = true;
  20875. // Keep reading until error or EOF
  20876. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20877. // Keep reading
  20878. }
  20879. // Should get an error since content_length wasn't satisfied
  20880. if (n < 0) {
  20881. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20882. handle.get_read_error() == Error::Read)
  20883. << "Actual error: " << to_string(handle.get_read_error());
  20884. }
  20885. svr.stop();
  20886. t.join();
  20887. }
  20888. #ifdef CPPHTTPLIB_SSL_ENABLED
  20889. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20890. // Test that read timeout during SSL streaming is detected
  20891. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20892. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20893. res.set_content_provider(
  20894. 1000, "text/plain",
  20895. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20896. if (offset < 100) {
  20897. std::string data(100, 'A');
  20898. sink.write(data.c_str(), data.size());
  20899. return true;
  20900. }
  20901. std::this_thread::sleep_for(std::chrono::seconds(3));
  20902. std::string data(900, 'B');
  20903. sink.write(data.c_str(), data.size());
  20904. return true;
  20905. });
  20906. });
  20907. auto port = 8093;
  20908. std::thread t([&]() { svr.listen("localhost", port); });
  20909. svr.wait_until_ready();
  20910. SSLClient cli("localhost", port);
  20911. cli.enable_server_certificate_verification(false);
  20912. cli.set_read_timeout(1, 0); // 1 second timeout
  20913. auto handle = cli.open_stream("GET", "/slow-stream");
  20914. ASSERT_TRUE(handle.is_valid());
  20915. char buf[256];
  20916. ssize_t total = 0;
  20917. ssize_t n;
  20918. bool got_error = false;
  20919. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20920. total += n;
  20921. }
  20922. if (n < 0) {
  20923. got_error = true;
  20924. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20925. handle.get_read_error() == Error::Read)
  20926. << "Actual error: " << to_string(handle.get_read_error());
  20927. }
  20928. EXPECT_TRUE(got_error || total < 1000)
  20929. << "Expected timeout but got all " << total << " bytes";
  20930. svr.stop();
  20931. t.join();
  20932. }
  20933. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20934. // Test SSL connection closed detection
  20935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20936. std::atomic<bool> close_now{false};
  20937. svr.Get("/will-close", [&](const Request &, Response &res) {
  20938. res.set_content_provider(
  20939. 10000, "text/plain",
  20940. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20941. if (offset < 100) {
  20942. std::string data(100, 'X');
  20943. sink.write(data.c_str(), data.size());
  20944. return true;
  20945. }
  20946. while (!close_now) {
  20947. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20948. }
  20949. return false;
  20950. });
  20951. });
  20952. auto port = 8094;
  20953. std::thread t([&]() { svr.listen("localhost", port); });
  20954. svr.wait_until_ready();
  20955. SSLClient cli("localhost", port);
  20956. cli.enable_server_certificate_verification(false);
  20957. auto handle = cli.open_stream("GET", "/will-close");
  20958. ASSERT_TRUE(handle.is_valid());
  20959. char buf[256];
  20960. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20961. EXPECT_GT(n, 0);
  20962. // Signal server to close
  20963. close_now = true;
  20964. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20965. // Keep reading
  20966. }
  20967. if (n < 0) {
  20968. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20969. handle.get_read_error() == Error::Read)
  20970. << "Actual error: " << to_string(handle.get_read_error());
  20971. }
  20972. svr.stop();
  20973. t.join();
  20974. }
  20975. #endif
  20976. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20977. using namespace httplib;
  20978. // Create a test file
  20979. const char *fname = "etag_testfile.txt";
  20980. const char *content = "etag-content";
  20981. {
  20982. std::ofstream ofs(fname);
  20983. ofs << content;
  20984. ASSERT_TRUE(ofs.good());
  20985. }
  20986. Server svr;
  20987. svr.set_mount_point("/static", ".");
  20988. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20989. svr.wait_until_ready();
  20990. Client cli(HOST, PORT);
  20991. // First request: should get 200 with ETag header
  20992. auto res1 = cli.Get("/static/etag_testfile.txt");
  20993. ASSERT_TRUE(res1);
  20994. ASSERT_EQ(200, res1->status);
  20995. ASSERT_TRUE(res1->has_header("ETag"));
  20996. std::string etag = res1->get_header_value("ETag");
  20997. EXPECT_FALSE(etag.empty());
  20998. // Verify ETag format: W/"hex-hex"
  20999. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21000. EXPECT_EQ('W', etag[0]);
  21001. EXPECT_EQ('/', etag[1]);
  21002. EXPECT_EQ('"', etag[2]);
  21003. EXPECT_EQ('"', etag.back());
  21004. // Exact match: expect 304 Not Modified
  21005. Headers h2 = {{"If-None-Match", etag}};
  21006. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21007. ASSERT_TRUE(res2);
  21008. EXPECT_EQ(304, res2->status);
  21009. // Wildcard match: expect 304 Not Modified
  21010. Headers h3 = {{"If-None-Match", "*"}};
  21011. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21012. ASSERT_TRUE(res3);
  21013. EXPECT_EQ(304, res3->status);
  21014. // Non-matching ETag: expect 200
  21015. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21016. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21017. ASSERT_TRUE(res4);
  21018. EXPECT_EQ(200, res4->status);
  21019. // Multiple ETags with one matching: expect 304
  21020. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21021. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21022. ASSERT_TRUE(res5);
  21023. EXPECT_EQ(304, res5->status);
  21024. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21025. // that equivalent to the single comma-separated list above, so the match on
  21026. // the second line must still be found.
  21027. Headers h6;
  21028. h6.emplace("If-None-Match", "W/\"other\"");
  21029. h6.emplace("If-None-Match", etag);
  21030. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21031. ASSERT_TRUE(res6);
  21032. EXPECT_EQ(304, res6->status);
  21033. svr.stop();
  21034. t.join();
  21035. std::remove(fname);
  21036. }
  21037. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21038. using namespace httplib;
  21039. Server svr;
  21040. svr.set_mount_point("/static", ".");
  21041. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21042. svr.wait_until_ready();
  21043. Client cli(HOST, PORT);
  21044. // Send If-None-Match: * to a non-existent file
  21045. Headers h = {{"If-None-Match", "*"}};
  21046. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21048. EXPECT_EQ(404, res->status);
  21049. svr.stop();
  21050. t.join();
  21051. }
  21052. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21053. using namespace httplib;
  21054. // Create a test file
  21055. const char *fname = "etag_boundary_testfile.txt";
  21056. const char *content = "boundary-test";
  21057. {
  21058. std::ofstream ofs(fname);
  21059. ofs << content;
  21060. ASSERT_TRUE(ofs.good());
  21061. }
  21062. Server svr;
  21063. svr.set_mount_point("/static", ".");
  21064. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21065. svr.wait_until_ready();
  21066. Client cli(HOST, PORT);
  21067. // Get the actual ETag
  21068. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21069. ASSERT_TRUE(res1);
  21070. ASSERT_EQ(200, res1->status);
  21071. ASSERT_TRUE(res1->has_header("ETag"));
  21072. std::string etag = res1->get_header_value("ETag");
  21073. // Test 1: Very long ETag value (longer than actual ETag)
  21074. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21075. Headers h1 = {{"If-None-Match", "W/"
  21076. "\"very-long-etag-value-that-is-much-longer-"
  21077. "than-the-actual-etag-value\""}};
  21078. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21079. ASSERT_TRUE(res2);
  21080. EXPECT_EQ(200, res2->status); // Should not match
  21081. // Test 2: Long string followed by wildcard
  21082. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21083. // string)
  21084. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21085. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21086. ASSERT_TRUE(res3);
  21087. EXPECT_EQ(304, res3->status); // Should match on "*"
  21088. // Test 3: Wildcard followed by long string
  21089. // Should match on "*" immediately and return 304
  21090. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21091. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21092. ASSERT_TRUE(res4);
  21093. EXPECT_EQ(304, res4->status); // Should match on "*"
  21094. // Test 4: Multiple long non-matching values
  21095. // Should NOT match and return 200 (test that all comparisons are safe)
  21096. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21097. "W/\"second-long-non-matching-value\", "
  21098. "W/\"third-long-non-matching-value\""}};
  21099. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21100. ASSERT_TRUE(res5);
  21101. EXPECT_EQ(200, res5->status); // Should not match
  21102. // Test 5: Single character that is not "*" (edge case)
  21103. Headers h5 = {{"If-None-Match", "X"}};
  21104. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21105. ASSERT_TRUE(res6);
  21106. EXPECT_EQ(200, res6->status); // Should not match
  21107. svr.stop();
  21108. t.join();
  21109. std::remove(fname);
  21110. }
  21111. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21112. using namespace httplib;
  21113. // Create a test file
  21114. const char *fname = "ims_testfile.txt";
  21115. const char *content = "if-modified-since-test";
  21116. {
  21117. std::ofstream ofs(fname);
  21118. ofs << content;
  21119. ASSERT_TRUE(ofs.good());
  21120. }
  21121. Server svr;
  21122. svr.set_mount_point("/static", ".");
  21123. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21124. svr.wait_until_ready();
  21125. Client cli(HOST, PORT);
  21126. // First request: should get 200 with Last-Modified header
  21127. auto res1 = cli.Get("/static/ims_testfile.txt");
  21128. ASSERT_TRUE(res1);
  21129. ASSERT_EQ(200, res1->status);
  21130. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21131. std::string last_modified = res1->get_header_value("Last-Modified");
  21132. EXPECT_FALSE(last_modified.empty());
  21133. // If-Modified-Since with same time: expect 304
  21134. Headers h2 = {{"If-Modified-Since", last_modified}};
  21135. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21136. ASSERT_TRUE(res2);
  21137. EXPECT_EQ(304, res2->status);
  21138. // If-Modified-Since with future time: expect 304
  21139. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21140. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21141. ASSERT_TRUE(res3);
  21142. EXPECT_EQ(304, res3->status);
  21143. // If-Modified-Since with past time: expect 200
  21144. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21145. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21146. ASSERT_TRUE(res4);
  21147. EXPECT_EQ(200, res4->status);
  21148. // If-None-Match takes precedence over If-Modified-Since
  21149. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21150. ASSERT_TRUE(res1->has_header("ETag"));
  21151. std::string etag = res1->get_header_value("ETag");
  21152. Headers h5 = {{"If-None-Match", etag},
  21153. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21154. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21155. ASSERT_TRUE(res5);
  21156. EXPECT_EQ(304, res5->status);
  21157. svr.stop();
  21158. t.join();
  21159. std::remove(fname);
  21160. }
  21161. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21162. using namespace httplib;
  21163. Server svr;
  21164. // Endpoint that returns compressible content
  21165. svr.Get("/compressible", [](const Request &, Response &res) {
  21166. // Return a large enough body to trigger compression
  21167. std::string body(1000, 'a');
  21168. res.set_content(body, "text/plain");
  21169. });
  21170. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21171. svr.wait_until_ready();
  21172. Client cli(HOST, PORT);
  21173. // Request with gzip support: should get Vary header when compressed
  21174. cli.set_compress(true);
  21175. auto res1 = cli.Get("/compressible");
  21176. ASSERT_TRUE(res1);
  21177. EXPECT_EQ(200, res1->status);
  21178. // If Content-Encoding is set, Vary should also be set
  21179. if (res1->has_header("Content-Encoding")) {
  21180. EXPECT_TRUE(res1->has_header("Vary"));
  21181. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21182. }
  21183. // Request without Accept-Encoding header: should not have compression
  21184. Headers h_no_compress;
  21185. auto res2 = cli.Get("/compressible", h_no_compress);
  21186. ASSERT_TRUE(res2);
  21187. EXPECT_EQ(200, res2->status);
  21188. // Verify Vary header is present when compression is applied
  21189. // (the exact behavior depends on server configuration)
  21190. svr.stop();
  21191. t.join();
  21192. }
  21193. TEST(ETagTest, IfRangeWithETag) {
  21194. using namespace httplib;
  21195. // Create a test file with known content
  21196. const char *fname = "if_range_testfile.txt";
  21197. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21198. {
  21199. std::ofstream ofs(fname);
  21200. ofs << content;
  21201. ASSERT_TRUE(ofs.good());
  21202. }
  21203. Server svr;
  21204. svr.set_mount_point("/static", ".");
  21205. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21206. svr.wait_until_ready();
  21207. Client cli(HOST, PORT);
  21208. // First request: get ETag
  21209. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21210. ASSERT_TRUE(res1);
  21211. ASSERT_EQ(200, res1->status);
  21212. ASSERT_TRUE(res1->has_header("ETag"));
  21213. std::string etag = res1->get_header_value("ETag");
  21214. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21215. // Since our server generates weak ETags (W/"..."), If-Range with our
  21216. // ETag should NOT result in partial content - it should return full content.
  21217. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21218. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21219. ASSERT_TRUE(res2);
  21220. // Weak ETag in If-Range -> full content (200), not partial (206)
  21221. EXPECT_EQ(200, res2->status);
  21222. EXPECT_EQ(content, res2->body);
  21223. EXPECT_FALSE(res2->has_header("Content-Range"));
  21224. // Range request with non-matching If-Range (ETag): should get 200 (full
  21225. // content)
  21226. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21227. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21228. ASSERT_TRUE(res3);
  21229. EXPECT_EQ(200, res3->status);
  21230. EXPECT_EQ(content, res3->body);
  21231. EXPECT_FALSE(res3->has_header("Content-Range"));
  21232. // Range request with strong ETag (hypothetical - our server doesn't generate
  21233. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21234. // should return full content)
  21235. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21236. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21237. ASSERT_TRUE(res4);
  21238. EXPECT_EQ(200, res4->status);
  21239. EXPECT_EQ(content, res4->body);
  21240. EXPECT_FALSE(res4->has_header("Content-Range"));
  21241. svr.stop();
  21242. t.join();
  21243. std::remove(fname);
  21244. }
  21245. TEST(ETagTest, IfRangeWithDate) {
  21246. using namespace httplib;
  21247. // Create a test file
  21248. const char *fname = "if_range_date_testfile.txt";
  21249. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21250. {
  21251. std::ofstream ofs(fname);
  21252. ofs << content;
  21253. ASSERT_TRUE(ofs.good());
  21254. }
  21255. Server svr;
  21256. svr.set_mount_point("/static", ".");
  21257. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21258. svr.wait_until_ready();
  21259. Client cli(HOST, PORT);
  21260. // First request: get Last-Modified
  21261. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21262. ASSERT_TRUE(res1);
  21263. ASSERT_EQ(200, res1->status);
  21264. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21265. std::string last_modified = res1->get_header_value("Last-Modified");
  21266. // Range request with matching If-Range (date): should get 206
  21267. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21268. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21269. ASSERT_TRUE(res2);
  21270. EXPECT_EQ(206, res2->status);
  21271. EXPECT_EQ("FGHIJ", res2->body);
  21272. // Range request with old If-Range date: should get 200 (full content)
  21273. Headers h3 = {{"Range", "bytes=5-9"},
  21274. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21275. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21276. ASSERT_TRUE(res3);
  21277. EXPECT_EQ(200, res3->status);
  21278. EXPECT_EQ(content, res3->body);
  21279. // Range request with future If-Range date: should get 206
  21280. Headers h4 = {{"Range", "bytes=0-4"},
  21281. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21282. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21283. ASSERT_TRUE(res4);
  21284. EXPECT_EQ(206, res4->status);
  21285. EXPECT_EQ("ABCDE", res4->body);
  21286. svr.stop();
  21287. t.join();
  21288. std::remove(fname);
  21289. }
  21290. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21291. using namespace httplib;
  21292. const char *fname = "etag_malformed.txt";
  21293. const char *content = "malformed-etag";
  21294. {
  21295. std::ofstream ofs(fname);
  21296. ofs << content;
  21297. ASSERT_TRUE(ofs.good());
  21298. }
  21299. Server svr;
  21300. svr.set_mount_point("/static", ".");
  21301. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21302. svr.wait_until_ready();
  21303. Client cli(HOST, PORT);
  21304. // baseline: should get 200 and an ETag
  21305. auto res1 = cli.Get("/static/etag_malformed.txt");
  21306. ASSERT_TRUE(res1);
  21307. ASSERT_EQ(200, res1->status);
  21308. ASSERT_TRUE(res1->has_header("ETag"));
  21309. // Malformed ETag value (missing quotes) should be treated as non-matching
  21310. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21311. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21312. ASSERT_TRUE(res_bad);
  21313. EXPECT_EQ(200, res_bad->status);
  21314. // Whitespace-only header value should be considered invalid / non-matching
  21315. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21316. "Host: localhost\r\n"
  21317. "If-None-Match: \r\n"
  21318. "Connection: close\r\n"
  21319. "\r\n";
  21320. std::string out;
  21321. ASSERT_TRUE(send_request(5, raw_req, &out));
  21322. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21323. svr.stop();
  21324. t.join();
  21325. std::remove(fname);
  21326. }
  21327. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21328. using namespace httplib;
  21329. const char *fname = "ims_invalid_format.txt";
  21330. const char *content = "ims-bad-format";
  21331. {
  21332. std::ofstream ofs(fname);
  21333. ofs << content;
  21334. ASSERT_TRUE(ofs.good());
  21335. }
  21336. Server svr;
  21337. svr.set_mount_point("/static", ".");
  21338. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21339. svr.wait_until_ready();
  21340. Client cli(HOST, PORT);
  21341. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21342. ASSERT_TRUE(res1);
  21343. ASSERT_EQ(200, res1->status);
  21344. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21345. // If-Modified-Since with invalid format should not result in 304
  21346. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21347. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21348. ASSERT_TRUE(res_bad);
  21349. EXPECT_EQ(200, res_bad->status);
  21350. // If-Range with invalid date format should be treated as mismatch -> full
  21351. // content (200)
  21352. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21353. {"If-Range", "invalid-date"}};
  21354. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21355. ASSERT_TRUE(res_ifrange);
  21356. EXPECT_EQ(200, res_ifrange->status);
  21357. svr.stop();
  21358. t.join();
  21359. std::remove(fname);
  21360. }
  21361. TEST(ETagTest, IfRangeWithMalformedETag) {
  21362. using namespace httplib;
  21363. const char *fname = "ifrange_malformed.txt";
  21364. const std::string content = "0123456789";
  21365. {
  21366. std::ofstream ofs(fname);
  21367. ofs << content;
  21368. ASSERT_TRUE(ofs.good());
  21369. }
  21370. Server svr;
  21371. svr.set_mount_point("/static", ".");
  21372. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21373. svr.wait_until_ready();
  21374. Client cli(HOST, PORT);
  21375. // First request: get ETag
  21376. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21377. ASSERT_TRUE(res1);
  21378. ASSERT_EQ(200, res1->status);
  21379. ASSERT_TRUE(res1->has_header("ETag"));
  21380. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21381. // full content (200)
  21382. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21383. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21384. ASSERT_TRUE(res2);
  21385. EXPECT_EQ(200, res2->status);
  21386. EXPECT_EQ(content, res2->body);
  21387. svr.stop();
  21388. t.join();
  21389. std::remove(fname);
  21390. }
  21391. TEST(ETagTest, ExtremeLargeDateValues) {
  21392. using namespace httplib;
  21393. const char *fname = "ims_extreme_date.txt";
  21394. const char *content = "ims-extreme-date";
  21395. {
  21396. std::ofstream ofs(fname);
  21397. ofs << content;
  21398. ASSERT_TRUE(ofs.good());
  21399. }
  21400. Server svr;
  21401. svr.set_mount_point("/static", ".");
  21402. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21403. svr.wait_until_ready();
  21404. Client cli(HOST, PORT);
  21405. auto res1 = cli.Get(std::string("/static/") + fname);
  21406. ASSERT_TRUE(res1);
  21407. ASSERT_EQ(200, res1->status);
  21408. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21409. // Extremely large year that may overflow date parsing routines.
  21410. Headers h_large_date = {
  21411. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21412. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21413. ASSERT_TRUE(res_bad);
  21414. // Expect server to treat this as invalid/mismatch and return full content
  21415. EXPECT_EQ(200, res_bad->status);
  21416. // If-Range with extremely large date should be treated as mismatch -> full
  21417. // content (200)
  21418. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21419. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21420. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21421. ASSERT_TRUE(res_ifrange);
  21422. EXPECT_EQ(200, res_ifrange->status);
  21423. svr.stop();
  21424. t.join();
  21425. std::remove(fname);
  21426. }
  21427. TEST(ETagTest, NegativeFileModificationTime) {
  21428. using namespace httplib;
  21429. const char *fname = "ims_negative_mtime.txt";
  21430. const std::string content = "negative-mtime";
  21431. {
  21432. std::ofstream ofs(fname);
  21433. ofs << content;
  21434. ASSERT_TRUE(ofs.good());
  21435. }
  21436. // Try to set file mtime to a negative value. This may fail on some
  21437. // platforms/filesystems; if it fails, the test will still verify server
  21438. // behaves safely by performing a regular conditional request.
  21439. #if defined(__APPLE__) || defined(__linux__)
  21440. bool set_negative = false;
  21441. do {
  21442. struct timeval times[2];
  21443. // access time: now
  21444. times[0].tv_sec = time(nullptr);
  21445. times[0].tv_usec = 0;
  21446. // modification time: negative (e.g., -1)
  21447. times[1].tv_sec = -1;
  21448. times[1].tv_usec = 0;
  21449. if (utimes(fname, times) == 0) { set_negative = true; }
  21450. } while (0);
  21451. #else
  21452. bool set_negative = false;
  21453. #endif
  21454. Server svr;
  21455. svr.set_mount_point("/static", ".");
  21456. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21457. svr.wait_until_ready();
  21458. Client cli(HOST, PORT);
  21459. auto res1 = cli.Get(std::string("/static/") + fname);
  21460. ASSERT_TRUE(res1);
  21461. ASSERT_EQ(200, res1->status);
  21462. bool has_last_modified = res1->has_header("Last-Modified");
  21463. std::string last_modified;
  21464. if (has_last_modified) {
  21465. last_modified = res1->get_header_value("Last-Modified");
  21466. }
  21467. if (set_negative) {
  21468. // If we successfully set a negative mtime, ensure server returns a
  21469. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21470. // with an old date and ensure server handles it without crash.
  21471. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21472. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21473. ASSERT_TRUE(res2);
  21474. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21475. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21476. } else {
  21477. // Could not set negative mtime on this platform; fall back to verifying
  21478. // that normal invalid/malformed dates are treated safely (non-304).
  21479. Headers h_bad_date = {
  21480. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21481. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21482. ASSERT_TRUE(res_bad);
  21483. EXPECT_EQ(200, res_bad->status);
  21484. }
  21485. svr.stop();
  21486. t.join();
  21487. std::remove(fname);
  21488. }
  21489. //==============================================================================
  21490. // Integration Tests with Server
  21491. //==============================================================================
  21492. class SSEIntegrationTest : public ::testing::Test {
  21493. protected:
  21494. void SetUp() override {
  21495. stop_server_.store(false);
  21496. events_.clear();
  21497. server_ = httplib::detail::make_unique<Server>();
  21498. setup_server();
  21499. start_server();
  21500. }
  21501. void TearDown() override {
  21502. stop_server_.store(true);
  21503. event_cv_.notify_all();
  21504. server_->stop();
  21505. if (server_thread_.joinable()) { server_thread_.join(); }
  21506. }
  21507. void setup_server() {
  21508. // Simple SSE endpoint
  21509. server_->Get("/events", [this](const Request &req, Response &res) {
  21510. auto last_id = req.get_header_value("Last-Event-ID");
  21511. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21512. res.set_chunked_content_provider(
  21513. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21514. std::unique_lock<std::mutex> lock(event_mutex_);
  21515. if (event_cv_.wait_for(
  21516. lock, std::chrono::milliseconds(200), [this] {
  21517. return !events_.empty() || stop_server_.load();
  21518. })) {
  21519. if (stop_server_.load()) { return false; }
  21520. if (!events_.empty()) {
  21521. std::string event = events_.front();
  21522. events_.erase(events_.begin());
  21523. sink.write(event.data(), event.size());
  21524. return true;
  21525. }
  21526. }
  21527. return !stop_server_.load();
  21528. });
  21529. });
  21530. // Endpoint that returns error
  21531. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21532. res.status = 500;
  21533. res.set_content("Internal Server Error", "text/plain");
  21534. });
  21535. // Endpoint for custom event types
  21536. server_->Get("/custom-events", [](const Request &, Response &res) {
  21537. res.set_chunked_content_provider(
  21538. "text/event-stream", [](size_t offset, DataSink &sink) {
  21539. if (offset == 0) {
  21540. std::string event = "event: update\ndata: updated\n\n"
  21541. "event: delete\ndata: deleted\n\n";
  21542. sink.write(event.data(), event.size());
  21543. }
  21544. return false; // End stream after sending
  21545. });
  21546. });
  21547. }
  21548. void start_server() {
  21549. port_ = server_->bind_to_any_port(HOST);
  21550. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21551. // Wait for server to start
  21552. while (!server_->is_running()) {
  21553. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21554. }
  21555. }
  21556. int get_port() const { return port_; }
  21557. void send_event(const std::string &event) {
  21558. std::lock_guard<std::mutex> lock(event_mutex_);
  21559. events_.push_back(event);
  21560. event_cv_.notify_all();
  21561. }
  21562. std::unique_ptr<Server> server_;
  21563. std::thread server_thread_;
  21564. std::mutex event_mutex_;
  21565. std::condition_variable event_cv_;
  21566. std::vector<std::string> events_;
  21567. std::atomic<bool> stop_server_{false};
  21568. std::string last_received_event_id_;
  21569. int port_ = 0;
  21570. };
  21571. //==============================================================================
  21572. // SSE Parsing Tests
  21573. //==============================================================================
  21574. class SSEParsingTest : public SSEIntegrationTest {
  21575. protected:
  21576. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21577. // A trailing sentinel event tells when the whole stream has been parsed.
  21578. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21579. auto body = stream + "event: end\ndata: end\n\n";
  21580. server_->Get("/parse", [body](const Request &, Response &res) {
  21581. res.set_content(body, "text/event-stream");
  21582. });
  21583. return collect("/parse");
  21584. }
  21585. // Runs SSEClient against path until an "end" event arrives and returns the
  21586. // messages dispatched before it
  21587. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21588. Client client(HOST, get_port());
  21589. sse::SSEClient sse(client, path);
  21590. std::mutex mutex;
  21591. std::condition_variable cv;
  21592. std::vector<sse::SSEMessage> messages;
  21593. auto done = false;
  21594. sse.on_message([&](const sse::SSEMessage &msg) {
  21595. std::lock_guard<std::mutex> lock(mutex);
  21596. // Ignore a replay from a reconnect that races with stop()
  21597. if (!done) { messages.push_back(msg); }
  21598. });
  21599. sse.on_event("end", [&](const sse::SSEMessage &) {
  21600. std::lock_guard<std::mutex> lock(mutex);
  21601. done = true;
  21602. cv.notify_all();
  21603. });
  21604. sse.set_reconnect_interval(100);
  21605. sse.start_async();
  21606. {
  21607. std::unique_lock<std::mutex> lock(mutex);
  21608. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21609. }
  21610. sse.stop();
  21611. EXPECT_TRUE(done);
  21612. return messages;
  21613. }
  21614. };
  21615. TEST_F(SSEParsingTest, SingleLineData) {
  21616. auto msgs = parse("data: hello\n\n");
  21617. ASSERT_EQ(msgs.size(), 1u);
  21618. EXPECT_EQ(msgs[0].data, "hello");
  21619. EXPECT_EQ(msgs[0].event, "message");
  21620. }
  21621. TEST_F(SSEParsingTest, MultiLineData) {
  21622. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21623. ASSERT_EQ(msgs.size(), 1u);
  21624. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21625. }
  21626. TEST_F(SSEParsingTest, CustomEventType) {
  21627. auto msgs = parse("event: update\ndata: payload\n\n");
  21628. ASSERT_EQ(msgs.size(), 1u);
  21629. EXPECT_EQ(msgs[0].event, "update");
  21630. EXPECT_EQ(msgs[0].data, "payload");
  21631. }
  21632. TEST_F(SSEParsingTest, EventIdHandling) {
  21633. auto msgs = parse("id: 12345\ndata: test\n\n");
  21634. ASSERT_EQ(msgs.size(), 1u);
  21635. EXPECT_EQ(msgs[0].id, "12345");
  21636. }
  21637. TEST_F(SSEParsingTest, EmptyEventId) {
  21638. auto msgs = parse("id:\ndata: test\n\n");
  21639. ASSERT_EQ(msgs.size(), 1u);
  21640. EXPECT_EQ(msgs[0].id, "");
  21641. }
  21642. TEST_F(SSEParsingTest, CommentsIgnored) {
  21643. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21644. ASSERT_EQ(msgs.size(), 1u);
  21645. EXPECT_EQ(msgs[0].data, "hello");
  21646. EXPECT_EQ(msgs[0].event, "message");
  21647. }
  21648. TEST_F(SSEParsingTest, ColonInValue) {
  21649. auto msgs = parse("data: hello:world:test\n\n");
  21650. ASSERT_EQ(msgs.size(), 1u);
  21651. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21652. }
  21653. TEST_F(SSEParsingTest, FieldNameOnly) {
  21654. // A line without a colon is a field name with an empty value
  21655. auto msgs = parse("data\n\n");
  21656. ASSERT_EQ(msgs.size(), 1u);
  21657. EXPECT_EQ(msgs[0].data, "");
  21658. }
  21659. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21660. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21661. ASSERT_EQ(msgs.size(), 1u);
  21662. EXPECT_EQ(msgs[0].event, "update");
  21663. EXPECT_EQ(msgs[0].data, "hello");
  21664. }
  21665. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21666. auto msgs = parse("data\r\n\r\n");
  21667. ASSERT_EQ(msgs.size(), 1u);
  21668. EXPECT_EQ(msgs[0].data, "");
  21669. }
  21670. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21671. auto msgs = parse("event: update\rdata: hello\r\r");
  21672. ASSERT_EQ(msgs.size(), 1u);
  21673. EXPECT_EQ(msgs[0].event, "update");
  21674. EXPECT_EQ(msgs[0].data, "hello");
  21675. }
  21676. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21677. // Chunk boundaries fall inside every \r\n and right before the first one
  21678. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21679. "\n\r", "\nevent: end\ndata: end\n\n"};
  21680. server_->Get("/split", [chunks](const Request &, Response &res) {
  21681. auto i = std::make_shared<size_t>(0);
  21682. res.set_chunked_content_provider(
  21683. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21684. if (*i == chunks.size()) {
  21685. sink.done();
  21686. } else {
  21687. sink.write(chunks[*i].data(), chunks[*i].size());
  21688. (*i)++;
  21689. }
  21690. return true;
  21691. });
  21692. });
  21693. auto msgs = collect("/split");
  21694. ASSERT_EQ(msgs.size(), 1u);
  21695. EXPECT_EQ(msgs[0].event, "update");
  21696. EXPECT_EQ(msgs[0].data, "hello");
  21697. }
  21698. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21699. // Only a BOM at the start of the stream is ignored
  21700. auto msgs = parse("\xEF\xBB\xBF"
  21701. "data: first\n\n"
  21702. "\xEF\xBB\xBF"
  21703. "data: second\n\n");
  21704. ASSERT_EQ(msgs.size(), 1u);
  21705. EXPECT_EQ(msgs[0].data, "first");
  21706. }
  21707. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21708. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21709. ASSERT_EQ(msgs.size(), 1u);
  21710. EXPECT_EQ(msgs[0].data, "hello");
  21711. EXPECT_EQ(msgs[0].event, "message");
  21712. }
  21713. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21714. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21715. ASSERT_EQ(msgs.size(), 2u);
  21716. EXPECT_EQ(msgs[0].data, "hello");
  21717. EXPECT_EQ(msgs[1].data, "hello");
  21718. }
  21719. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21720. // An event without data is not dispatched, and its type must not leak
  21721. // into the next event
  21722. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21723. ASSERT_EQ(msgs.size(), 1u);
  21724. EXPECT_EQ(msgs[0].event, "message");
  21725. EXPECT_EQ(msgs[0].data, "hello");
  21726. }
  21727. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21728. // Also when the empty field replaces an earlier type
  21729. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21730. ASSERT_EQ(msgs.size(), 2u);
  21731. EXPECT_EQ(msgs[0].event, "message");
  21732. EXPECT_EQ(msgs[1].event, "message");
  21733. }
  21734. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21735. // The first connection sends only an id; the second echoes back the
  21736. // Last-Event-ID it was reconnected with
  21737. std::atomic<int> connection_count{0};
  21738. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21739. if (connection_count++ == 0) {
  21740. res.set_content("id: 42\n\n", "text/event-stream");
  21741. } else {
  21742. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21743. "\n\nevent: end\ndata: end\n\n",
  21744. "text/event-stream");
  21745. }
  21746. });
  21747. auto msgs = collect("/id-only");
  21748. ASSERT_EQ(msgs.size(), 1u);
  21749. EXPECT_EQ(msgs[0].data, "42");
  21750. }
  21751. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21752. // The first connection sets an id and then clears it with an empty one; the
  21753. // second reports whether it was reconnected with a Last-Event-ID
  21754. std::atomic<int> connection_count{0};
  21755. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21756. if (connection_count++ == 0) {
  21757. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21758. "text/event-stream");
  21759. } else {
  21760. res.set_content(
  21761. std::string("data: ") +
  21762. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21763. "\n\nevent: end\ndata: end\n\n",
  21764. "text/event-stream");
  21765. }
  21766. });
  21767. auto msgs = collect("/id-clear");
  21768. ASSERT_EQ(msgs.size(), 3u);
  21769. EXPECT_EQ(msgs[0].id, "1");
  21770. EXPECT_EQ(msgs[1].id, "");
  21771. EXPECT_EQ(msgs[2].data, "not sent");
  21772. }
  21773. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21774. // The first connection sets an id and then sends ids that cannot be carried
  21775. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21776. // with
  21777. std::atomic<int> connection_count{0};
  21778. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21779. if (connection_count++ == 0) {
  21780. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21781. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21782. "text/event-stream");
  21783. } else {
  21784. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21785. "\n\nevent: end\ndata: end\n\n",
  21786. "text/event-stream");
  21787. }
  21788. });
  21789. auto msgs = collect("/id-unsendable");
  21790. ASSERT_EQ(msgs.size(), 1u);
  21791. EXPECT_EQ(msgs[0].data, "42");
  21792. }
  21793. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21794. auto msgs = parse("event: notification\nid: evt-42\n"
  21795. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21796. ASSERT_EQ(msgs.size(), 1u);
  21797. EXPECT_EQ(msgs[0].event, "notification");
  21798. EXPECT_EQ(msgs[0].id, "evt-42");
  21799. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21800. }
  21801. TEST(SSEMessageTest, Clear) {
  21802. sse::SSEMessage msg;
  21803. msg.event = "custom";
  21804. msg.data = "some data";
  21805. msg.id = "123";
  21806. msg.clear();
  21807. EXPECT_EQ(msg.event, "message");
  21808. EXPECT_EQ(msg.data, "");
  21809. EXPECT_EQ(msg.id, "");
  21810. }
  21811. //==============================================================================
  21812. // SSE Integration Tests
  21813. //==============================================================================
  21814. // Test: Successful connection and on_open callback
  21815. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21816. // Add a simple endpoint that sends one event and closes
  21817. server_->Get("/simple-event", [](const Request &, Response &res) {
  21818. res.set_chunked_content_provider(
  21819. "text/event-stream", [](size_t offset, DataSink &sink) {
  21820. if (offset == 0) {
  21821. std::string event = "data: hello\n\n";
  21822. sink.write(event.data(), event.size());
  21823. }
  21824. return false; // Close stream after sending
  21825. });
  21826. });
  21827. Client client("localhost", get_port());
  21828. sse::SSEClient sse(client, "/simple-event");
  21829. std::atomic<bool> open_called{false};
  21830. std::atomic<bool> message_received{false};
  21831. sse.on_open([&open_called]() { open_called.store(true); });
  21832. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21833. if (msg.data == "hello") { message_received.store(true); }
  21834. });
  21835. sse.set_reconnect_interval(100);
  21836. sse.set_max_reconnect_attempts(1);
  21837. // Start async
  21838. sse.start_async();
  21839. // Wait for message to be processed
  21840. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21841. sse.stop();
  21842. EXPECT_TRUE(open_called.load());
  21843. EXPECT_TRUE(message_received.load());
  21844. }
  21845. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21846. // A data line that never ends.
  21847. server_->Get("/endless-line", [](const Request &, Response &res) {
  21848. res.set_chunked_content_provider(
  21849. "text/event-stream", [](size_t offset, DataSink &sink) {
  21850. if (offset == 0) { sink.write("data: ", 6); }
  21851. std::string chunk(64 * 1024, 'A');
  21852. return sink.write(chunk.data(), chunk.size());
  21853. });
  21854. });
  21855. Client client("localhost", get_port());
  21856. sse::SSEClient sse(client, "/endless-line");
  21857. std::atomic<bool> too_long{false};
  21858. sse.on_error([&](Error err) {
  21859. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21860. });
  21861. sse.set_max_reconnect_attempts(1);
  21862. sse.start_async();
  21863. for (int i = 0; i < 500 && !too_long; i++) {
  21864. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21865. }
  21866. sse.stop();
  21867. EXPECT_TRUE(too_long);
  21868. }
  21869. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21870. // Far more in all than the client's payload limit below.
  21871. server_->Get("/many-events", [](const Request &, Response &res) {
  21872. res.set_chunked_content_provider(
  21873. "text/event-stream", [](size_t offset, DataSink &sink) {
  21874. if (offset == 0) {
  21875. std::string events;
  21876. for (int i = 0; i < 1000; i++) {
  21877. events += "data: message\n\n";
  21878. }
  21879. sink.write(events.data(), events.size());
  21880. }
  21881. return false;
  21882. });
  21883. });
  21884. Client client("localhost", get_port());
  21885. client.set_payload_max_length(1024);
  21886. sse::SSEClient sse(client, "/many-events");
  21887. std::atomic<int> messages{0};
  21888. std::atomic<bool> too_large{false};
  21889. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21890. sse.on_error([&](Error err) {
  21891. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21892. });
  21893. sse.set_max_reconnect_attempts(1);
  21894. sse.start_async();
  21895. for (int i = 0; i < 500 && messages < 1000; i++) {
  21896. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21897. }
  21898. sse.stop();
  21899. EXPECT_GE(messages.load(), 1000);
  21900. EXPECT_FALSE(too_large);
  21901. }
  21902. // Test: on_message callback
  21903. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21904. // Endpoint that sends multiple events then closes
  21905. server_->Get("/multi-event", [](const Request &, Response &res) {
  21906. res.set_chunked_content_provider(
  21907. "text/event-stream", [](size_t offset, DataSink &sink) {
  21908. if (offset == 0) {
  21909. std::string events = "data: message1\n\ndata: message2\n\n";
  21910. sink.write(events.data(), events.size());
  21911. }
  21912. return false;
  21913. });
  21914. });
  21915. Client client("localhost", get_port());
  21916. sse::SSEClient sse(client, "/multi-event");
  21917. std::vector<std::string> received_messages;
  21918. std::mutex messages_mutex;
  21919. sse.on_message([&](const sse::SSEMessage &msg) {
  21920. std::lock_guard<std::mutex> lock(messages_mutex);
  21921. received_messages.push_back(msg.data);
  21922. });
  21923. sse.set_reconnect_interval(100);
  21924. sse.set_max_reconnect_attempts(1);
  21925. sse.start_async();
  21926. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21927. sse.stop();
  21928. std::lock_guard<std::mutex> lock(messages_mutex);
  21929. EXPECT_GE(received_messages.size(), 2u);
  21930. if (received_messages.size() >= 2) {
  21931. EXPECT_EQ(received_messages[0], "message1");
  21932. EXPECT_EQ(received_messages[1], "message2");
  21933. }
  21934. }
  21935. // Test: on_event for specific types
  21936. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21937. Client client("localhost", get_port());
  21938. sse::SSEClient sse(client, "/custom-events");
  21939. std::atomic<bool> update_received{false};
  21940. std::atomic<bool> delete_received{false};
  21941. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21942. if (msg.data == "updated") { update_received.store(true); }
  21943. });
  21944. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21945. if (msg.data == "deleted") { delete_received.store(true); }
  21946. });
  21947. sse.set_max_reconnect_attempts(1);
  21948. sse.start_async();
  21949. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21950. sse.stop();
  21951. EXPECT_TRUE(update_received.load());
  21952. EXPECT_TRUE(delete_received.load());
  21953. }
  21954. // Test: on_error callback on connection failure
  21955. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21956. // Connect to a non-existent port
  21957. Client client("localhost", 59999);
  21958. sse::SSEClient sse(client, "/events");
  21959. std::atomic<bool> error_called{false};
  21960. Error received_error = Error::Success;
  21961. sse.on_error([&](Error err) {
  21962. error_called.store(true);
  21963. received_error = err;
  21964. });
  21965. sse.set_reconnect_interval(50);
  21966. sse.set_max_reconnect_attempts(1);
  21967. sse.start_async();
  21968. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21969. sse.stop();
  21970. EXPECT_TRUE(error_called.load());
  21971. EXPECT_NE(received_error, Error::Success);
  21972. }
  21973. // Test: Last-Event-ID header sent on reconnect
  21974. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21975. // Endpoint that sends event with ID
  21976. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21977. res.set_chunked_content_provider(
  21978. "text/event-stream", [](size_t offset, DataSink &sink) {
  21979. if (offset == 0) {
  21980. std::string event = "id: evt-123\ndata: test\n\n";
  21981. sink.write(event.data(), event.size());
  21982. }
  21983. return false;
  21984. });
  21985. });
  21986. Client client("localhost", get_port());
  21987. sse::SSEClient sse(client, "/event-with-id");
  21988. std::atomic<bool> id_received{false};
  21989. sse.on_message([&](const sse::SSEMessage &msg) {
  21990. if (!msg.id.empty()) { id_received.store(true); }
  21991. });
  21992. sse.set_reconnect_interval(100);
  21993. sse.set_max_reconnect_attempts(1);
  21994. sse.start_async();
  21995. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21996. sse.stop();
  21997. EXPECT_TRUE(id_received.load());
  21998. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21999. }
  22000. // Test: Manual stop
  22001. TEST_F(SSEIntegrationTest, ManualStop) {
  22002. // Endpoint that sends one event and stays open briefly. The server outlives
  22003. // this test body, so the provider uses the fixture's flag, not a local.
  22004. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22005. res.set_chunked_content_provider(
  22006. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22007. if (offset == 0) {
  22008. std::string event = "data: connected\n\n";
  22009. sink.write(event.data(), event.size());
  22010. }
  22011. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22012. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22013. }
  22014. return false;
  22015. });
  22016. });
  22017. Client client("localhost", get_port());
  22018. sse::SSEClient sse(client, "/stay-open");
  22019. std::atomic<bool> connected{false};
  22020. sse.on_open([&connected]() { connected.store(true); });
  22021. sse.set_reconnect_interval(100);
  22022. sse.set_max_reconnect_attempts(1);
  22023. sse.start_async();
  22024. // Wait for connection to establish
  22025. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22026. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22027. }
  22028. EXPECT_TRUE(connected.load());
  22029. EXPECT_TRUE(sse.is_connected());
  22030. // Signal handler to stop
  22031. stop_server_.store(true);
  22032. // Stop SSE client
  22033. sse.stop();
  22034. EXPECT_FALSE(sse.is_connected());
  22035. }
  22036. // Sends one event, then nothing until stop is set
  22037. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22038. return [&stop](const Request &, Response &res) {
  22039. res.set_chunked_content_provider(
  22040. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22041. if (offset == 0) {
  22042. std::string event = "data: hello\n\n";
  22043. sink.write(event.data(), event.size());
  22044. }
  22045. while (!stop.load()) {
  22046. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22047. }
  22048. return false;
  22049. });
  22050. };
  22051. }
  22052. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22053. static void check_stop_interrupts_blocked_read(Client &client) {
  22054. client.set_read_timeout(30, 0);
  22055. for (auto by_destructor : {false, true}) {
  22056. std::atomic<bool> received{false};
  22057. std::chrono::steady_clock::time_point start;
  22058. {
  22059. sse::SSEClient sse(client, "/idle-stream");
  22060. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22061. sse.start_async();
  22062. for (int i = 0; i < 500 && !received.load(); ++i) {
  22063. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22064. }
  22065. ASSERT_TRUE(received.load());
  22066. // Let the client block in the next read
  22067. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22068. start = std::chrono::steady_clock::now();
  22069. if (!by_destructor) { sse.stop(); }
  22070. }
  22071. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22072. std::chrono::seconds(2));
  22073. }
  22074. }
  22075. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22076. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22077. Client client("localhost", get_port());
  22078. check_stop_interrupts_blocked_read(client);
  22079. }
  22080. #ifdef CPPHTTPLIB_SSL_ENABLED
  22081. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22082. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22083. std::atomic<bool> done{false};
  22084. svr.Get("/idle-stream", idle_event_stream(done));
  22085. auto port = svr.bind_to_any_port(HOST);
  22086. std::thread t([&] { svr.listen_after_bind(); });
  22087. auto se = detail::scope_exit([&] {
  22088. done.store(true);
  22089. svr.stop();
  22090. t.join();
  22091. });
  22092. svr.wait_until_ready();
  22093. Client client("https://localhost:" + std::to_string(port));
  22094. client.enable_server_certificate_verification(false);
  22095. check_stop_interrupts_blocked_read(client);
  22096. }
  22097. #endif
  22098. // Test: SSEClient with custom headers
  22099. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22100. // Setup a server endpoint that checks for custom header
  22101. std::atomic<bool> header_received{false};
  22102. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22103. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22104. header_received.store(true);
  22105. }
  22106. res.set_chunked_content_provider("text/event-stream",
  22107. [](size_t, DataSink &) { return false; });
  22108. });
  22109. Client client("localhost", get_port());
  22110. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22111. sse::SSEClient sse(client, "/header-check", headers);
  22112. sse.set_max_reconnect_attempts(1);
  22113. sse.start_async();
  22114. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22115. sse.stop();
  22116. EXPECT_TRUE(header_received.load());
  22117. }
  22118. // Test: Reconnect interval configuration
  22119. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22120. Client client("localhost", get_port());
  22121. sse::SSEClient sse(client, "/events");
  22122. auto &result = sse.set_reconnect_interval(500);
  22123. // Builder pattern should return reference to self
  22124. EXPECT_EQ(&result, &sse);
  22125. }
  22126. // Test: Max reconnect attempts
  22127. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22128. // Connect to non-existent port to force reconnects
  22129. Client client("localhost", 59998);
  22130. sse::SSEClient sse(client, "/events");
  22131. std::atomic<int> error_count{0};
  22132. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22133. sse.set_reconnect_interval(50);
  22134. sse.set_max_reconnect_attempts(2);
  22135. auto start = std::chrono::steady_clock::now();
  22136. sse.start(); // Blocking call
  22137. auto end = std::chrono::steady_clock::now();
  22138. // Should have stopped after 2 failed attempts
  22139. EXPECT_GE(error_count.load(), 2);
  22140. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22141. auto duration =
  22142. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22143. #ifdef _WIN32
  22144. // Windows is much slower for socket connection failures
  22145. EXPECT_LT(duration.count(), 7000);
  22146. #else
  22147. EXPECT_LT(duration.count(), 1000);
  22148. #endif
  22149. }
  22150. // Test: Multi-line data in integration
  22151. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22152. // Endpoint with multi-line data
  22153. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22154. res.set_chunked_content_provider(
  22155. "text/event-stream", [](size_t offset, DataSink &sink) {
  22156. if (offset == 0) {
  22157. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22158. sink.write(event.data(), event.size());
  22159. }
  22160. return false;
  22161. });
  22162. });
  22163. Client client("localhost", get_port());
  22164. sse::SSEClient sse(client, "/multiline-data");
  22165. std::string received_data;
  22166. std::mutex data_mutex;
  22167. sse.on_message([&](const sse::SSEMessage &msg) {
  22168. std::lock_guard<std::mutex> lock(data_mutex);
  22169. received_data = msg.data;
  22170. });
  22171. sse.set_reconnect_interval(100);
  22172. sse.set_max_reconnect_attempts(1);
  22173. sse.start_async();
  22174. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22175. sse.stop();
  22176. std::lock_guard<std::mutex> lock(data_mutex);
  22177. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22178. }
  22179. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22180. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22181. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22182. DataSink &sink) {
  22183. if (offset == 0) {
  22184. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22185. sink.write(events.data(), events.size());
  22186. }
  22187. return false;
  22188. });
  22189. });
  22190. Client client("localhost", get_port());
  22191. sse::SSEClient sse(client, "/empty-data-lines");
  22192. std::mutex mutex;
  22193. std::condition_variable cv;
  22194. std::vector<std::string> received;
  22195. sse.on_message([&](const sse::SSEMessage &msg) {
  22196. std::lock_guard<std::mutex> lock(mutex);
  22197. received.push_back(msg.data);
  22198. cv.notify_all();
  22199. });
  22200. sse.set_max_reconnect_attempts(1);
  22201. sse.start_async();
  22202. {
  22203. std::unique_lock<std::mutex> lock(mutex);
  22204. cv.wait_for(lock, std::chrono::seconds(2),
  22205. [&] { return received.size() >= 3; });
  22206. }
  22207. sse.stop();
  22208. ASSERT_GE(received.size(), 3u);
  22209. EXPECT_EQ(received[0], "");
  22210. EXPECT_EQ(received[1], "\nhello");
  22211. EXPECT_EQ(received[2], "");
  22212. }
  22213. // Test: Auto-reconnect after server disconnection
  22214. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22215. std::atomic<int> connection_count{0};
  22216. std::atomic<int> message_count{0};
  22217. // Endpoint that sends one event and closes, forcing reconnect
  22218. server_->Get("/reconnect-test",
  22219. [&connection_count](const Request &, Response &res) {
  22220. connection_count.fetch_add(1);
  22221. res.set_chunked_content_provider(
  22222. "text/event-stream", [](size_t offset, DataSink &sink) {
  22223. if (offset == 0) {
  22224. std::string event = "data: hello\n\n";
  22225. sink.write(event.data(), event.size());
  22226. }
  22227. return false; // Close connection after sending
  22228. });
  22229. });
  22230. Client client("localhost", get_port());
  22231. sse::SSEClient sse(client, "/reconnect-test");
  22232. sse.on_message([&message_count](const sse::SSEMessage &) {
  22233. message_count.fetch_add(1);
  22234. });
  22235. sse.set_reconnect_interval(100);
  22236. sse.set_max_reconnect_attempts(3);
  22237. sse.start_async();
  22238. // Wait long enough for multiple reconnects
  22239. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22240. sse.stop();
  22241. // Should have connected multiple times (initial + reconnects)
  22242. EXPECT_GE(connection_count.load(), 2);
  22243. // Should have received messages from multiple connections
  22244. EXPECT_GE(message_count.load(), 2);
  22245. }
  22246. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22247. std::atomic<int> connection_count{0};
  22248. // Neither Content-Length nor chunked: the close ends the stream
  22249. server_->Get("/close-delimited",
  22250. [&connection_count](const Request &, Response &res) {
  22251. connection_count.fetch_add(1);
  22252. res.set_content_provider(
  22253. "text/event-stream", [](size_t offset, DataSink &sink) {
  22254. if (offset == 0) {
  22255. std::string event = "data: hello\n\n";
  22256. sink.write(event.data(), event.size());
  22257. } else {
  22258. sink.done();
  22259. }
  22260. return true;
  22261. });
  22262. });
  22263. Client client("localhost", get_port());
  22264. sse::SSEClient sse(client, "/close-delimited");
  22265. std::atomic<int> error_count{0};
  22266. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22267. sse.set_reconnect_interval(100);
  22268. sse.start_async();
  22269. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22270. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22271. }
  22272. sse.stop();
  22273. // Reconnects as after any end of the stream, but reports no error
  22274. EXPECT_GE(connection_count.load(), 2);
  22275. EXPECT_EQ(0, error_count.load());
  22276. }
  22277. // Test: A retry field that is not all ASCII digits is ignored
  22278. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22279. std::atomic<int> connection_count{0};
  22280. server_->Get("/bad-retry",
  22281. [&connection_count](const Request &, Response &res) {
  22282. connection_count.fetch_add(1);
  22283. res.set_chunked_content_provider(
  22284. "text/event-stream", [](size_t offset, DataSink &sink) {
  22285. if (offset == 0) {
  22286. std::string event = "retry: -1\ndata: hello\n\n";
  22287. sink.write(event.data(), event.size());
  22288. }
  22289. return false;
  22290. });
  22291. });
  22292. Client client("localhost", get_port());
  22293. sse::SSEClient sse(client, "/bad-retry");
  22294. sse.set_reconnect_interval(10000);
  22295. sse.start_async();
  22296. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22297. sse.stop();
  22298. EXPECT_EQ(connection_count.load(), 1);
  22299. }
  22300. // Test: A retry field of all ASCII digits sets the reconnection time
  22301. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22302. std::mutex mutex;
  22303. std::condition_variable cv;
  22304. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22305. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22306. {
  22307. std::lock_guard<std::mutex> lock(mutex);
  22308. connected_at.push_back(std::chrono::steady_clock::now());
  22309. cv.notify_all();
  22310. }
  22311. res.set_chunked_content_provider(
  22312. "text/event-stream", [](size_t offset, DataSink &sink) {
  22313. if (offset == 0) {
  22314. std::string event = "retry: 0\ndata: hello\n\n";
  22315. sink.write(event.data(), event.size());
  22316. }
  22317. return false;
  22318. });
  22319. });
  22320. Client client("localhost", get_port());
  22321. sse::SSEClient sse(client, "/zero-retry");
  22322. sse.set_reconnect_interval(10000);
  22323. sse.start_async();
  22324. {
  22325. std::unique_lock<std::mutex> lock(mutex);
  22326. cv.wait_for(lock, std::chrono::seconds(5),
  22327. [&] { return connected_at.size() >= 2; });
  22328. }
  22329. sse.stop();
  22330. // The server-supplied interval is applied, but never below 100ms, so
  22331. // "retry: 0" does not cause a busy reconnect loop
  22332. std::lock_guard<std::mutex> lock(mutex);
  22333. ASSERT_GE(connected_at.size(), 2u);
  22334. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22335. connected_at[1] - connected_at[0])
  22336. .count();
  22337. EXPECT_GE(interval_ms, 100);
  22338. }
  22339. // Test: Last-Event-ID sent on reconnect
  22340. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22341. std::atomic<int> connection_count{0};
  22342. std::vector<std::string> received_last_event_ids;
  22343. std::mutex id_mutex;
  22344. // Endpoint that checks Last-Event-ID header and sends event with ID
  22345. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22346. int conn = connection_count.fetch_add(1);
  22347. // Capture the Last-Event-ID header from each connection
  22348. {
  22349. std::lock_guard<std::mutex> lock(id_mutex);
  22350. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22351. }
  22352. res.set_chunked_content_provider(
  22353. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22354. if (offset == 0) {
  22355. std::string event =
  22356. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22357. sink.write(event.data(), event.size());
  22358. }
  22359. return false;
  22360. });
  22361. });
  22362. Client client("localhost", get_port());
  22363. sse::SSEClient sse(client, "/reconnect-with-id");
  22364. sse.set_reconnect_interval(100);
  22365. sse.set_max_reconnect_attempts(3);
  22366. sse.start_async();
  22367. // Wait for at least 2 connections
  22368. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22369. sse.stop();
  22370. // Verify behavior
  22371. std::lock_guard<std::mutex> lock(id_mutex);
  22372. EXPECT_GE(received_last_event_ids.size(), 2u);
  22373. // First connection should have no Last-Event-ID
  22374. if (!received_last_event_ids.empty()) {
  22375. EXPECT_EQ(received_last_event_ids[0], "");
  22376. }
  22377. // Second connection should have Last-Event-ID from first connection
  22378. if (received_last_event_ids.size() >= 2) {
  22379. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22380. }
  22381. }
  22382. // Test: set_headers updates headers used on reconnect
  22383. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22384. std::vector<std::string> received_tokens;
  22385. std::mutex token_mutex;
  22386. // Endpoint that captures Authorization header
  22387. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22388. {
  22389. std::lock_guard<std::mutex> lock(token_mutex);
  22390. received_tokens.push_back(req.get_header_value("Authorization"));
  22391. }
  22392. res.set_chunked_content_provider(
  22393. "text/event-stream", [](size_t offset, DataSink &sink) {
  22394. if (offset == 0) {
  22395. std::string event = "data: hello\n\n";
  22396. sink.write(event.data(), event.size());
  22397. }
  22398. return false; // Close connection to trigger reconnect
  22399. });
  22400. });
  22401. Client client("localhost", get_port());
  22402. Headers headers = {{"Authorization", "Bearer old-token"}};
  22403. sse::SSEClient sse(client, "/auth-check", headers);
  22404. // Update headers on each successful connection
  22405. sse.on_open(
  22406. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22407. sse.set_reconnect_interval(100);
  22408. sse.set_max_reconnect_attempts(3);
  22409. sse.start_async();
  22410. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22411. sse.stop();
  22412. std::lock_guard<std::mutex> lock(token_mutex);
  22413. ASSERT_GE(received_tokens.size(), 2u);
  22414. // First connection uses original header
  22415. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22416. // Second connection uses updated header from set_headers
  22417. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22418. }
  22419. // Test: 401 allows reconnection (so on_error can refresh headers)
  22420. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22421. std::atomic<int> connection_count{0};
  22422. // Endpoint: returns 401 on first attempt, 200 on second
  22423. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22424. int conn = connection_count.fetch_add(1);
  22425. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22426. res.status = StatusCode::Unauthorized_401;
  22427. res.set_content("Unauthorized", "text/plain");
  22428. return;
  22429. }
  22430. res.set_chunked_content_provider(
  22431. "text/event-stream", [](size_t offset, DataSink &sink) {
  22432. if (offset == 0) {
  22433. std::string event = "data: authenticated\n\n";
  22434. sink.write(event.data(), event.size());
  22435. }
  22436. return false;
  22437. });
  22438. });
  22439. Client client("localhost", get_port());
  22440. Headers headers = {{"Authorization", "Bearer expired"}};
  22441. sse::SSEClient sse(client, "/auth-retry", headers);
  22442. std::atomic<bool> message_received{false};
  22443. // Refresh token on error
  22444. sse.on_error(
  22445. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22446. sse.on_message([&](const sse::SSEMessage &msg) {
  22447. if (msg.data == "authenticated") { message_received.store(true); }
  22448. });
  22449. sse.set_reconnect_interval(100);
  22450. sse.set_max_reconnect_attempts(3);
  22451. sse.start_async();
  22452. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22453. sse.stop();
  22454. // Should have reconnected after 401 and succeeded with new token
  22455. EXPECT_GE(connection_count.load(), 2);
  22456. EXPECT_TRUE(message_received.load());
  22457. }
  22458. TEST(Issue2318Test, EmptyHostString) {
  22459. {
  22460. httplib::Client cli_empty("", PORT);
  22461. auto res = cli_empty.Get("/");
  22462. ASSERT_FALSE(res);
  22463. EXPECT_EQ(httplib::Error::Connection, res.error());
  22464. }
  22465. {
  22466. httplib::Client cli(" ", PORT);
  22467. auto res = cli.Get("/");
  22468. ASSERT_FALSE(res);
  22469. EXPECT_EQ(httplib::Error::Connection, res.error());
  22470. }
  22471. }
  22472. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22473. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22474. Server svr;
  22475. // Set a small payload limit (1KB)
  22476. svr.set_payload_max_length(1024);
  22477. svr.Post("/test", [&](const Request &req, Response &res) {
  22478. res.set_content("Body size: " + std::to_string(req.body.size()),
  22479. "text/plain");
  22480. });
  22481. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22482. auto se = detail::scope_exit([&] {
  22483. svr.stop();
  22484. listen_thread.join();
  22485. });
  22486. svr.wait_until_ready();
  22487. // Create data that compresses well but exceeds limit when decompressed
  22488. // 8KB of repeated null bytes compresses to a very small size
  22489. std::string original_data(8 * 1024, '\0');
  22490. // Compress the data using gzip
  22491. std::string compressed_data;
  22492. detail::gzip_compressor compressor;
  22493. compressor.compress(original_data.data(), original_data.size(), true,
  22494. [&](const char *data, size_t size) {
  22495. compressed_data.append(data, size);
  22496. return true;
  22497. });
  22498. // Verify compression worked (compressed should be much smaller)
  22499. ASSERT_LT(compressed_data.size(), original_data.size());
  22500. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22501. // Send compressed data with Content-Encoding: gzip
  22502. Client cli(HOST, PORT);
  22503. Headers headers = {{"Content-Encoding", "gzip"}};
  22504. auto res =
  22505. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22506. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22508. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22509. }
  22510. #endif
  22511. // ============================================================================
  22512. // OpenSSL-Specific Tests
  22513. // ============================================================================
  22514. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22515. X509 *readCertificate(const std::string &strFileName) {
  22516. std::ifstream inStream(strFileName);
  22517. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22518. std::istreambuf_iterator<char>());
  22519. if (strCertPEM.empty()) return (nullptr);
  22520. BIO *pbCert = BIO_new(BIO_s_mem());
  22521. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22522. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22523. BIO_free(pbCert);
  22524. return (pCert);
  22525. }
  22526. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22527. std::ifstream inStream(strFileName);
  22528. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22529. std::istreambuf_iterator<char>());
  22530. if (strPrivateKeyPEM.empty()) return (nullptr);
  22531. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22532. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22533. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22534. BIO_free(pbPrivKey);
  22535. return (pPrivateKey);
  22536. }
  22537. TEST(BindServerTest, UpdateCerts) {
  22538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22539. int port = svr.bind_to_any_port("0.0.0.0");
  22540. ASSERT_TRUE(svr.is_valid());
  22541. ASSERT_TRUE(port > 0);
  22542. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22543. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22544. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22545. ASSERT_TRUE(cert != nullptr);
  22546. ASSERT_TRUE(ca_cert != nullptr);
  22547. ASSERT_TRUE(key != nullptr);
  22548. X509_STORE *cert_store = X509_STORE_new();
  22549. X509_STORE_add_cert(cert_store, ca_cert);
  22550. // svr.update_certs(cert, key, cert_store); // deprecated
  22551. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22552. CLIENT_CA_CERT_FILE);
  22553. ASSERT_TRUE(svr.is_valid());
  22554. svr.stop();
  22555. X509_STORE_free(cert_store);
  22556. X509_free(cert);
  22557. X509_free(ca_cert);
  22558. EVP_PKEY_free(key);
  22559. }
  22560. // Test that update_certs() updates client CA list correctly
  22561. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22562. // Start with file-based constructor
  22563. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22564. ASSERT_TRUE(svr.is_valid());
  22565. // Initially no client CA list should be set
  22566. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22567. ASSERT_TRUE(ssl_ctx != nullptr);
  22568. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22569. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22570. // Now update with client CA (PEM string)
  22571. std::string cert_pem, key_pem, ca_pem;
  22572. read_file(SERVER_CERT_FILE, cert_pem);
  22573. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22574. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22575. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22576. ASSERT_TRUE(svr.is_valid());
  22577. // Now client CA list should be set
  22578. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22579. ASSERT_TRUE(ca_list_after != nullptr);
  22580. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22581. }
  22582. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22583. // Test that the file-path SSLServer constructor properly sets the client CA
  22584. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22585. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22586. ASSERT_TRUE(svr.is_valid());
  22587. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22588. ASSERT_TRUE(ssl_ctx != nullptr);
  22589. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22590. ASSERT_TRUE(ca_list != nullptr);
  22591. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22592. }
  22593. #endif
  22594. // ============================================================================
  22595. // MbedTLS-Specific Tests
  22596. // ============================================================================
  22597. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22598. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22599. using namespace httplib::tls;
  22600. // Track if callback was invoked
  22601. bool callback_invoked = false;
  22602. // The callback receives void* ctx which is actually MbedTlsContext*
  22603. // We can access the mbedtls_ssl_config via the context
  22604. auto setup_callback = [&callback_invoked](void *ctx) {
  22605. callback_invoked = true;
  22606. // Cast to MbedTlsContext* to access the ssl config
  22607. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22608. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22609. // Use static variables to hold certificate data (simplified for test)
  22610. static mbedtls_x509_crt own_cert;
  22611. static mbedtls_pk_context own_key;
  22612. static mbedtls_x509_crt ca_chain;
  22613. static bool initialized = false;
  22614. if (!initialized) {
  22615. mbedtls_x509_crt_init(&own_cert);
  22616. mbedtls_pk_init(&own_key);
  22617. mbedtls_x509_crt_init(&ca_chain);
  22618. // Load server certificate
  22619. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22620. return false;
  22621. }
  22622. // Load server private key.
  22623. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22624. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22625. #if MBEDTLS_VERSION_MAJOR == 3
  22626. ,
  22627. mbedtls_ctr_drbg_random, nullptr
  22628. #endif
  22629. ) != 0) {
  22630. return false;
  22631. }
  22632. // Load CA chain for client verification
  22633. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22634. return false;
  22635. }
  22636. initialized = true;
  22637. }
  22638. // Configure the SSL config
  22639. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22640. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22641. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22642. // Set minimum TLS version using mbedTLS native API
  22643. #if MBEDTLS_VERSION_MAJOR >= 3
  22644. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22645. #else
  22646. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22647. MBEDTLS_SSL_MINOR_VERSION_3);
  22648. #endif
  22649. return true;
  22650. };
  22651. SSLServer svr(setup_callback);
  22652. ASSERT_TRUE(svr.is_valid());
  22653. ASSERT_TRUE(callback_invoked);
  22654. svr.Get("/test", [&](const Request &req, Response &res) {
  22655. res.set_content("test", "text/plain");
  22656. auto cert = req.peer_cert();
  22657. ASSERT_TRUE(static_cast<bool>(cert));
  22658. auto common_name = cert.subject_cn();
  22659. EXPECT_EQ("Common Name", common_name);
  22660. });
  22661. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22662. auto se = detail::scope_exit([&] {
  22663. svr.stop();
  22664. t.join();
  22665. ASSERT_FALSE(svr.is_running());
  22666. });
  22667. svr.wait_until_ready();
  22668. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22669. cli.enable_server_certificate_verification(false);
  22670. cli.set_connection_timeout(30);
  22671. auto res = cli.Get("/test");
  22672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22673. ASSERT_EQ(StatusCode::OK_200, res->status);
  22674. }
  22675. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22676. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22677. // keep-alive SSL session, which reads through that config in
  22678. // mbedtls_ssl_close_notify.
  22679. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22680. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22681. ASSERT_TRUE(svr.is_valid());
  22682. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22683. res.set_content("test", "text/plain");
  22684. });
  22685. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22686. auto se = detail::scope_exit([&] {
  22687. svr.stop();
  22688. t.join();
  22689. ASSERT_FALSE(svr.is_running());
  22690. });
  22691. svr.wait_until_ready();
  22692. {
  22693. SSLClient cli(HOST, PORT);
  22694. cli.enable_server_certificate_verification(false);
  22695. cli.set_keep_alive(true);
  22696. auto res = cli.Get("/test");
  22697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22698. ASSERT_EQ(StatusCode::OK_200, res->status);
  22699. // cli is destructed here with the keep-alive SSL session still open.
  22700. }
  22701. }
  22702. #endif
  22703. // WebSocket Tests
  22704. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22705. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22706. // defining the meaning of these bits has been negotiated.
  22707. auto make_frame = [](uint8_t first_byte) {
  22708. std::string frame;
  22709. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22710. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22711. frame += "Hello";
  22712. return frame;
  22713. };
  22714. // RSV1 set (0x40)
  22715. {
  22716. detail::BufferStream strm;
  22717. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22718. ws::Opcode opcode;
  22719. std::string payload;
  22720. bool fin;
  22721. EXPECT_EQ(
  22722. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22723. ws::impl::FrameRead::Fail);
  22724. }
  22725. // RSV2 set (0x20)
  22726. {
  22727. detail::BufferStream strm;
  22728. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22729. ws::Opcode opcode;
  22730. std::string payload;
  22731. bool fin;
  22732. EXPECT_EQ(
  22733. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22734. ws::impl::FrameRead::Fail);
  22735. }
  22736. // RSV3 set (0x10)
  22737. {
  22738. detail::BufferStream strm;
  22739. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22740. ws::Opcode opcode;
  22741. std::string payload;
  22742. bool fin;
  22743. EXPECT_EQ(
  22744. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22745. ws::impl::FrameRead::Fail);
  22746. }
  22747. // No RSV bits set - should succeed
  22748. {
  22749. detail::BufferStream strm;
  22750. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22751. ws::Opcode opcode;
  22752. std::string payload;
  22753. bool fin;
  22754. EXPECT_EQ(
  22755. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22756. ws::impl::FrameRead::Ok);
  22757. EXPECT_EQ(ws::Opcode::Text, opcode);
  22758. EXPECT_EQ("Hello", payload);
  22759. EXPECT_TRUE(fin);
  22760. }
  22761. }
  22762. TEST(WebSocketTest, ControlFrameValidation) {
  22763. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22764. // payload length <= 125.
  22765. // Ping with FIN=0 - must be rejected
  22766. {
  22767. detail::BufferStream strm;
  22768. std::string frame;
  22769. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22770. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22771. strm.write(frame.data(), frame.size());
  22772. ws::Opcode opcode;
  22773. std::string payload;
  22774. bool fin;
  22775. EXPECT_EQ(
  22776. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22777. ws::impl::FrameRead::Fail);
  22778. }
  22779. // Close with FIN=0 - must be rejected
  22780. {
  22781. detail::BufferStream strm;
  22782. std::string frame;
  22783. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22784. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22785. strm.write(frame.data(), frame.size());
  22786. ws::Opcode opcode;
  22787. std::string payload;
  22788. bool fin;
  22789. EXPECT_EQ(
  22790. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22791. ws::impl::FrameRead::Fail);
  22792. }
  22793. // Ping with payload_len=126 (extended length) - must be rejected
  22794. {
  22795. detail::BufferStream strm;
  22796. std::string frame;
  22797. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22798. frame += static_cast<char>(126); // payload_len=126 (>125)
  22799. frame += static_cast<char>(0x00); // extended length high byte
  22800. frame += static_cast<char>(126); // extended length low byte
  22801. frame += std::string(126, 'x');
  22802. strm.write(frame.data(), frame.size());
  22803. ws::Opcode opcode;
  22804. std::string payload;
  22805. bool fin;
  22806. EXPECT_EQ(
  22807. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22808. ws::impl::FrameRead::Fail);
  22809. }
  22810. // Ping with FIN=1 and payload_len=125 - should succeed
  22811. {
  22812. detail::BufferStream strm;
  22813. std::string frame;
  22814. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22815. frame += static_cast<char>(125); // payload_len=125
  22816. frame += std::string(125, 'x');
  22817. strm.write(frame.data(), frame.size());
  22818. ws::Opcode opcode;
  22819. std::string payload;
  22820. bool fin;
  22821. EXPECT_EQ(
  22822. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22823. ws::impl::FrameRead::Ok);
  22824. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22825. EXPECT_EQ(125u, payload.size());
  22826. EXPECT_TRUE(fin);
  22827. }
  22828. }
  22829. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22830. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22831. // length MUST be 0.
  22832. // MSB set - must be rejected
  22833. {
  22834. detail::BufferStream strm;
  22835. std::string frame;
  22836. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22837. frame += static_cast<char>(127); // 64-bit extended length
  22838. frame += static_cast<char>(0x80); // MSB set (invalid)
  22839. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22840. strm.write(frame.data(), frame.size());
  22841. ws::Opcode opcode;
  22842. std::string payload;
  22843. bool fin;
  22844. EXPECT_EQ(
  22845. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22846. ws::impl::FrameRead::Fail);
  22847. }
  22848. // MSB clear - should pass length parsing (will be rejected by max_len,
  22849. // but that's a different check; use a small length to verify)
  22850. {
  22851. detail::BufferStream strm;
  22852. std::string frame;
  22853. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22854. frame += static_cast<char>(127); // 64-bit extended length
  22855. frame += std::string(7, '\0'); // high bytes = 0
  22856. frame += static_cast<char>(0x03); // length = 3
  22857. frame += "abc";
  22858. strm.write(frame.data(), frame.size());
  22859. ws::Opcode opcode;
  22860. std::string payload;
  22861. bool fin;
  22862. EXPECT_EQ(
  22863. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22864. ws::impl::FrameRead::Ok);
  22865. EXPECT_EQ(ws::Opcode::Text, opcode);
  22866. EXPECT_EQ("abc", payload);
  22867. }
  22868. }
  22869. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22870. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22871. // Valid UTF-8
  22872. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22873. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22874. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22875. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22876. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22877. // Invalid UTF-8
  22878. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22879. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22880. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22881. EXPECT_FALSE(
  22882. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22883. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22884. }
  22885. TEST(WebSocketTest, ConnectAndDisconnect) {
  22886. Server svr;
  22887. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22888. std::string msg;
  22889. while (ws.read(msg)) {}
  22890. });
  22891. auto port = svr.bind_to_any_port(HOST);
  22892. std::thread t([&]() { svr.listen_after_bind(); });
  22893. svr.wait_until_ready();
  22894. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22895. auto res = client.connect();
  22896. ASSERT_TRUE(res);
  22897. EXPECT_EQ(Error::Success, res.error());
  22898. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22899. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22900. EXPECT_TRUE(client.is_open());
  22901. client.close();
  22902. EXPECT_FALSE(client.is_open());
  22903. svr.stop();
  22904. t.join();
  22905. }
  22906. TEST(WebSocketTest, ValidURL) {
  22907. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22908. EXPECT_TRUE(ws1.is_valid());
  22909. ws::WebSocketClient ws2("ws://example.com/path");
  22910. EXPECT_TRUE(ws2.is_valid());
  22911. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22912. EXPECT_TRUE(ws3.is_valid());
  22913. #ifdef CPPHTTPLIB_SSL_ENABLED
  22914. ws::WebSocketClient wss1("wss://example.com/path");
  22915. EXPECT_TRUE(wss1.is_valid());
  22916. ws::WebSocketClient wss2("wss://example.com:443/path");
  22917. EXPECT_TRUE(wss2.is_valid());
  22918. #endif
  22919. }
  22920. TEST(WebSocketTest, InvalidURL) {
  22921. // No scheme
  22922. ws::WebSocketClient ws1("localhost:8080/path");
  22923. EXPECT_FALSE(ws1.is_valid());
  22924. // No path
  22925. ws::WebSocketClient ws2("ws://localhost:8080");
  22926. EXPECT_FALSE(ws2.is_valid());
  22927. // Empty string
  22928. ws::WebSocketClient ws3("");
  22929. EXPECT_FALSE(ws3.is_valid());
  22930. // Missing host
  22931. ws::WebSocketClient ws4("ws://:8080/path");
  22932. EXPECT_FALSE(ws4.is_valid());
  22933. // Port number overflow — should not crash
  22934. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22935. EXPECT_FALSE(ws5.is_valid());
  22936. // Port out of range
  22937. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22938. EXPECT_FALSE(ws6.is_valid());
  22939. }
  22940. TEST(WebSocketTest, UnsupportedScheme) {
  22941. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22942. ws::WebSocketClient ws1("http://localhost:8080/path");
  22943. EXPECT_FALSE(ws1.is_valid());
  22944. ws::WebSocketClient ws2("https://localhost:8080/path");
  22945. EXPECT_FALSE(ws2.is_valid());
  22946. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22947. EXPECT_FALSE(ws3.is_valid());
  22948. #else
  22949. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22950. std::invalid_argument);
  22951. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22952. std::invalid_argument);
  22953. #endif
  22954. }
  22955. TEST(WebSocketTest, ConnectWhenInvalid) {
  22956. ws::WebSocketClient ws("not a valid url");
  22957. EXPECT_FALSE(ws.is_valid());
  22958. auto res = ws.connect();
  22959. EXPECT_FALSE(res);
  22960. EXPECT_EQ(Error::Connection, res.error());
  22961. EXPECT_EQ(-1, res.status());
  22962. }
  22963. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22964. // Grab a port that is free, then close it again so nothing listens there
  22965. Server svr;
  22966. auto port = svr.bind_to_any_port(HOST);
  22967. svr.stop();
  22968. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22969. auto res = client.connect();
  22970. ASSERT_FALSE(res);
  22971. EXPECT_EQ(Error::Connection, res.error());
  22972. EXPECT_EQ(-1, res.status());
  22973. }
  22974. TEST(WebSocketTest, DefaultPort) {
  22975. ws::WebSocketClient ws1("ws://example.com/path");
  22976. EXPECT_TRUE(ws1.is_valid());
  22977. // ws:// defaults to port 80 (verified by successful parse)
  22978. #ifdef CPPHTTPLIB_SSL_ENABLED
  22979. ws::WebSocketClient ws2("wss://example.com/path");
  22980. EXPECT_TRUE(ws2.is_valid());
  22981. // wss:// defaults to port 443 (verified by successful parse)
  22982. #endif
  22983. }
  22984. TEST(WebSocketTest, IPv6LiteralAddress) {
  22985. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22986. EXPECT_TRUE(ws1.is_valid());
  22987. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22988. EXPECT_TRUE(ws2.is_valid());
  22989. }
  22990. TEST(WebSocketTest, ComplexPath) {
  22991. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22992. EXPECT_TRUE(ws1.is_valid());
  22993. ws::WebSocketClient ws2("ws://localhost:8080/");
  22994. EXPECT_TRUE(ws2.is_valid());
  22995. }
  22996. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  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 another_host = "example.com";
  23006. auto wrong_ip = "192.0.2.1";
  23007. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23008. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23009. ASSERT_TRUE(client.connect());
  23010. EXPECT_TRUE(client.is_open());
  23011. client.close();
  23012. svr.stop();
  23013. t.join();
  23014. }
  23015. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23016. Server svr;
  23017. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23018. std::string msg;
  23019. while (ws.read(msg)) {}
  23020. });
  23021. auto port = svr.bind_to_any_port(HOST);
  23022. std::thread t([&]() { svr.listen_after_bind(); });
  23023. svr.wait_until_ready();
  23024. auto wrong_ip = "192.0.2.1";
  23025. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23026. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23027. client.set_connection_timeout(1);
  23028. client.set_read_timeout(1);
  23029. client.set_write_timeout(1);
  23030. EXPECT_FALSE(client.connect());
  23031. EXPECT_FALSE(client.is_open());
  23032. svr.stop();
  23033. t.join();
  23034. }
  23035. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23036. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23037. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23038. // (RFC 6761) is only a map key and the Host header value.
  23039. auto host = "target.invalid";
  23040. Server svr;
  23041. std::string received_host;
  23042. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23043. received_host = req.get_header_value("Host");
  23044. std::string msg;
  23045. while (ws.read(msg)) {}
  23046. });
  23047. auto port = svr.bind_to_any_port(HOST);
  23048. std::thread t([&]() { svr.listen_after_bind(); });
  23049. // ASSERT_* below returns from the test body, which would leave t joinable
  23050. // and make ~thread call std::terminate.
  23051. auto se = detail::scope_exit([&] {
  23052. svr.stop();
  23053. if (t.joinable()) { t.join(); }
  23054. });
  23055. svr.wait_until_ready();
  23056. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23057. std::to_string(port) + "/ws");
  23058. client.set_hostname_addr_map({{host, HOST}});
  23059. ASSERT_TRUE(client.connect());
  23060. EXPECT_TRUE(client.is_open());
  23061. client.close();
  23062. svr.stop();
  23063. t.join();
  23064. // The mapping only redirects the connection; the identity stays host_.
  23065. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23066. }
  23067. class WebSocketIntegrationTest : public ::testing::Test {
  23068. protected:
  23069. void SetUp() override {
  23070. server_ = httplib::detail::make_unique<Server>();
  23071. setup_server();
  23072. start_server();
  23073. }
  23074. void TearDown() override {
  23075. server_->stop();
  23076. if (server_thread_.joinable()) { server_thread_.join(); }
  23077. }
  23078. void setup_server() {
  23079. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23080. std::string msg;
  23081. ws::ReadResult ret;
  23082. while ((ret = ws.read(msg))) {
  23083. if (ret == ws::Binary) {
  23084. ws.send(msg.data(), msg.size());
  23085. } else {
  23086. ws.send(msg);
  23087. }
  23088. }
  23089. });
  23090. server_->WebSocket("/ws-echo-string",
  23091. [](const Request &, ws::WebSocket &ws) {
  23092. std::string msg;
  23093. while (ws.read(msg)) {
  23094. ws.send("echo: " + msg);
  23095. }
  23096. });
  23097. server_->WebSocket(
  23098. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23099. // Echo back request metadata
  23100. ws.send("path:" + req.path);
  23101. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23102. std::string msg;
  23103. while (ws.read(msg)) {}
  23104. });
  23105. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23106. std::string msg;
  23107. ws.read(msg); // wait for a message
  23108. ws.close();
  23109. });
  23110. server_->WebSocket("/ws-close-status",
  23111. [](const Request &, ws::WebSocket &ws) {
  23112. std::string msg;
  23113. ws.read(msg); // wait for a message
  23114. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23115. });
  23116. server_->WebSocket(
  23117. "/ws-subprotocol",
  23118. [](const Request &, ws::WebSocket &ws) {
  23119. std::string msg;
  23120. while (ws.read(msg)) {
  23121. ws.send(msg);
  23122. }
  23123. },
  23124. [](const std::vector<std::string> &protocols) -> std::string {
  23125. for (const auto &p : protocols) {
  23126. if (p == "graphql-ws") { return p; }
  23127. }
  23128. return "";
  23129. });
  23130. server_->WebSocket(
  23131. "/ws-subprotocol-unoffered",
  23132. [](const Request &, ws::WebSocket &ws) {
  23133. std::string msg;
  23134. while (ws.read(msg)) {
  23135. ws.send(msg);
  23136. }
  23137. },
  23138. [](const std::vector<std::string> &) -> std::string {
  23139. return "admin";
  23140. });
  23141. }
  23142. void start_server() {
  23143. port_ = server_->bind_to_any_port(HOST);
  23144. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23145. server_->wait_until_ready();
  23146. }
  23147. std::unique_ptr<Server> server_;
  23148. std::thread server_thread_;
  23149. int port_ = 0;
  23150. };
  23151. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23152. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23153. "/ws-echo");
  23154. ASSERT_TRUE(client.connect());
  23155. ASSERT_TRUE(client.is_open());
  23156. ASSERT_TRUE(client.send("Hello WebSocket"));
  23157. std::string msg;
  23158. EXPECT_EQ(ws::Text, client.read(msg));
  23159. EXPECT_EQ("Hello WebSocket", msg);
  23160. client.close();
  23161. }
  23162. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23163. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23164. "/ws-echo");
  23165. ASSERT_TRUE(client.connect());
  23166. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23167. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23168. std::string msg;
  23169. EXPECT_EQ(ws::Binary, client.read(msg));
  23170. EXPECT_EQ(binary_data, msg);
  23171. client.close();
  23172. }
  23173. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23174. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23175. "/ws-echo");
  23176. ASSERT_TRUE(client.connect());
  23177. for (int i = 0; i < 10; i++) {
  23178. auto text = "message " + std::to_string(i);
  23179. ASSERT_TRUE(client.send(text));
  23180. std::string msg;
  23181. ASSERT_TRUE(client.read(msg));
  23182. EXPECT_EQ(text, msg);
  23183. }
  23184. client.close();
  23185. }
  23186. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23187. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23188. "/ws-close");
  23189. ASSERT_TRUE(client.connect());
  23190. // Send a message to trigger the server to close
  23191. ASSERT_TRUE(client.send("trigger close"));
  23192. // The server will close, so read should return false
  23193. std::string msg;
  23194. EXPECT_FALSE(client.read(msg));
  23195. EXPECT_FALSE(client.is_open());
  23196. }
  23197. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23198. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23199. "/ws-echo");
  23200. ASSERT_TRUE(client.connect());
  23201. // 128KB message
  23202. std::string large_data(128 * 1024, 'X');
  23203. ASSERT_TRUE(client.send(large_data));
  23204. std::string msg;
  23205. ASSERT_TRUE(client.read(msg));
  23206. EXPECT_EQ(large_data, msg);
  23207. client.close();
  23208. }
  23209. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23210. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23211. "/ws-echo");
  23212. ASSERT_TRUE(client.connect());
  23213. const int num_threads = 4;
  23214. std::vector<std::thread> threads;
  23215. std::atomic<int> send_count{0};
  23216. for (int t = 0; t < num_threads; t++) {
  23217. threads.emplace_back([&client, &send_count, t]() {
  23218. for (int i = 0; i < 5; i++) {
  23219. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23220. if (client.send(text)) { send_count++; }
  23221. }
  23222. });
  23223. }
  23224. for (auto &th : threads) {
  23225. th.join();
  23226. }
  23227. int received = 0;
  23228. std::string msg;
  23229. while (received < send_count.load()) {
  23230. if (!client.read(msg)) { break; }
  23231. received++;
  23232. }
  23233. EXPECT_EQ(send_count.load(), received);
  23234. client.close();
  23235. }
  23236. TEST_F(WebSocketIntegrationTest, ReadString) {
  23237. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23238. "/ws-echo-string");
  23239. ASSERT_TRUE(client.connect());
  23240. ASSERT_TRUE(client.send("hello"));
  23241. std::string msg;
  23242. ASSERT_TRUE(client.read(msg));
  23243. EXPECT_EQ("echo: hello", msg);
  23244. ASSERT_TRUE(client.send("world"));
  23245. ASSERT_TRUE(client.read(msg));
  23246. EXPECT_EQ("echo: world", msg);
  23247. client.close();
  23248. }
  23249. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23250. Headers headers = {{"X-Test-Header", "test-value"}};
  23251. ws::WebSocketClient client(
  23252. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23253. ASSERT_TRUE(client.connect());
  23254. std::string msg;
  23255. ASSERT_TRUE(client.read(msg));
  23256. EXPECT_EQ("path:/ws-request-info", msg);
  23257. ASSERT_TRUE(client.read(msg));
  23258. EXPECT_EQ("header:test-value", msg);
  23259. client.close();
  23260. }
  23261. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23262. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23263. "/ws-echo");
  23264. client.set_read_timeout(1, 0); // 1 second
  23265. ASSERT_TRUE(client.connect());
  23266. // Don't send anything — server echo handler waits for a message, so read()
  23267. // should time out. The connection survives it: nothing was consumed.
  23268. std::string msg;
  23269. EXPECT_EQ(client.read(msg), ws::Timeout);
  23270. EXPECT_TRUE(client.is_open());
  23271. // And it is still usable afterwards.
  23272. EXPECT_TRUE(client.send("after timeout"));
  23273. EXPECT_EQ(client.read(msg), ws::Text);
  23274. EXPECT_EQ(msg, "after timeout");
  23275. }
  23276. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23277. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23278. "/ws-echo");
  23279. client.set_read_timeout(1, 0);
  23280. ASSERT_TRUE(client.connect());
  23281. ASSERT_TRUE(client.send("first"));
  23282. std::string msg;
  23283. ASSERT_EQ(client.read(msg), ws::Text);
  23284. ASSERT_EQ(msg, "first");
  23285. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23286. // not be used with a read timeout: it would reprocess the previous message.
  23287. EXPECT_EQ(client.read(msg), ws::Timeout);
  23288. EXPECT_EQ(msg, "first");
  23289. }
  23290. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23291. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23292. "/ws-echo");
  23293. ASSERT_TRUE(client.connect());
  23294. // Setting it once the connection is open reaches the live stream, not just
  23295. // the seed for the next connect().
  23296. client.set_read_timeout(1, 0);
  23297. std::string msg;
  23298. EXPECT_EQ(client.read(msg), ws::Timeout);
  23299. EXPECT_TRUE(client.is_open());
  23300. }
  23301. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23302. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23303. "/ws-echo");
  23304. client.set_read_timeout(5, 0);
  23305. ASSERT_TRUE(client.connect());
  23306. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23307. // The server should reject it and close the connection.
  23308. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23309. client.send(oversized);
  23310. // The server's read() should have failed due to payload limit,
  23311. // so our read() should return false (connection closed).
  23312. std::string msg;
  23313. EXPECT_FALSE(client.read(msg));
  23314. }
  23315. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23316. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23317. "/ws-echo");
  23318. client.set_read_timeout(10, 0);
  23319. ASSERT_TRUE(client.connect());
  23320. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23321. // This should succeed.
  23322. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23323. ASSERT_TRUE(client.send(at_limit));
  23324. std::string msg;
  23325. ASSERT_TRUE(client.read(msg));
  23326. EXPECT_EQ(at_limit.size(), msg.size());
  23327. client.close();
  23328. }
  23329. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23330. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23331. "/nonexistent");
  23332. auto res = client.connect();
  23333. EXPECT_FALSE(res);
  23334. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23335. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23336. EXPECT_FALSE(client.is_open());
  23337. }
  23338. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23339. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23340. "/ws-echo");
  23341. ASSERT_TRUE(client.connect());
  23342. ASSERT_TRUE(client.send(""));
  23343. std::string msg;
  23344. EXPECT_EQ(ws::Text, client.read(msg));
  23345. EXPECT_EQ("", msg);
  23346. client.close();
  23347. }
  23348. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23349. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23350. "/ws-echo");
  23351. // First connection
  23352. ASSERT_TRUE(client.connect());
  23353. ASSERT_TRUE(client.send("first"));
  23354. std::string msg;
  23355. ASSERT_TRUE(client.read(msg));
  23356. EXPECT_EQ("first", msg);
  23357. client.close();
  23358. EXPECT_FALSE(client.is_open());
  23359. // Reconnect using the same client object
  23360. ASSERT_TRUE(client.connect());
  23361. ASSERT_TRUE(client.is_open());
  23362. ASSERT_TRUE(client.send("second"));
  23363. ASSERT_TRUE(client.read(msg));
  23364. EXPECT_EQ("second", msg);
  23365. client.close();
  23366. }
  23367. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23368. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23369. "/ws-close-status");
  23370. ASSERT_TRUE(client.connect());
  23371. // Trigger the server to close with GoingAway status
  23372. ASSERT_TRUE(client.send("trigger"));
  23373. // read() should return false after receiving the close frame
  23374. std::string msg;
  23375. EXPECT_FALSE(client.read(msg));
  23376. EXPECT_FALSE(client.is_open());
  23377. }
  23378. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23379. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23380. "/ws-echo");
  23381. ASSERT_TRUE(client.connect());
  23382. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23383. EXPECT_FALSE(client.is_open());
  23384. }
  23385. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23386. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23387. ws::WebSocketClient client(
  23388. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23389. ASSERT_TRUE(client.connect());
  23390. // Server should have selected graphql-ws
  23391. EXPECT_EQ("graphql-ws", client.subprotocol());
  23392. client.close();
  23393. }
  23394. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23395. Headers headers;
  23396. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23397. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23398. ws::WebSocketClient client(
  23399. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23400. ASSERT_TRUE(client.connect());
  23401. // The offer on the second field line counts too, so graphql-ws is selected
  23402. EXPECT_EQ("graphql-ws", client.subprotocol());
  23403. client.close();
  23404. }
  23405. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23406. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23407. ws::WebSocketClient client(
  23408. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23409. ASSERT_TRUE(client.connect());
  23410. // Server should not have selected any subprotocol
  23411. EXPECT_TRUE(client.subprotocol().empty());
  23412. client.close();
  23413. }
  23414. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23415. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23416. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23417. "/ws-subprotocol-unoffered",
  23418. headers);
  23419. ASSERT_TRUE(client.connect());
  23420. EXPECT_TRUE(client.subprotocol().empty());
  23421. client.close();
  23422. }
  23423. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23424. // Connect without requesting any subprotocol
  23425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23426. "/ws-subprotocol");
  23427. ASSERT_TRUE(client.connect());
  23428. EXPECT_TRUE(client.subprotocol().empty());
  23429. client.close();
  23430. }
  23431. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23432. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23433. "/ws-echo");
  23434. client.set_tcp_nodelay(true);
  23435. client.set_connection_timeout(3, 0);
  23436. bool socket_options_called = false;
  23437. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23438. ASSERT_TRUE(client.connect());
  23439. ASSERT_TRUE(client.is_open());
  23440. EXPECT_TRUE(socket_options_called);
  23441. ASSERT_TRUE(client.send("hello"));
  23442. std::string msg;
  23443. auto result = client.read(msg);
  23444. EXPECT_EQ(result, ws::ReadResult::Text);
  23445. EXPECT_EQ(msg, "hello");
  23446. client.close();
  23447. }
  23448. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23449. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23450. "/ws-echo");
  23451. client.set_connection_timeout(std::chrono::seconds(3));
  23452. client.set_write_timeout(std::chrono::seconds(3));
  23453. // A sub-second remainder exercises the seconds/microseconds split.
  23454. client.set_read_timeout(std::chrono::milliseconds(1500));
  23455. ASSERT_TRUE(client.connect());
  23456. auto start = std::chrono::steady_clock::now();
  23457. std::string msg;
  23458. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23459. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23460. std::chrono::steady_clock::now() - start)
  23461. .count();
  23462. // Above 1s so that dropping the microseconds half of the split fails here.
  23463. // Ignoring the setter altogether would not reach this line at all: a client
  23464. // waits forever by default.
  23465. EXPECT_GE(elapsed, 1400);
  23466. EXPECT_LT(elapsed, 30000);
  23467. }
  23468. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23469. Server svr;
  23470. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23471. if (!req.has_header("Authorization")) {
  23472. res.status = StatusCode::Unauthorized_401;
  23473. res.set_content("Unauthorized", "text/plain");
  23474. return Server::HandlerResponse::Handled;
  23475. }
  23476. return Server::HandlerResponse::Unhandled;
  23477. });
  23478. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23479. std::string msg;
  23480. while (ws.read(msg)) {
  23481. ws.send(msg);
  23482. }
  23483. });
  23484. auto port = svr.bind_to_any_port("localhost");
  23485. std::thread t([&]() { svr.listen_after_bind(); });
  23486. svr.wait_until_ready();
  23487. // Without Authorization header - should be rejected before upgrade
  23488. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23489. EXPECT_FALSE(client1.connect());
  23490. // The rejection is framed like any other HTTP response
  23491. {
  23492. Client cli("localhost", port);
  23493. Headers headers = {{"Upgrade", "websocket"},
  23494. {"Connection", "Upgrade"},
  23495. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23496. {"Sec-WebSocket-Version", "13"}};
  23497. auto res = cli.Get("/ws", headers);
  23498. ASSERT_TRUE(res);
  23499. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23500. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23501. EXPECT_EQ("Unauthorized", res->body);
  23502. }
  23503. // With Authorization header - should succeed
  23504. Headers headers = {{"Authorization", "Bearer token123"}};
  23505. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23506. headers);
  23507. ASSERT_TRUE(client2.connect());
  23508. ASSERT_TRUE(client2.send("hello"));
  23509. std::string msg;
  23510. ASSERT_TRUE(client2.read(msg));
  23511. EXPECT_EQ("hello", msg);
  23512. client2.close();
  23513. svr.stop();
  23514. t.join();
  23515. }
  23516. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23517. Server svr;
  23518. std::atomic<int> pre_routing_calls{0};
  23519. std::atomic<int> pre_request_calls{0};
  23520. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23521. pre_routing_calls++;
  23522. if (req.path == "/handled") {
  23523. res.set_content("handled", "text/plain");
  23524. return Server::HandlerResponse::Handled;
  23525. }
  23526. return Server::HandlerResponse::Unhandled;
  23527. });
  23528. svr.set_pre_request_handler([&](const Request &, Response &) {
  23529. pre_request_calls++;
  23530. return Server::HandlerResponse::Unhandled;
  23531. });
  23532. svr.Get("/http", [](const Request &, Response &res) {
  23533. res.set_content("http", "text/plain");
  23534. });
  23535. svr.WebSocket("/ws",
  23536. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23537. auto port = svr.bind_to_any_port("localhost");
  23538. std::thread t([&]() { svr.listen_after_bind(); });
  23539. auto se = detail::scope_exit([&] {
  23540. svr.stop();
  23541. t.join();
  23542. });
  23543. svr.wait_until_ready();
  23544. Headers upgrade = {{"Upgrade", "websocket"},
  23545. {"Connection", "Upgrade"},
  23546. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23547. {"Sec-WebSocket-Version", "13"}};
  23548. auto get = [&](const char *path) {
  23549. pre_routing_calls = 0;
  23550. return Client("localhost", port).Get(path, upgrade);
  23551. };
  23552. // No WebSocket route, but an HTTP one
  23553. auto res = get("/http");
  23554. ASSERT_TRUE(res);
  23555. EXPECT_EQ(StatusCode::OK_200, res->status);
  23556. EXPECT_EQ("http", res->body);
  23557. EXPECT_EQ(1, pre_routing_calls);
  23558. EXPECT_EQ(1, pre_request_calls);
  23559. // No route at all
  23560. res = get("/none");
  23561. ASSERT_TRUE(res);
  23562. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23563. EXPECT_EQ(1, pre_routing_calls);
  23564. // Answered by the pre-routing handler
  23565. res = get("/handled");
  23566. ASSERT_TRUE(res);
  23567. EXPECT_EQ(StatusCode::OK_200, res->status);
  23568. EXPECT_EQ("handled", res->body);
  23569. EXPECT_EQ(1, pre_routing_calls);
  23570. // A WebSocket route
  23571. pre_routing_calls = 0;
  23572. pre_request_calls = 0;
  23573. {
  23574. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23575. "/ws");
  23576. ASSERT_TRUE(client.connect());
  23577. std::string msg;
  23578. ASSERT_TRUE(client.read(msg));
  23579. EXPECT_EQ("ws", msg);
  23580. client.close();
  23581. }
  23582. EXPECT_EQ(1, pre_routing_calls);
  23583. EXPECT_EQ(1, pre_request_calls);
  23584. }
  23585. // An upgrade request answered by a hook leaves its body unread, so that body
  23586. // must not be served as the next request on the connection.
  23587. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23588. Server svr;
  23589. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23590. if (req.path == "/pre-routing") {
  23591. res.set_content("pre-routing", "text/plain");
  23592. return Server::HandlerResponse::Handled;
  23593. }
  23594. return Server::HandlerResponse::Unhandled;
  23595. });
  23596. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23597. if (req.matched_route == "/pre-request") {
  23598. res.set_content("pre-request", "text/plain");
  23599. return Server::HandlerResponse::Handled;
  23600. }
  23601. return Server::HandlerResponse::Unhandled;
  23602. });
  23603. svr.Get("/smuggled", [](const Request &, Response &res) {
  23604. res.set_content("smuggled", "text/plain");
  23605. });
  23606. svr.WebSocket("/pre-request",
  23607. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23608. auto port = svr.bind_to_any_port(HOST);
  23609. std::thread t([&]() { svr.listen_after_bind(); });
  23610. auto se = detail::scope_exit([&] {
  23611. svr.stop();
  23612. t.join();
  23613. });
  23614. svr.wait_until_ready();
  23615. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23616. for (auto path : {"/pre-routing", "/pre-request"}) {
  23617. std::string req = std::string("GET ") + path +
  23618. " HTTP/1.1\r\n"
  23619. "Host: localhost\r\n"
  23620. "Upgrade: websocket\r\n"
  23621. "Connection: Upgrade\r\n"
  23622. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23623. "Sec-WebSocket-Version: 13\r\n"
  23624. "Content-Length: " +
  23625. std::to_string(body.size()) + "\r\n\r\n" + body;
  23626. std::string res;
  23627. ASSERT_TRUE(send_request(5, req, &res, port));
  23628. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23629. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23630. // Only one response, and the body was not served as a request
  23631. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23632. }
  23633. }
  23634. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23635. Server svr;
  23636. std::atomic<int> pre_request_calls{0};
  23637. std::atomic<bool> route_matched{false};
  23638. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23639. pre_request_calls++;
  23640. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23641. if (req.get_header_value("Authorization") != "Bearer token123") {
  23642. res.status = StatusCode::Unauthorized_401;
  23643. res.set_content("Unauthorized", "text/plain");
  23644. return Server::HandlerResponse::Handled;
  23645. }
  23646. return Server::HandlerResponse::Unhandled;
  23647. });
  23648. std::atomic<bool> handler_called{false};
  23649. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23650. handler_called = true;
  23651. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23652. });
  23653. auto port = svr.bind_to_any_port("localhost");
  23654. std::thread t([&]() { svr.listen_after_bind(); });
  23655. svr.wait_until_ready();
  23656. // Without Authorization header - should be rejected before upgrade
  23657. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23658. "/ws/1");
  23659. EXPECT_FALSE(client1.connect());
  23660. EXPECT_FALSE(handler_called);
  23661. EXPECT_EQ(1, pre_request_calls);
  23662. EXPECT_TRUE(route_matched);
  23663. // The rejection is an ordinary HTTP response, not a protocol switch
  23664. {
  23665. Client cli("localhost", port);
  23666. Headers headers = {{"Upgrade", "websocket"},
  23667. {"Connection", "Upgrade"},
  23668. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23669. {"Sec-WebSocket-Version", "13"}};
  23670. auto res = cli.Get("/ws/1", headers);
  23671. ASSERT_TRUE(res);
  23672. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23673. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23674. EXPECT_EQ("Unauthorized", res->body);
  23675. }
  23676. EXPECT_FALSE(handler_called);
  23677. // With Authorization header - should succeed
  23678. Headers headers = {{"Authorization", "Bearer token123"}};
  23679. ws::WebSocketClient client2(
  23680. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23681. ASSERT_TRUE(client2.connect());
  23682. std::string msg;
  23683. ASSERT_TRUE(client2.read(msg));
  23684. EXPECT_EQ("/ws/:id 2", msg);
  23685. EXPECT_TRUE(handler_called);
  23686. client2.close();
  23687. svr.stop();
  23688. t.join();
  23689. }
  23690. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23691. Server svr;
  23692. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23693. // A read timeout is how a handler gets control back. Without it, a handler
  23694. // parked in read() can never write on the connection it is reading.
  23695. ws.set_read_timeout(std::chrono::milliseconds(100));
  23696. std::string msg;
  23697. while (ws.is_open()) {
  23698. auto r = ws.read(msg);
  23699. if (r == httplib::ws::Timeout) {
  23700. ws.send("tick");
  23701. continue;
  23702. }
  23703. if (r == httplib::ws::Fail) { break; }
  23704. ws.send(msg);
  23705. }
  23706. });
  23707. auto port = svr.bind_to_any_port("localhost");
  23708. std::thread t([&]() { svr.listen_after_bind(); });
  23709. svr.wait_until_ready();
  23710. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23711. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23712. ASSERT_TRUE(client.connect());
  23713. // The client sends nothing, so anything it receives came out of the
  23714. // handler's timeout path.
  23715. std::string msg;
  23716. ASSERT_EQ(client.read(msg), ws::Text);
  23717. EXPECT_EQ("tick", msg);
  23718. client.close();
  23719. svr.stop();
  23720. t.join();
  23721. }
  23722. // Stream::read may return fewer bytes than asked for. This is that contract at
  23723. // its worst -- one byte per call -- which is what a frame header straddling a
  23724. // read buffer's boundary looks like to the frame parser.
  23725. class WsByteAtATimeStream : public Stream {
  23726. public:
  23727. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23728. bool is_readable() const override { return true; }
  23729. bool wait_readable() const override { return true; }
  23730. bool wait_writable() const override { return true; }
  23731. ssize_t read(char *ptr, size_t size) override {
  23732. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23733. *ptr = data_[pos_++];
  23734. return 1;
  23735. }
  23736. ssize_t write(const char *, size_t size) override {
  23737. return static_cast<ssize_t>(size);
  23738. }
  23739. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23740. ip = "127.0.0.1";
  23741. port = 0;
  23742. }
  23743. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23744. ip = "127.0.0.1";
  23745. port = 0;
  23746. }
  23747. socket_t socket() const override { return INVALID_SOCKET; }
  23748. time_t duration() const override { return 0; }
  23749. private:
  23750. std::string data_;
  23751. size_t pos_ = 0;
  23752. };
  23753. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23754. // The payload uses the 16-bit extended length, so the header, the length
  23755. // and the mask key are all multi-byte fields here. Each used to be read
  23756. // with a single read() call, which fails as soon as one is split. The
  23757. // payload is also a little over one read chunk, so it is read in two.
  23758. std::string body;
  23759. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23760. body += static_cast<char>(i % 251);
  23761. }
  23762. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23763. std::string frame;
  23764. frame += static_cast<char>(0x81); // FIN + Text
  23765. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23766. frame += static_cast<char>(body.size() >> 8);
  23767. frame += static_cast<char>(body.size() & 0xff);
  23768. for (size_t i = 0; i < 4; i++) {
  23769. frame += static_cast<char>(mask[i]);
  23770. }
  23771. for (size_t i = 0; i < body.size(); i++) {
  23772. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23773. }
  23774. WsByteAtATimeStream strm(frame);
  23775. ws::Opcode opcode;
  23776. std::string payload;
  23777. bool fin = false;
  23778. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23779. /*expect_masked=*/true, body.size()),
  23780. ws::impl::FrameRead::Ok);
  23781. EXPECT_TRUE(fin);
  23782. EXPECT_EQ(opcode, ws::Opcode::Text);
  23783. EXPECT_EQ(payload, body);
  23784. }
  23785. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23786. std::string body(2000, 'x');
  23787. std::string frame;
  23788. frame += static_cast<char>(0x82); // FIN + Binary
  23789. frame += static_cast<char>(126); // 16-bit length follows
  23790. frame += static_cast<char>(body.size() >> 8);
  23791. frame += static_cast<char>(body.size() & 0xff);
  23792. frame += body;
  23793. detail::BufferStream strm;
  23794. strm.write(frame.data(), frame.size());
  23795. ws::Opcode opcode;
  23796. std::string payload;
  23797. bool fin;
  23798. EXPECT_EQ(
  23799. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23800. ws::impl::FrameRead::Ok);
  23801. EXPECT_EQ(body, payload);
  23802. }
  23803. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23804. // The header announces the largest payload allowed, and only 3 bytes of it
  23805. // ever arrive.
  23806. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23807. std::string frame;
  23808. frame += static_cast<char>(0x82); // FIN + Binary
  23809. frame += static_cast<char>(127); // 64-bit length follows
  23810. for (int shift = 56; shift >= 0; shift -= 8) {
  23811. frame += static_cast<char>((len >> shift) & 0xff);
  23812. }
  23813. frame += "abc";
  23814. detail::BufferStream strm;
  23815. strm.write(frame.data(), frame.size());
  23816. ws::Opcode opcode;
  23817. std::string payload;
  23818. bool fin;
  23819. EXPECT_EQ(
  23820. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23821. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23822. ws::impl::FrameRead::Fail);
  23823. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23824. }
  23825. TEST(WebSocketTest, QueryStringInHandshake) {
  23826. Server svr;
  23827. std::mutex mtx;
  23828. std::string received_target;
  23829. std::string received_token;
  23830. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23831. {
  23832. std::lock_guard<std::mutex> lock(mtx);
  23833. received_target = req.target;
  23834. if (req.has_param("token")) {
  23835. received_token = req.get_param_value("token");
  23836. }
  23837. }
  23838. std::string msg;
  23839. while (ws.read(msg)) {
  23840. ws.send(msg);
  23841. }
  23842. });
  23843. auto port = svr.bind_to_any_port("localhost");
  23844. std::thread t([&]() { svr.listen_after_bind(); });
  23845. svr.wait_until_ready();
  23846. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23847. "/ws?token=ABC&session=123");
  23848. ASSERT_TRUE(client.connect());
  23849. // Round-trip ensures the handler has run and captured the request.
  23850. ASSERT_TRUE(client.send("hello"));
  23851. std::string msg;
  23852. ASSERT_TRUE(client.read(msg));
  23853. EXPECT_EQ("hello", msg);
  23854. client.close();
  23855. {
  23856. std::lock_guard<std::mutex> lock(mtx);
  23857. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23858. EXPECT_EQ("ABC", received_token);
  23859. }
  23860. svr.stop();
  23861. t.join();
  23862. }
  23863. // Run a handshake against a throwaway server and hand the request the server
  23864. // received back to the caller, so tests can assert on the headers the client
  23865. // actually put on the wire.
  23866. static void capture_websocket_handshake_request(
  23867. const Headers &client_headers,
  23868. std::function<void(const Request &, int port)> verify) {
  23869. Server svr;
  23870. std::mutex mtx;
  23871. Request received;
  23872. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23873. {
  23874. std::lock_guard<std::mutex> lock(mtx);
  23875. received = req;
  23876. }
  23877. std::string msg;
  23878. while (ws.read(msg)) {
  23879. ws.send(msg);
  23880. }
  23881. });
  23882. auto port = svr.bind_to_any_port("localhost");
  23883. std::thread t([&]() { svr.listen_after_bind(); });
  23884. auto se = detail::scope_exit([&] {
  23885. svr.stop();
  23886. t.join();
  23887. });
  23888. svr.wait_until_ready();
  23889. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23890. client_headers);
  23891. ASSERT_TRUE(client.connect());
  23892. ASSERT_TRUE(client.send("hello"));
  23893. std::string msg;
  23894. ASSERT_TRUE(client.read(msg));
  23895. client.close();
  23896. {
  23897. std::lock_guard<std::mutex> lock(mtx);
  23898. verify(received, port);
  23899. }
  23900. }
  23901. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23902. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23903. // Non-default port must be present in the Host header. Default ports
  23904. // (80/443) are omitted; that logic is covered by
  23905. // MakeHostAndPortStringTest.
  23906. EXPECT_EQ("localhost:" + std::to_string(port),
  23907. req.get_header_value("Host"));
  23908. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23909. req.get_header_value("User-Agent"));
  23910. EXPECT_FALSE(req.has_header("Accept"));
  23911. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23912. EXPECT_FALSE(req.has_header("Content-Length"));
  23913. });
  23914. }
  23915. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23916. capture_websocket_handshake_request(
  23917. {{"Host", "example.com"},
  23918. {"User-Agent", "custom-agent"},
  23919. {"X-Custom", "value"}},
  23920. [](const Request &req, int) {
  23921. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23922. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23923. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23924. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23925. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23926. });
  23927. }
  23928. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23929. capture_websocket_handshake_request(
  23930. {{"Upgrade", "bogus"},
  23931. {"Connection", "close"},
  23932. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23933. {"Sec-WebSocket-Version", "8"}},
  23934. [](const Request &req, int) {
  23935. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23936. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23937. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23938. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23939. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23940. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23941. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23942. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23943. req.get_header_value("Sec-WebSocket-Key"));
  23944. });
  23945. }
  23946. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23947. // A header the client refuses to send must abort the handshake before any
  23948. // part of it reaches the wire; a lone request line would otherwise sit in
  23949. // the peer's buffer as a truncated request.
  23950. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23951. ASSERT_NE(INVALID_SOCKET, srv);
  23952. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23953. sockaddr_in addr{};
  23954. addr.sin_family = AF_INET;
  23955. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23956. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23957. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23958. ASSERT_EQ(0, ::listen(srv, 1));
  23959. sockaddr_in bound{};
  23960. socklen_t bound_len = sizeof(bound);
  23961. ASSERT_EQ(
  23962. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23963. auto port = ntohs(bound.sin_port);
  23964. ssize_t received = -1;
  23965. std::thread t([&] {
  23966. // Bound every blocking call so a regression fails the test with a bad
  23967. // value instead of hanging the suite.
  23968. fd_set rfds;
  23969. FD_ZERO(&rfds);
  23970. FD_SET(srv, &rfds);
  23971. timeval tv{5, 0};
  23972. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23973. 0) {
  23974. return;
  23975. }
  23976. sockaddr_in cli_addr{};
  23977. socklen_t cli_len = sizeof(cli_addr);
  23978. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23979. if (cli == INVALID_SOCKET) { return; }
  23980. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23981. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23982. char buf[4096];
  23983. received = ::recv(cli, buf, sizeof(buf), 0);
  23984. });
  23985. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23986. // connect() has already shut the socket down by the time it returns false,
  23987. // so the peer sees EOF without waiting for the client to be destroyed.
  23988. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23989. {{"X-Bad", "a\r\nInjected: 1"}});
  23990. EXPECT_FALSE(client.connect());
  23991. t.join();
  23992. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23993. EXPECT_EQ(0, received);
  23994. }
  23995. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23996. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23997. // contains "upgrade" as a substring is a different token and must not
  23998. // start a WebSocket handshake.
  23999. auto make_request = [](const std::vector<std::string> &connection_values) {
  24000. Request req;
  24001. req.method = "GET";
  24002. req.headers.emplace("Upgrade", "websocket");
  24003. for (const auto &value : connection_values) {
  24004. req.headers.emplace("Connection", value);
  24005. }
  24006. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24007. req.headers.emplace("Sec-WebSocket-Version", "13");
  24008. return req;
  24009. };
  24010. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24011. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24012. EXPECT_TRUE(
  24013. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24014. EXPECT_TRUE(
  24015. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24016. EXPECT_TRUE(
  24017. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24018. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24019. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24020. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24021. EXPECT_FALSE(
  24022. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24023. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24024. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24025. }
  24026. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24027. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24028. // asks recipients to match each protocol-name case-insensitively, and RFC
  24029. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24030. // client naming websocket alongside another protocol, or on a second field
  24031. // line, is offering websocket; a value that merely contains "websocket" as a
  24032. // substring is a different protocol name and is not.
  24033. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24034. Request req;
  24035. req.method = "GET";
  24036. for (const auto &value : upgrade_values) {
  24037. req.headers.emplace("Upgrade", value);
  24038. }
  24039. req.headers.emplace("Connection", "Upgrade");
  24040. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24041. req.headers.emplace("Sec-WebSocket-Version", "13");
  24042. return req;
  24043. };
  24044. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24045. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24046. EXPECT_TRUE(
  24047. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24048. EXPECT_TRUE(
  24049. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24050. EXPECT_TRUE(
  24051. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24052. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24053. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24054. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24055. EXPECT_FALSE(
  24056. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24057. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24058. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24059. }
  24060. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24061. Server svr;
  24062. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24063. auto port = svr.bind_to_any_port("localhost");
  24064. std::thread t([&]() { svr.listen_after_bind(); });
  24065. auto se = detail::scope_exit([&] {
  24066. svr.stop();
  24067. t.join();
  24068. });
  24069. svr.wait_until_ready();
  24070. Headers headers = {{"Upgrade", "websocket"},
  24071. {"Connection", "notupgrade"},
  24072. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24073. {"Sec-WebSocket-Version", "13"}};
  24074. Client cli("localhost", port);
  24075. auto res = cli.Get("/ws", headers);
  24076. // The route exists only as a WebSocket route, so a request that fails the
  24077. // handshake check falls through to ordinary routing.
  24078. ASSERT_TRUE(res);
  24079. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24080. }
  24081. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24082. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24083. // Connection value is the only thing left for the client to reject.
  24084. Server svr;
  24085. svr.Get("/ws", [](const Request &req, Response &res) {
  24086. res.status = StatusCode::SwitchingProtocol_101;
  24087. res.set_header("Upgrade", "websocket");
  24088. res.set_header("Connection", "notupgrade");
  24089. res.set_header("Sec-WebSocket-Accept",
  24090. detail::websocket_accept_key(
  24091. req.get_header_value("Sec-WebSocket-Key")));
  24092. });
  24093. auto port = svr.bind_to_any_port("localhost");
  24094. std::thread t([&]() { svr.listen_after_bind(); });
  24095. auto se = detail::scope_exit([&] {
  24096. svr.stop();
  24097. t.join();
  24098. });
  24099. svr.wait_until_ready();
  24100. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24101. auto res = client.connect();
  24102. EXPECT_FALSE(res);
  24103. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24104. EXPECT_FALSE(client.is_open());
  24105. }
  24106. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24107. Server svr;
  24108. svr.Get("/ws", [](const Request &req, Response &res) {
  24109. res.status = StatusCode::SwitchingProtocol_101;
  24110. res.set_header("Upgrade", "websocket");
  24111. res.set_header("Connection", "Upgrade");
  24112. res.set_header("Sec-WebSocket-Accept",
  24113. detail::websocket_accept_key(
  24114. req.get_header_value("Sec-WebSocket-Key")));
  24115. res.set_header("Sec-WebSocket-Protocol", "admin");
  24116. });
  24117. auto port = svr.bind_to_any_port("localhost");
  24118. std::thread t([&]() { svr.listen_after_bind(); });
  24119. auto se = detail::scope_exit([&] {
  24120. svr.stop();
  24121. t.join();
  24122. });
  24123. svr.wait_until_ready();
  24124. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24125. // Server selects a subprotocol the client never offered
  24126. {
  24127. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24128. ws::WebSocketClient client(url, headers);
  24129. auto res = client.connect();
  24130. EXPECT_FALSE(res);
  24131. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24132. EXPECT_FALSE(client.is_open());
  24133. EXPECT_TRUE(client.subprotocol().empty());
  24134. }
  24135. // Client offered none but the server named one anyway
  24136. {
  24137. ws::WebSocketClient client(url);
  24138. auto res = client.connect();
  24139. EXPECT_FALSE(res);
  24140. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24141. EXPECT_FALSE(client.is_open());
  24142. EXPECT_TRUE(client.subprotocol().empty());
  24143. }
  24144. }
  24145. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24146. // The socket path doubles as the URL host, so it must not contain '/'.
  24147. const char *shard = getenv("GTEST_SHARD_INDEX");
  24148. const std::string sock_path =
  24149. shard ? std::string("httplib-ws-") + shard + ".sock"
  24150. : std::string("httplib-ws.sock");
  24151. std::remove(sock_path.c_str());
  24152. Server svr;
  24153. std::mutex mtx;
  24154. std::string received_host;
  24155. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24156. {
  24157. std::lock_guard<std::mutex> lock(mtx);
  24158. received_host = req.get_header_value("Host");
  24159. }
  24160. std::string msg;
  24161. while (ws.read(msg)) {
  24162. ws.send(msg);
  24163. }
  24164. });
  24165. svr.set_address_family(AF_UNIX);
  24166. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24167. auto se = detail::scope_exit([&] {
  24168. svr.stop();
  24169. t.join();
  24170. std::remove(sock_path.c_str());
  24171. });
  24172. svr.wait_until_ready();
  24173. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24174. client.set_address_family(AF_UNIX);
  24175. ASSERT_TRUE(client.connect());
  24176. ASSERT_TRUE(client.send("hello"));
  24177. std::string msg;
  24178. ASSERT_TRUE(client.read(msg));
  24179. client.close();
  24180. {
  24181. std::lock_guard<std::mutex> lock(mtx);
  24182. // There is no host:port for a Unix socket, so the same "localhost"
  24183. // placeholder the HTTP client uses is expected.
  24184. EXPECT_EQ("localhost", received_host);
  24185. }
  24186. }
  24187. // Two threads must never parse WebSocket frames from the same stream.
  24188. // close() used to read the peer's Close reply with its own frame read, so it
  24189. // raced a reader thread that was in the middle of a payload: the payload loop
  24190. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24191. // so bytes taken by close() were replaced with bytes from further along the
  24192. // stream. The message kept its length and silently changed content.
  24193. //
  24194. // The raw peer below sends a frame header plus part of the payload, waits for
  24195. // the handler to call close(), and only then sends the rest. Whichever thread
  24196. // would win the race for those bytes, the message must arrive intact, because
  24197. // close() must not touch the stream while read() owns it.
  24198. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24199. #ifndef _WIN32
  24200. signal(SIGPIPE, SIG_IGN);
  24201. #endif
  24202. const size_t payload_len = 120; // fits the 7-bit length field
  24203. const size_t prefix_len = 8;
  24204. const int attempts = 8;
  24205. std::string expected(payload_len, '\0');
  24206. for (size_t i = 0; i < payload_len; i++) {
  24207. expected[i] = static_cast<char>('a' + i % 26);
  24208. }
  24209. std::atomic<bool> peer_stalled{false};
  24210. std::atomic<bool> handler_done{false};
  24211. std::mutex received_mutex;
  24212. std::vector<std::string> received;
  24213. // Bound every wait, so a regression fails the test instead of hanging the
  24214. // suite.
  24215. auto wait_for = [](const std::atomic<bool> &flag) {
  24216. for (int i = 0; i < 500 && !flag; i++) {
  24217. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24218. }
  24219. };
  24220. Server svr;
  24221. svr.set_websocket_ping_interval(0);
  24222. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24223. std::thread reader([&]() {
  24224. std::string msg;
  24225. while (ws.read(msg)) {
  24226. std::lock_guard<std::mutex> guard(received_mutex);
  24227. received.push_back(msg);
  24228. }
  24229. });
  24230. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24231. // inside read_websocket_frame() when close() runs.
  24232. wait_for(peer_stalled);
  24233. ws.close();
  24234. reader.join();
  24235. handler_done = true;
  24236. });
  24237. auto port = svr.bind_to_any_port("127.0.0.1");
  24238. std::thread t([&]() { svr.listen_after_bind(); });
  24239. auto se = detail::scope_exit([&] {
  24240. svr.stop();
  24241. t.join();
  24242. });
  24243. svr.wait_until_ready();
  24244. auto send_bytes = [](socket_t s, const std::string &data) {
  24245. #ifdef _WIN32
  24246. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24247. #else
  24248. auto n = ::send(s, data.data(), data.size(), 0);
  24249. #endif
  24250. return n == static_cast<decltype(n)>(data.size());
  24251. };
  24252. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24253. // Every length used here fits the 7-bit length field.
  24254. auto masked_header = [](uint8_t first_byte, size_t len) {
  24255. std::string h;
  24256. h += static_cast<char>(first_byte);
  24257. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24258. h.append(4, '\0'); // mask key
  24259. return h;
  24260. };
  24261. for (int attempt = 0; attempt < attempts; attempt++) {
  24262. peer_stalled = false;
  24263. handler_done = false;
  24264. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24265. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24266. auto se_sock = detail::scope_exit([&] {
  24267. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24268. });
  24269. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24270. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24271. sockaddr_in addr{};
  24272. addr.sin_family = AF_INET;
  24273. addr.sin_port = htons(static_cast<uint16_t>(port));
  24274. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24275. ASSERT_EQ(
  24276. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24277. << "attempt " << attempt;
  24278. ASSERT_TRUE(send_bytes(sock,
  24279. "GET /ws HTTP/1.1\r\n"
  24280. "Host: 127.0.0.1\r\n"
  24281. "Upgrade: websocket\r\n"
  24282. "Connection: Upgrade\r\n"
  24283. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24284. "Sec-WebSocket-Version: 13\r\n"
  24285. "\r\n"))
  24286. << "attempt " << attempt;
  24287. std::string response;
  24288. while (response.find("\r\n\r\n") == std::string::npos) {
  24289. char buf[512];
  24290. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24291. if (n <= 0) { break; }
  24292. response.append(buf, static_cast<size_t>(n));
  24293. }
  24294. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24295. << "attempt " << attempt;
  24296. // Send the header of a Binary message but only the first prefix_len bytes
  24297. // of its payload, leaving the reader thread stalled inside the payload.
  24298. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24299. expected.substr(0, prefix_len)))
  24300. << "attempt " << attempt;
  24301. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24302. peer_stalled = true;
  24303. // Let close() send its Close frame and park in its own read before the
  24304. // rest of the payload arrives, so both threads are waiting for it.
  24305. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24306. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24307. close_frame += static_cast<char>(0x03); // status 1000
  24308. close_frame += static_cast<char>(0xE8);
  24309. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24310. << "attempt " << attempt;
  24311. // Closing the peer releases the reader thread even on the buggy path,
  24312. // where it waits for bytes another thread already consumed.
  24313. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24314. detail::close_socket(sock);
  24315. sock = INVALID_SOCKET;
  24316. wait_for(handler_done);
  24317. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24318. }
  24319. std::lock_guard<std::mutex> guard(received_mutex);
  24320. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24321. << "a message in flight when close() ran was dropped";
  24322. for (size_t i = 0; i < received.size(); i++) {
  24323. EXPECT_EQ(expected, received[i]) << "message " << i;
  24324. }
  24325. }
  24326. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24327. // returning the socket, or INVALID_SOCKET.
  24328. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24329. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24330. if (sock == INVALID_SOCKET) { return sock; }
  24331. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24332. sockaddr_in addr{};
  24333. addr.sin_family = AF_INET;
  24334. addr.sin_port = htons(static_cast<uint16_t>(port));
  24335. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24336. std::string req = "GET " + path +
  24337. " HTTP/1.1\r\n"
  24338. "Host: 127.0.0.1\r\n"
  24339. "Upgrade: websocket\r\n"
  24340. "Connection: Upgrade\r\n"
  24341. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24342. "Sec-WebSocket-Version: 13\r\n"
  24343. "\r\n";
  24344. std::string res;
  24345. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24346. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24347. static_cast<ssize_t>(req.size())) {
  24348. char c;
  24349. while (res.find("\r\n\r\n") == std::string::npos &&
  24350. ::recv(sock, &c, 1, 0) == 1) {
  24351. res += c;
  24352. }
  24353. }
  24354. if (res.find(" 101 ") == std::string::npos) {
  24355. detail::close_socket(sock);
  24356. return INVALID_SOCKET;
  24357. }
  24358. return sock;
  24359. }
  24360. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24361. // The payload must fit the 7-bit length field.
  24362. static std::string masked_frame(uint8_t first_byte,
  24363. const std::string &payload) {
  24364. std::string f;
  24365. f += static_cast<char>(first_byte);
  24366. f += static_cast<char>(0x80 | payload.size());
  24367. f.append(4, '\0');
  24368. return f + payload;
  24369. }
  24370. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24371. std::atomic<bool> done{false};
  24372. std::string received;
  24373. Server svr;
  24374. svr.set_websocket_ping_interval(0);
  24375. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24376. std::string msg;
  24377. if (ws.read(msg) == ws::Binary) { received = msg; }
  24378. done = true;
  24379. });
  24380. auto port = svr.bind_to_any_port("127.0.0.1");
  24381. std::thread t([&]() { svr.listen_after_bind(); });
  24382. auto se = detail::scope_exit([&] {
  24383. svr.stop();
  24384. t.join();
  24385. });
  24386. svr.wait_until_ready();
  24387. auto sock = connect_raw_websocket(port, "/ws");
  24388. ASSERT_NE(INVALID_SOCKET, sock);
  24389. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24390. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24391. masked_frame(0x89, "p") + // FIN + Ping
  24392. masked_frame(0x80, "lo"); // FIN + Continuation
  24393. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24394. for (int i = 0; i < 500 && !done; i++) {
  24395. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24396. }
  24397. ASSERT_TRUE(done);
  24398. EXPECT_EQ("Hello", received);
  24399. // The Ping between the fragments is answered with a Pong.
  24400. char pong[3];
  24401. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24402. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24403. }
  24404. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24405. Server svr;
  24406. svr.set_websocket_ping_interval(-1);
  24407. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24408. std::string msg;
  24409. while (ws.read(msg)) {}
  24410. });
  24411. auto port = svr.bind_to_any_port("127.0.0.1");
  24412. std::thread t([&]() { svr.listen_after_bind(); });
  24413. auto se = detail::scope_exit([&] {
  24414. svr.stop();
  24415. t.join();
  24416. });
  24417. svr.wait_until_ready();
  24418. auto sock = connect_raw_websocket(port, "/ws");
  24419. ASSERT_NE(INVALID_SOCKET, sock);
  24420. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24421. // Nothing comes while the client stays quiet.
  24422. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24423. char c;
  24424. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24425. }
  24426. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24427. // and that has to end a read() already waiting on the peer, on every platform.
  24428. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24429. // The peer sends no pings, and its handler never calls read(), which is
  24430. // where pongs are written.
  24431. std::mutex mutex;
  24432. std::condition_variable cv;
  24433. auto release = false;
  24434. svr.set_websocket_ping_interval(0);
  24435. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24436. std::unique_lock<std::mutex> lock(mutex);
  24437. cv.wait(lock, [&] { return release; });
  24438. });
  24439. auto port = svr.bind_to_any_port(HOST);
  24440. std::thread t([&]() { svr.listen_after_bind(); });
  24441. auto se = detail::scope_exit([&] {
  24442. {
  24443. std::lock_guard<std::mutex> lock(mutex);
  24444. release = true;
  24445. }
  24446. cv.notify_all();
  24447. svr.stop();
  24448. t.join();
  24449. });
  24450. svr.wait_until_ready();
  24451. ws::WebSocketClient client(std::string(scheme) +
  24452. "://localhost:" + std::to_string(port) + "/ws");
  24453. #ifdef CPPHTTPLIB_SSL_ENABLED
  24454. client.enable_server_certificate_verification(false);
  24455. #endif
  24456. // A ping a second, given up on after two go unanswered: about 3s
  24457. client.set_websocket_ping_interval(1);
  24458. client.set_websocket_max_missed_pongs(2);
  24459. // Well past that, so that a read the timeout ends instead stands out
  24460. client.set_read_timeout(10);
  24461. ASSERT_TRUE(client.connect());
  24462. auto start = std::chrono::steady_clock::now();
  24463. std::string msg;
  24464. EXPECT_EQ(ws::Fail, client.read(msg));
  24465. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24466. std::chrono::steady_clock::now() - start)
  24467. .count(),
  24468. 6000);
  24469. EXPECT_FALSE(client.is_open());
  24470. }
  24471. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24472. Server svr;
  24473. check_pong_timeout_ends_read(svr, "ws");
  24474. }
  24475. #ifdef CPPHTTPLIB_SSL_ENABLED
  24476. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24478. ASSERT_TRUE(svr.is_valid());
  24479. check_pong_timeout_ends_read(svr, "wss");
  24480. }
  24481. #endif
  24482. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24483. Server svr;
  24484. svr.set_websocket_ping_interval(0);
  24485. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24486. std::string msg;
  24487. while (ws.read(msg)) {}
  24488. });
  24489. auto port = svr.bind_to_any_port("127.0.0.1");
  24490. std::thread t([&]() { svr.listen_after_bind(); });
  24491. auto se = detail::scope_exit([&] {
  24492. svr.stop();
  24493. t.join();
  24494. });
  24495. svr.wait_until_ready();
  24496. // Each Close payload and the reply it should get: an echo when valid, 1002
  24497. // otherwise.
  24498. std::vector<std::pair<std::string, std::string>> cases = {
  24499. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24500. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24501. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24502. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24503. };
  24504. // Also between the fragments of a message.
  24505. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24506. for (const auto &c : cases) {
  24507. auto sock = connect_raw_websocket(port, "/ws");
  24508. ASSERT_NE(INVALID_SOCKET, sock);
  24509. auto frames = prefix + masked_frame(0x88, c.first);
  24510. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24511. std::string reply;
  24512. char buf[256];
  24513. while (reply.size() < 2 + c.second.size()) {
  24514. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24515. if (n <= 0) { break; }
  24516. reply.append(buf, static_cast<size_t>(n));
  24517. }
  24518. detail::close_socket(sock);
  24519. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24520. c.second,
  24521. reply);
  24522. }
  24523. }
  24524. }
  24525. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24526. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24527. protected:
  24528. void SetUp() override {
  24529. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24530. SERVER_PRIVATE_KEY_FILE);
  24531. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24532. std::string msg;
  24533. ws::ReadResult ret;
  24534. while ((ret = ws.read(msg))) {
  24535. if (ret == ws::Binary) {
  24536. ws.send(msg.data(), msg.size());
  24537. } else {
  24538. ws.send(msg);
  24539. }
  24540. }
  24541. });
  24542. port_ = server_->bind_to_any_port(HOST);
  24543. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24544. server_->wait_until_ready();
  24545. }
  24546. void TearDown() override {
  24547. server_->stop();
  24548. if (server_thread_.joinable()) { server_thread_.join(); }
  24549. }
  24550. std::unique_ptr<SSLServer> server_;
  24551. std::thread server_thread_;
  24552. int port_ = 0;
  24553. };
  24554. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24555. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24556. {
  24557. ws::WebSocketClient client(url);
  24558. client.enable_server_certificate_verification(false);
  24559. auto calls = 0;
  24560. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24561. calls++;
  24562. return false;
  24563. });
  24564. EXPECT_FALSE(client.connect());
  24565. EXPECT_GT(calls, 0);
  24566. }
  24567. {
  24568. ws::WebSocketClient client(url);
  24569. client.enable_server_certificate_verification(false);
  24570. client.set_session_verifier([](tls::session_t) {
  24571. return SSLVerifierResponse::CertificateRejected;
  24572. });
  24573. EXPECT_FALSE(client.connect());
  24574. }
  24575. {
  24576. ws::WebSocketClient client(url);
  24577. client.enable_server_certificate_verification(false);
  24578. client.set_session_verifier([](tls::session_t) {
  24579. return SSLVerifierResponse::CertificateAccepted;
  24580. });
  24581. EXPECT_TRUE(client.connect());
  24582. }
  24583. }
  24584. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24585. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24586. "/ws-echo");
  24587. client.enable_server_certificate_verification(false);
  24588. ASSERT_TRUE(client.connect());
  24589. ASSERT_TRUE(client.is_open());
  24590. ASSERT_TRUE(client.send("Hello WSS"));
  24591. std::string msg;
  24592. EXPECT_EQ(ws::Text, client.read(msg));
  24593. EXPECT_EQ("Hello WSS", msg);
  24594. client.close();
  24595. }
  24596. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24597. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24598. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24599. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24600. // client (without calling close() first) is the only path that runs
  24601. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24602. // bug exactly.
  24603. //
  24604. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24605. // when linked against an instrumented libssl; run under Valgrind to catch it
  24606. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24607. // suite (the freed session otherwise stalls on the close handshake) — this test
  24608. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24609. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24610. {
  24611. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24612. "/ws-echo");
  24613. client.enable_server_certificate_verification(false);
  24614. client.set_read_timeout(2, 0);
  24615. client.set_write_timeout(2, 0);
  24616. ASSERT_TRUE(client.connect());
  24617. ASSERT_TRUE(client.is_open());
  24618. ASSERT_TRUE(client.send("still open"));
  24619. // Intentionally do NOT call client.close(): leaving scope runs
  24620. // shutdown_and_close() with the WebSocket still open, which must send the
  24621. // close frame while the TLS session is still alive.
  24622. }
  24623. }
  24624. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24625. // shutdown_and_close() at the start of connect(), reproducing the same
  24626. // use-after-free within the test body rather than at scope exit. The second
  24627. // connect must succeed and echo, proving the close handshake ran over a live
  24628. // session. See the note above about memory-tool requirements.
  24629. TEST_F(WebSocketSSLIntegrationTest,
  24630. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24631. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24632. "/ws-echo");
  24633. client.enable_server_certificate_verification(false);
  24634. client.set_read_timeout(2, 0);
  24635. client.set_write_timeout(2, 0);
  24636. ASSERT_TRUE(client.connect());
  24637. ASSERT_TRUE(client.is_open());
  24638. ASSERT_TRUE(client.send("still open"));
  24639. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24640. // the still-open connection, which must not touch a freed TLS session.
  24641. ASSERT_TRUE(client.connect());
  24642. ASSERT_TRUE(client.is_open());
  24643. ASSERT_TRUE(client.send("after reconnect"));
  24644. std::string msg;
  24645. EXPECT_EQ(ws::Text, client.read(msg));
  24646. EXPECT_EQ("after reconnect", msg);
  24647. client.close();
  24648. }
  24649. #endif
  24650. #ifdef CPPHTTPLIB_SSL_ENABLED
  24651. class WebSocketSSLCATest : public ::testing::Test {
  24652. protected:
  24653. void SetUp() override {
  24654. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24655. SERVER_PRIVATE_KEY_FILE);
  24656. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24657. std::string msg;
  24658. while (ws.read(msg)) {
  24659. ws.send(msg);
  24660. }
  24661. });
  24662. port_ = server_->bind_to_any_port("127.0.0.1");
  24663. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24664. server_->wait_until_ready();
  24665. }
  24666. void TearDown() override {
  24667. server_->stop();
  24668. if (server_thread_.joinable()) { server_thread_.join(); }
  24669. }
  24670. std::string url() const {
  24671. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24672. }
  24673. std::unique_ptr<SSLServer> server_;
  24674. std::thread server_thread_;
  24675. int port_ = 0;
  24676. };
  24677. // A custom CA loaded as PEM verifies the server with full certificate
  24678. // verification enabled
  24679. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24680. ws::WebSocketClient client(url());
  24681. std::string cert;
  24682. read_file(SERVER_CERT2_FILE, cert);
  24683. client.load_ca_cert_store(cert.c_str(), cert.size());
  24684. ASSERT_TRUE(client.connect());
  24685. ASSERT_TRUE(client.send("hello"));
  24686. std::string msg;
  24687. EXPECT_EQ(ws::Text, client.read(msg));
  24688. EXPECT_EQ("hello", msg);
  24689. client.close();
  24690. }
  24691. // A custom CA that does not cover the server must fail verification (the
  24692. // custom CA is exclusive; system certs are not loaded alongside it)
  24693. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24694. ws::WebSocketClient client(url());
  24695. std::string cert;
  24696. read_file(CLIENT_CA_CERT_FILE, cert);
  24697. client.load_ca_cert_store(cert.c_str(), cert.size());
  24698. auto res = client.connect();
  24699. ASSERT_FALSE(res);
  24700. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24701. EXPECT_EQ(-1, res.status());
  24702. EXPECT_NE(0u, res.ssl_backend_error());
  24703. }
  24704. // The same CA as a file path rather than PEM in memory
  24705. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24706. ws::WebSocketClient client(url());
  24707. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24708. ASSERT_TRUE(client.connect());
  24709. ASSERT_TRUE(client.send("hello"));
  24710. std::string msg;
  24711. EXPECT_EQ(ws::Text, client.read(msg));
  24712. EXPECT_EQ("hello", msg);
  24713. client.close();
  24714. }
  24715. // ...and a CA file that does not cover the server still fails, so it is the
  24716. // path above that decides the outcome
  24717. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24718. ws::WebSocketClient client(url());
  24719. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24720. ASSERT_FALSE(client.connect());
  24721. }
  24722. // Regression test: reconnecting with a native custom CA store used to reuse
  24723. // a store handle the previous TLS context had already freed (use-after-free
  24724. // under the OpenSSL backend). The context now lives as long as the client.
  24725. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24726. ws::WebSocketClient client(url());
  24727. std::string cert;
  24728. read_file(SERVER_CERT2_FILE, cert);
  24729. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24730. ASSERT_TRUE(client.connect());
  24731. client.close();
  24732. ASSERT_TRUE(client.connect());
  24733. ASSERT_TRUE(client.send("again"));
  24734. std::string msg;
  24735. EXPECT_EQ(ws::Text, client.read(msg));
  24736. EXPECT_EQ("again", msg);
  24737. client.close();
  24738. }
  24739. // Regression test: a certificate with a trusted chain but no identity match
  24740. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24741. // verification entirely for IP hosts, so this connection succeeded there.
  24742. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24743. // chain verification while the identity check must still fail.
  24744. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24746. ASSERT_TRUE(svr.is_valid());
  24747. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24748. std::string msg;
  24749. while (ws.read(msg)) {
  24750. ws.send(msg);
  24751. }
  24752. });
  24753. auto port = svr.bind_to_any_port("127.0.0.1");
  24754. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24755. auto se = detail::scope_exit([&] {
  24756. svr.stop();
  24757. t.join();
  24758. });
  24759. svr.wait_until_ready();
  24760. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24761. "/echo");
  24762. std::string cert;
  24763. read_file(SERVER_CERT_FILE, cert);
  24764. client.load_ca_cert_store(cert.c_str(), cert.size());
  24765. ASSERT_FALSE(client.connect());
  24766. }
  24767. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24768. // SNI, so nothing binds the host name to the TLS session. These bind the
  24769. // server to "localhost" instead, the only shape that exercises the SNI and
  24770. // hostname-verification path with certificate verification left enabled.
  24771. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24772. protected:
  24773. void Start(const char *cert_file) {
  24774. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24775. SERVER_PRIVATE_KEY_FILE);
  24776. ASSERT_TRUE(server_->is_valid());
  24777. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24778. std::string msg;
  24779. while (ws.read(msg)) {
  24780. ws.send(msg);
  24781. }
  24782. });
  24783. port_ = server_->bind_to_any_port("localhost");
  24784. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24785. server_->wait_until_ready();
  24786. }
  24787. void TearDown() override {
  24788. if (server_) { server_->stop(); }
  24789. if (server_thread_.joinable()) { server_thread_.join(); }
  24790. }
  24791. std::string url() const {
  24792. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24793. }
  24794. std::unique_ptr<SSLServer> server_;
  24795. std::thread server_thread_;
  24796. int port_ = 0;
  24797. };
  24798. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24799. // out and the connection is usable
  24800. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24801. Start(SERVER_CERT2_FILE);
  24802. ws::WebSocketClient client(url());
  24803. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24804. ASSERT_TRUE(client.connect());
  24805. ASSERT_TRUE(client.send("hello"));
  24806. std::string msg;
  24807. EXPECT_EQ(ws::Text, client.read(msg));
  24808. EXPECT_EQ("hello", msg);
  24809. client.close();
  24810. }
  24811. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24812. // while the identity check must still reject "localhost"
  24813. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24814. Start(SERVER_CERT_FILE);
  24815. ws::WebSocketClient client(url());
  24816. client.set_ca_cert_path(SERVER_CERT_FILE);
  24817. auto res = client.connect();
  24818. ASSERT_FALSE(res);
  24819. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24820. EXPECT_EQ(-1, res.status());
  24821. }
  24822. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24823. // disabled: the chain is still checked, only the identity check is skipped
  24824. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24825. Start(SERVER_CERT_FILE);
  24826. ws::WebSocketClient client(url());
  24827. client.set_ca_cert_path(SERVER_CERT_FILE);
  24828. client.enable_server_hostname_verification(false);
  24829. ASSERT_TRUE(client.connect());
  24830. ASSERT_TRUE(client.send("hello"));
  24831. std::string msg;
  24832. EXPECT_EQ(ws::Text, client.read(msg));
  24833. EXPECT_EQ("hello", msg);
  24834. client.close();
  24835. }
  24836. // A CA that did not sign the server certificate fails the chain, even though
  24837. // the name would match
  24838. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24839. Start(SERVER_CERT2_FILE);
  24840. ws::WebSocketClient client(url());
  24841. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24842. ASSERT_FALSE(client.connect());
  24843. }
  24844. // With verification disabled, neither the chain nor the name is checked
  24845. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24846. Start(SERVER_CERT_FILE);
  24847. ws::WebSocketClient client(url());
  24848. client.enable_server_certificate_verification(false);
  24849. ASSERT_TRUE(client.connect());
  24850. ASSERT_TRUE(client.send("hello"));
  24851. std::string msg;
  24852. EXPECT_EQ(ws::Text, client.read(msg));
  24853. EXPECT_EQ("hello", msg);
  24854. client.close();
  24855. }
  24856. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24857. protected:
  24858. void SetUp() override {
  24859. server_ = httplib::detail::make_unique<SSLServer>(
  24860. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24861. ASSERT_TRUE(server_->is_valid());
  24862. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24863. std::string msg;
  24864. while (ws.read(msg)) {
  24865. ws.send(msg);
  24866. }
  24867. });
  24868. port_ = server_->bind_to_any_port("localhost");
  24869. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24870. server_->wait_until_ready();
  24871. }
  24872. void TearDown() override {
  24873. server_->stop();
  24874. if (server_thread_.joinable()) { server_thread_.join(); }
  24875. }
  24876. std::string url() const {
  24877. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24878. }
  24879. void ConnectWithClientCert(const std::string &client_cert_file,
  24880. const std::string &client_private_key_file,
  24881. const char *private_key_password) {
  24882. std::string cert_pem, key_pem;
  24883. read_file(client_cert_file, cert_pem);
  24884. read_file(client_private_key_file, key_pem);
  24885. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24886. key_pem.c_str(), key_pem.size(),
  24887. private_key_password};
  24888. ConnectWithPem(pem);
  24889. }
  24890. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24891. ws::WebSocketClient client(url(), pem);
  24892. ASSERT_TRUE(client.is_valid());
  24893. client.enable_server_certificate_verification(false);
  24894. ASSERT_TRUE(client.connect());
  24895. ASSERT_TRUE(client.send("hello"));
  24896. std::string msg;
  24897. EXPECT_EQ(ws::Text, client.read(msg));
  24898. EXPECT_EQ("hello", msg);
  24899. client.close();
  24900. }
  24901. std::unique_ptr<SSLServer> server_;
  24902. std::thread server_thread_;
  24903. int port_ = 0;
  24904. };
  24905. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24906. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24907. }
  24908. // Control for the tests above: the fixture's server really does require a
  24909. // client certificate, so it is the PEM the constructor installed that decides
  24910. // the outcome.
  24911. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24912. ws::WebSocketClient client(url());
  24913. ASSERT_TRUE(client.is_valid());
  24914. client.enable_server_certificate_verification(false);
  24915. EXPECT_FALSE(client.connect());
  24916. }
  24917. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24918. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24919. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24920. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24921. }
  24922. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24923. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24924. std::string cert_pem, key_pem;
  24925. read_file(CLIENT_CERT_FILE, cert_pem);
  24926. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24927. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24928. std::vector<char> key(key_pem.begin(), key_pem.end());
  24929. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24930. key.size(), nullptr};
  24931. ConnectWithPem(pem);
  24932. }
  24933. #endif
  24934. #if !defined(_WIN32)
  24935. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24936. auto secret_dir = std::string("./symlink_test_secret");
  24937. auto served_dir = std::string("./symlink_test_served");
  24938. auto secret_file = secret_dir + "/secret.txt";
  24939. auto symlink_path = served_dir + "/escape";
  24940. // Setup: create directories and files
  24941. mkdir(secret_dir.c_str(), 0755);
  24942. mkdir(served_dir.c_str(), 0755);
  24943. {
  24944. std::ofstream ofs(secret_file);
  24945. ofs << "SECRET_DATA";
  24946. }
  24947. // Create symlink using absolute path so it resolves correctly
  24948. #ifdef PATH_MAX
  24949. char abs_secret[PATH_MAX];
  24950. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24951. #else
  24952. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24953. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24954. ASSERT_NE(nullptr, abs_secret);
  24955. #endif
  24956. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24957. auto se = detail::scope_exit([&] {
  24958. unlink(symlink_path.c_str());
  24959. unlink(secret_file.c_str());
  24960. rmdir(served_dir.c_str());
  24961. rmdir(secret_dir.c_str());
  24962. });
  24963. Server svr;
  24964. svr.set_mount_point("/", served_dir);
  24965. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24966. auto se2 = detail::scope_exit([&] {
  24967. svr.stop();
  24968. listen_thread.join();
  24969. });
  24970. svr.wait_until_ready();
  24971. Client cli("localhost", PORT);
  24972. // Symlink pointing outside base dir should be blocked
  24973. auto res = cli.Get("/escape/secret.txt");
  24974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24975. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24976. }
  24977. #endif
  24978. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24979. // "GET /smuggled" request), reads the first response, and only then sends the
  24980. // embedded request as the body. Returns how many times /smuggled ran.
  24981. //
  24982. // The body is sent AFTER receiving the first response (as in the original
  24983. // PoC) so that the stream_line_reader cannot buffer it together with the
  24984. // headers of the first request.
  24985. static int count_smuggled_requests(const std::string &outer_head,
  24986. std::string &first_response) {
  24987. Server svr;
  24988. svr.set_mount_point("/", "./www");
  24989. std::atomic<int> smuggled_count(0);
  24990. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24991. smuggled_count++;
  24992. res.set_content("oops", "text/plain");
  24993. });
  24994. svr.Post("/post", [&](const Request &req, Response &res) {
  24995. res.set_content(req.body, "text/plain");
  24996. });
  24997. auto port = svr.bind_to_any_port("localhost");
  24998. thread t = thread([&] { svr.listen_after_bind(); });
  24999. auto se = detail::scope_exit([&] {
  25000. svr.stop();
  25001. t.join();
  25002. });
  25003. svr.wait_until_ready();
  25004. auto error = Error::Success;
  25005. auto sock = detail::create_client_socket(
  25006. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25007. /*connection_timeout_sec=*/2, 0,
  25008. /*read_timeout_sec=*/2, 0,
  25009. /*write_timeout_sec=*/2, 0, std::string(), error);
  25010. EXPECT_NE(INVALID_SOCKET, sock);
  25011. if (sock == INVALID_SOCKET) { return -1; }
  25012. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25013. // The "smuggled" request will be sent as the body of the outer request
  25014. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25015. "Host: localhost\r\n"
  25016. "Connection: close\r\n"
  25017. "\r\n";
  25018. auto head = outer_head;
  25019. auto len = std::to_string(smuggled.size());
  25020. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25021. pos = head.find("{len}", pos + len.size())) {
  25022. head.replace(pos, 5, len);
  25023. }
  25024. // Step 1: Send only the outer request headers (no body yet)
  25025. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25026. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25027. // Step 2: Read the first response
  25028. char buf[4096];
  25029. for (;;) {
  25030. auto n = recv(sock, buf, sizeof(buf), 0);
  25031. if (n <= 0) break;
  25032. first_response.append(buf, static_cast<size_t>(n));
  25033. // Stop once we have a complete response (headers + body)
  25034. auto hdr_end = first_response.find("\r\n\r\n");
  25035. if (hdr_end != std::string::npos) {
  25036. // Check for Content-Length to know when the body is complete
  25037. auto cl_pos = first_response.find("Content-Length:");
  25038. if (cl_pos != std::string::npos) {
  25039. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25040. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25041. auto cl = std::stoul(
  25042. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25043. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25044. } else {
  25045. break; // No Content-Length, assume headers-only response
  25046. }
  25047. }
  25048. }
  25049. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25050. // vulnerable server the keep-alive loop reads this as a second request. The
  25051. // server may already have closed the connection, so the result is ignored.
  25052. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25053. // Half-close so that a server which drained the body sees EOF and closes,
  25054. // instead of the read below waiting for the read timeout.
  25055. #ifdef _WIN32
  25056. ::shutdown(sock, SD_SEND);
  25057. #else
  25058. ::shutdown(sock, SHUT_WR);
  25059. #endif
  25060. // Step 4: Read until the server closes the connection
  25061. for (;;) {
  25062. auto n = recv(sock, buf, sizeof(buf), 0);
  25063. if (n <= 0) break;
  25064. }
  25065. return smuggled_count.load();
  25066. }
  25067. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25068. // A GET request with Content-Length to a static file handler must have its
  25069. // body drained before the keep-alive connection is reused. Otherwise the
  25070. // unread body bytes are interpreted as the next HTTP request.
  25071. std::string first_response;
  25072. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25073. "Host: localhost\r\n"
  25074. "Content-Length: {len}\r\n"
  25075. "\r\n",
  25076. first_response));
  25077. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25078. }
  25079. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25080. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25081. // be answered with 400 and the connection closed. Treating it as "no body"
  25082. // leaves the body to be parsed as the next request.
  25083. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25084. const char *targets[] = {
  25085. "GET /file", // handler that never reads the body
  25086. "GET /not-found", // no handler matches (404)
  25087. "POST /post", // handler that reads the body
  25088. };
  25089. for (auto target : targets) {
  25090. for (auto value : values) {
  25091. std::string first_response;
  25092. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25093. " HTTP/1.1\r\n"
  25094. "Host: localhost\r\n"
  25095. "Content-Length: " +
  25096. value + "\r\n\r\n",
  25097. first_response))
  25098. << target << " with Content-Length: " << value;
  25099. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25100. << target << " with Content-Length: " << value;
  25101. }
  25102. }
  25103. }
  25104. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25105. // A 400 for an unparseable request line leaves the rest of the message
  25106. // unread, so the connection must be closed rather than reused.
  25107. std::string first_response;
  25108. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25109. "Host: localhost\r\n"
  25110. "Content-Length: {len}\r\n"
  25111. "\r\n",
  25112. first_response));
  25113. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25114. }
  25115. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25116. // Same as above for a header block that fails to parse.
  25117. std::string first_response;
  25118. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25119. "Host: localhost\r\n"
  25120. "Bad Header\r\n"
  25121. "Content-Length: {len}\r\n"
  25122. "\r\n",
  25123. first_response));
  25124. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25125. }
  25126. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25127. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25128. // server must not read another request on that connection, even when the
  25129. // request had no body to drain.
  25130. std::string first_response;
  25131. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25132. "Host: localhost\r\n"
  25133. "\r\n",
  25134. first_response));
  25135. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25136. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25137. }
  25138. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25139. // A content reader that stops early leaves the stream inside the body.
  25140. // Draining the whole Content-Length from there, or reading the body again,
  25141. // reads into the next request, and whatever follows is parsed as a request
  25142. // of its own.
  25143. Server svr;
  25144. std::atomic<int> smuggled_count(0);
  25145. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25146. svr.Post("/upload", [](const Request &req, Response &res,
  25147. const ContentReader &content_reader) {
  25148. // Stop at the last chunk, so the whole body has been read however it
  25149. // arrives.
  25150. auto length = req.get_header_value_u64("Content-Length");
  25151. size_t total = 0;
  25152. auto consumed = content_reader([&](const char *, size_t n) {
  25153. total += n;
  25154. return total < length;
  25155. });
  25156. EXPECT_FALSE(consumed);
  25157. if (req.has_param("retry")) {
  25158. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25159. }
  25160. // Replace the 400 the aborted read set, which would close the connection.
  25161. res.set_redirect("/done");
  25162. });
  25163. auto port = svr.bind_to_any_port(HOST);
  25164. thread t = thread([&] { svr.listen_after_bind(); });
  25165. auto se = detail::scope_exit([&] {
  25166. svr.stop();
  25167. t.join();
  25168. });
  25169. svr.wait_until_ready();
  25170. // A front end sees the second request as a POST whose body is the GET. The
  25171. // first body is as long as the POST's headers, so draining it again reads
  25172. // exactly those and leaves the GET to be parsed next.
  25173. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25174. "Host: localhost\r\n"
  25175. "\r\n";
  25176. std::string second_head = "POST /post HTTP/1.1\r\n"
  25177. "Host: localhost\r\n"
  25178. "Content-Length: " +
  25179. std::to_string(inner.size()) +
  25180. "\r\n"
  25181. "\r\n";
  25182. for (auto target : {"/upload", "/upload?retry"}) {
  25183. smuggled_count = 0;
  25184. std::string request = "POST " + std::string(target) +
  25185. " HTTP/1.1\r\n"
  25186. "Host: localhost\r\n"
  25187. "Content-Length: " +
  25188. std::to_string(second_head.size()) +
  25189. "\r\n"
  25190. "\r\n" +
  25191. std::string(second_head.size(), 'A') + second_head +
  25192. inner;
  25193. std::string response;
  25194. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25195. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25196. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25197. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25198. EXPECT_EQ(0, smuggled_count.load()) << target;
  25199. }
  25200. }
  25201. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25202. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25203. // must be rejected with 400 Bad Request.
  25204. Server svr;
  25205. svr.Post("/test", [&](const Request &, Response &res) {
  25206. res.set_content("ok", "text/plain");
  25207. });
  25208. thread t = thread([&] { svr.listen(HOST, PORT); });
  25209. auto se = detail::scope_exit([&] {
  25210. svr.stop();
  25211. t.join();
  25212. ASSERT_FALSE(svr.is_running());
  25213. });
  25214. svr.wait_until_ready();
  25215. // Exact "chunked"
  25216. {
  25217. auto req = "POST /test HTTP/1.1\r\n"
  25218. "Host: localhost\r\n"
  25219. "Content-Length: 5\r\n"
  25220. "Transfer-Encoding: chunked\r\n"
  25221. "Connection: close\r\n"
  25222. "\r\n"
  25223. "hello";
  25224. std::string response;
  25225. ASSERT_TRUE(send_request(1, req, &response));
  25226. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25227. response.substr(0, response.find("\r\n")));
  25228. }
  25229. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25230. {
  25231. auto req = "POST /test HTTP/1.1\r\n"
  25232. "Host: localhost\r\n"
  25233. "Content-Length: 5\r\n"
  25234. "Transfer-Encoding: gzip, chunked\r\n"
  25235. "Connection: close\r\n"
  25236. "\r\n"
  25237. "hello";
  25238. std::string response;
  25239. ASSERT_TRUE(send_request(1, req, &response));
  25240. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25241. response.substr(0, response.find("\r\n")));
  25242. }
  25243. }
  25244. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25245. Server svr;
  25246. svr.Post("/test", [&](const Request &, Response &res) {
  25247. res.set_content("ok", "text/plain");
  25248. });
  25249. thread t = thread([&] { svr.listen(HOST, PORT); });
  25250. auto se = detail::scope_exit([&] {
  25251. svr.stop();
  25252. t.join();
  25253. ASSERT_FALSE(svr.is_running());
  25254. });
  25255. svr.wait_until_ready();
  25256. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25257. // length cannot be determined, so the server must answer 400 and close
  25258. // rather than treat the request as bodyless and leave the body in the
  25259. // socket for the next request to pick up.
  25260. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25261. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25262. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25263. std::string response;
  25264. ASSERT_TRUE(send_request(1, req, &response));
  25265. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25266. response.substr(0, response.find("\r\n")))
  25267. << transfer_encoding;
  25268. }
  25269. // RFC 9110 5.3: the codings may also be split across several
  25270. // Transfer-Encoding lines, which combine in the order they were received.
  25271. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25272. // just like the single-line "chunked, gzip" above.
  25273. {
  25274. auto req = "POST /test HTTP/1.1\r\n"
  25275. "Host: localhost\r\n"
  25276. "Transfer-Encoding: chunked\r\n"
  25277. "Transfer-Encoding: gzip\r\n"
  25278. "\r\n"
  25279. "0\r\n\r\n";
  25280. std::string response;
  25281. ASSERT_TRUE(send_request(1, req, &response));
  25282. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25283. response.substr(0, response.find("\r\n")));
  25284. }
  25285. // A sequence ending in chunked stays valid.
  25286. auto req = "POST /test HTTP/1.1\r\n"
  25287. "Host: localhost\r\n"
  25288. "Transfer-Encoding: gzip, chunked\r\n"
  25289. "Connection: close\r\n"
  25290. "\r\n"
  25291. "0\r\n\r\n";
  25292. std::string response;
  25293. ASSERT_TRUE(send_request(1, req, &response));
  25294. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  25295. // ...including when it is spread over several lines.
  25296. auto split_req = "POST /test HTTP/1.1\r\n"
  25297. "Host: localhost\r\n"
  25298. "Transfer-Encoding: gzip\r\n"
  25299. "Transfer-Encoding: chunked\r\n"
  25300. "Connection: close\r\n"
  25301. "\r\n"
  25302. "0\r\n\r\n";
  25303. std::string split_response;
  25304. ASSERT_TRUE(send_request(1, split_req, &split_response));
  25305. EXPECT_EQ("HTTP/1.1 200 OK",
  25306. split_response.substr(0, split_response.find("\r\n")));
  25307. }
  25308. // Regression for issue #2450: a DELETE without Content-Length on a
  25309. // keep-alive connection must not let the post-response drain consume the
  25310. // next request's bytes.
  25311. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25312. Server svr;
  25313. std::atomic<int> delete_count(0);
  25314. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25315. delete_count++;
  25316. res.status = StatusCode::NoContent_204;
  25317. });
  25318. auto port = svr.bind_to_any_port(HOST);
  25319. thread t = thread([&] { svr.listen_after_bind(); });
  25320. auto se = detail::scope_exit([&] {
  25321. svr.stop();
  25322. t.join();
  25323. });
  25324. svr.wait_until_ready();
  25325. auto error = Error::Success;
  25326. auto sock = detail::create_client_socket(
  25327. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25328. /*connection_timeout_sec=*/2, 0,
  25329. /*read_timeout_sec=*/2, 0,
  25330. /*write_timeout_sec=*/2, 0, std::string(), error);
  25331. ASSERT_NE(INVALID_SOCKET, sock);
  25332. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25333. auto send_request_and_read_response = [&](const std::string &req,
  25334. std::string &out) -> bool {
  25335. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25336. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25337. char buf[4096];
  25338. for (;;) {
  25339. auto n = recv(sock, buf, sizeof(buf), 0);
  25340. if (n <= 0) { return !out.empty(); }
  25341. out.append(buf, static_cast<size_t>(n));
  25342. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25343. }
  25344. };
  25345. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25346. "Host: localhost\r\n"
  25347. "\r\n";
  25348. std::string resp1;
  25349. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25350. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25351. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25352. "Host: localhost\r\n"
  25353. "Connection: close\r\n"
  25354. "\r\n";
  25355. std::string resp2;
  25356. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25357. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25358. EXPECT_EQ(2, delete_count.load());
  25359. }
  25360. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25361. Server svr;
  25362. svr.Post("/ingest", [&](const Request &, Response &res,
  25363. const ContentReader &content_reader) {
  25364. auto consumed = content_reader([](const char *, size_t) { return false; });
  25365. EXPECT_FALSE(consumed);
  25366. res.status = StatusCode::Conflict_409;
  25367. res.set_header("Connection", "close");
  25368. });
  25369. auto port = svr.bind_to_any_port(HOST);
  25370. thread t = thread([&] { svr.listen_after_bind(); });
  25371. auto se = detail::scope_exit([&] {
  25372. svr.stop();
  25373. t.join();
  25374. });
  25375. svr.wait_until_ready();
  25376. auto error = Error::Success;
  25377. auto sock = detail::create_client_socket(
  25378. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25379. /*connection_timeout_sec=*/2, 0,
  25380. /*read_timeout_sec=*/1, 0,
  25381. /*write_timeout_sec=*/2, 0, std::string(), error);
  25382. ASSERT_NE(INVALID_SOCKET, sock);
  25383. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25384. std::string request = "POST /ingest HTTP/1.1\r\n"
  25385. "Host: localhost\r\n"
  25386. "Transfer-Encoding: chunked\r\n"
  25387. "\r\n"
  25388. "4\r\n"
  25389. "data\r\n";
  25390. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25391. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25392. std::string response;
  25393. ssize_t received = 0;
  25394. do {
  25395. char buf[4096];
  25396. received = recv(sock, buf, sizeof(buf), 0);
  25397. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25398. } while (received > 0);
  25399. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25400. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25401. EXPECT_EQ(0, received);
  25402. }
  25403. namespace no_proxy_test {
  25404. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25405. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25406. // calling listen().
  25407. class ScopedServer {
  25408. public:
  25409. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25410. ~ScopedServer() {
  25411. svr_.stop();
  25412. if (th_.joinable()) { th_.join(); }
  25413. }
  25414. Server &svr() { return svr_; }
  25415. int port() const { return port_; }
  25416. void listen() {
  25417. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25418. svr_.wait_until_ready();
  25419. }
  25420. private:
  25421. Server svr_;
  25422. std::thread th_;
  25423. int port_ = 0;
  25424. };
  25425. class ProxyAndTargetServers {
  25426. public:
  25427. ProxyAndTargetServers() {
  25428. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25429. proxy_hits_++;
  25430. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25431. res.set_content("via-proxy", "text/plain");
  25432. });
  25433. target_.Get(".*", [this](const Request &req, Response &res) {
  25434. target_hits_++;
  25435. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25436. res.set_content("direct", "text/plain");
  25437. });
  25438. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25439. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25440. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25441. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25442. proxy_mock_.wait_until_ready();
  25443. target_.wait_until_ready();
  25444. }
  25445. ~ProxyAndTargetServers() {
  25446. proxy_mock_.stop();
  25447. target_.stop();
  25448. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25449. if (target_thread_.joinable()) { target_thread_.join(); }
  25450. }
  25451. Server &proxy_mock() { return proxy_mock_; }
  25452. Server &target() { return target_; }
  25453. int proxy_port() const { return proxy_port_; }
  25454. int target_port() const { return target_port_; }
  25455. int proxy_hits() const { return proxy_hits_.load(); }
  25456. int target_hits() const { return target_hits_.load(); }
  25457. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25458. void reset_counters() {
  25459. proxy_hits_ = 0;
  25460. target_hits_ = 0;
  25461. last_had_proxy_authz_ = false;
  25462. }
  25463. private:
  25464. Server proxy_mock_;
  25465. Server target_;
  25466. std::thread proxy_thread_;
  25467. std::thread target_thread_;
  25468. int proxy_port_ = 0;
  25469. int target_port_ = 0;
  25470. std::atomic<int> proxy_hits_{0};
  25471. std::atomic<int> target_hits_{0};
  25472. std::atomic<bool> last_had_proxy_authz_{false};
  25473. };
  25474. inline std::unique_ptr<Client> make_client(const std::string &host,
  25475. ProxyAndTargetServers &s) {
  25476. auto cli = detail::make_unique<Client>(host, s.target_port());
  25477. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25478. cli->set_proxy("127.0.0.1", s.proxy_port());
  25479. return cli;
  25480. }
  25481. } // namespace no_proxy_test
  25482. using no_proxy_test::make_client;
  25483. using no_proxy_test::ProxyAndTargetServers;
  25484. // A stream request carries the credentials a buffered request does
  25485. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25486. no_proxy_test::ScopedServer origin;
  25487. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25488. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25489. });
  25490. origin.listen();
  25491. Client cli("127.0.0.1", origin.port());
  25492. cli.set_basic_auth("user", "pass");
  25493. auto handle = cli.open_stream("GET", "/x");
  25494. ASSERT_TRUE(handle.is_valid());
  25495. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25496. Client bearer("127.0.0.1", origin.port());
  25497. bearer.set_bearer_token_auth("tok");
  25498. auto handle2 = bearer.open_stream("GET", "/x");
  25499. ASSERT_TRUE(handle2.is_valid());
  25500. EXPECT_EQ("Bearer tok", read_all(handle2));
  25501. }
  25502. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25503. // takes its own credentials, as for a buffered request
  25504. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25505. std::string target, authz, proxy_authz;
  25506. no_proxy_test::ScopedServer proxy;
  25507. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25508. target = req.target;
  25509. authz = req.get_header_value("Authorization");
  25510. proxy_authz = req.get_header_value("Proxy-Authorization");
  25511. res.set_content("ok", "text/plain");
  25512. });
  25513. proxy.listen();
  25514. Client cli("origin.example", 8080);
  25515. cli.set_proxy("127.0.0.1", proxy.port());
  25516. cli.set_proxy_basic_auth("puser", "ppass");
  25517. cli.set_basic_auth("user", "pass");
  25518. auto handle = cli.open_stream("GET", "/x");
  25519. ASSERT_TRUE(handle.is_valid());
  25520. EXPECT_EQ("ok", read_all(handle));
  25521. EXPECT_EQ("http://origin.example:8080/x", target);
  25522. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25523. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25524. }
  25525. TEST(NoProxyTest, ExactHostnameBypasses) {
  25526. ProxyAndTargetServers s;
  25527. auto cli = make_client("example.com", s);
  25528. cli->set_no_proxy({"example.com"});
  25529. auto res = cli->Get("/");
  25530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25531. EXPECT_EQ(0, s.proxy_hits());
  25532. EXPECT_EQ(1, s.target_hits());
  25533. }
  25534. TEST(NoProxyTest, SubdomainBypasses) {
  25535. ProxyAndTargetServers s;
  25536. auto cli = make_client("foo.example.com", s);
  25537. cli->set_no_proxy({"example.com"});
  25538. auto res = cli->Get("/");
  25539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25540. EXPECT_EQ(0, s.proxy_hits());
  25541. EXPECT_EQ(1, s.target_hits());
  25542. }
  25543. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25544. // Regression guard: "evilexample.com" must not be considered a subdomain
  25545. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25546. // check would let traffic bypass the proxy and leak credentials direct
  25547. // to the attacker host.
  25548. ProxyAndTargetServers s;
  25549. auto cli = make_client("evilexample.com", s);
  25550. cli->set_no_proxy({"example.com"});
  25551. auto res = cli->Get("/");
  25552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25553. EXPECT_GE(s.proxy_hits(), 1);
  25554. EXPECT_EQ(0, s.target_hits());
  25555. }
  25556. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25557. ProxyAndTargetServers s;
  25558. auto cli = make_client("example.com.evil.com", s);
  25559. cli->set_no_proxy({"example.com"});
  25560. auto res = cli->Get("/");
  25561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25562. EXPECT_GE(s.proxy_hits(), 1);
  25563. EXPECT_EQ(0, s.target_hits());
  25564. }
  25565. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25566. ProxyAndTargetServers s;
  25567. auto cli = make_client("example.com", s);
  25568. cli->set_no_proxy({".example.com"});
  25569. auto res = cli->Get("/");
  25570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25571. EXPECT_EQ(0, s.proxy_hits());
  25572. EXPECT_EQ(1, s.target_hits());
  25573. }
  25574. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25575. ProxyAndTargetServers s;
  25576. auto cli = make_client("Example.COM", s);
  25577. cli->set_no_proxy({"EXAMPLE.com"});
  25578. auto res = cli->Get("/");
  25579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25580. EXPECT_EQ(0, s.proxy_hits());
  25581. EXPECT_EQ(1, s.target_hits());
  25582. }
  25583. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25584. ProxyAndTargetServers s;
  25585. auto cli = make_client("example.com.", s);
  25586. cli->set_no_proxy({"example.com"});
  25587. auto res = cli->Get("/");
  25588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25589. EXPECT_EQ(0, s.proxy_hits());
  25590. EXPECT_EQ(1, s.target_hits());
  25591. }
  25592. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25593. // Trailing dots must be normalized on BOTH sides — host and entry.
  25594. // An implementation that only strips the host-side trailing dot would
  25595. // fail to match host "example.com" against entry "example.com." because
  25596. // a literal substring search would compare 11 chars against 12.
  25597. ProxyAndTargetServers s;
  25598. auto cli = make_client("example.com", s);
  25599. cli->set_no_proxy({"example.com."});
  25600. auto res = cli->Get("/");
  25601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25602. EXPECT_EQ(0, s.proxy_hits());
  25603. EXPECT_EQ(1, s.target_hits());
  25604. }
  25605. TEST(NoProxyTest, WildcardBypassesEverything) {
  25606. ProxyAndTargetServers s;
  25607. auto cli = make_client("anything.invalid.test", s);
  25608. cli->set_no_proxy({"*"});
  25609. auto res = cli->Get("/");
  25610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25611. EXPECT_EQ(0, s.proxy_hits());
  25612. EXPECT_EQ(1, s.target_hits());
  25613. }
  25614. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25615. ProxyAndTargetServers s;
  25616. Client cli("127.0.0.1", s.target_port());
  25617. cli.set_proxy("127.0.0.1", s.proxy_port());
  25618. cli.set_no_proxy({"127.0.0.1"});
  25619. auto res = cli.Get("/");
  25620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25621. EXPECT_EQ(0, s.proxy_hits());
  25622. EXPECT_EQ(1, s.target_hits());
  25623. }
  25624. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25625. ProxyAndTargetServers s;
  25626. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25627. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25628. cli.set_proxy("127.0.0.1", s.proxy_port());
  25629. cli.set_no_proxy({"::1"});
  25630. auto res = cli.Get("/");
  25631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25632. EXPECT_EQ(0, s.proxy_hits());
  25633. EXPECT_EQ(1, s.target_hits());
  25634. }
  25635. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25636. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25637. // must still be recognized as IPv6 for CIDR matching. Implementations
  25638. // that detect IPv6 only when the host begins with '[' would parse the
  25639. // host as a hostname and miss the match.
  25640. ProxyAndTargetServers s;
  25641. Client cli("fe80::1", s.target_port());
  25642. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25643. cli.set_proxy("127.0.0.1", s.proxy_port());
  25644. cli.set_no_proxy({"fe80::/10"});
  25645. auto res = cli.Get("/");
  25646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25647. EXPECT_EQ(0, s.proxy_hits());
  25648. EXPECT_EQ(1, s.target_hits());
  25649. }
  25650. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25651. ProxyAndTargetServers s;
  25652. Client cli("::1", s.target_port());
  25653. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25654. cli.set_proxy("127.0.0.1", s.proxy_port());
  25655. cli.set_no_proxy({"[::1]"});
  25656. auto res = cli.Get("/");
  25657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25658. EXPECT_EQ(0, s.proxy_hits());
  25659. EXPECT_EQ(1, s.target_hits());
  25660. }
  25661. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25662. ProxyAndTargetServers s;
  25663. Client cli("fe80::1", s.target_port());
  25664. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25665. cli.set_proxy("127.0.0.1", s.proxy_port());
  25666. cli.set_no_proxy({"[fe80::]/10"});
  25667. auto res = cli.Get("/");
  25668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25669. EXPECT_EQ(0, s.proxy_hits());
  25670. EXPECT_EQ(1, s.target_hits());
  25671. }
  25672. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25673. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25674. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25675. // tricks via address-family conversion.
  25676. ProxyAndTargetServers s;
  25677. Client cli("::ffff:127.0.0.1", s.target_port());
  25678. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25679. cli.set_proxy("127.0.0.1", s.proxy_port());
  25680. cli.set_no_proxy({"127.0.0.1"});
  25681. auto res = cli.Get("/");
  25682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25683. EXPECT_GE(s.proxy_hits(), 1);
  25684. EXPECT_EQ(0, s.target_hits());
  25685. }
  25686. TEST(NoProxyTest, IPv4CidrMatch) {
  25687. ProxyAndTargetServers s;
  25688. Client cli("127.0.0.1", s.target_port());
  25689. cli.set_proxy("127.0.0.1", s.proxy_port());
  25690. cli.set_no_proxy({"127.0.0.0/8"});
  25691. auto res = cli.Get("/");
  25692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25693. EXPECT_EQ(0, s.proxy_hits());
  25694. EXPECT_EQ(1, s.target_hits());
  25695. }
  25696. TEST(NoProxyTest, IPv4CidrNonMatch) {
  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({"10.0.0.0/8"});
  25701. auto res = cli.Get("/");
  25702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25703. EXPECT_GE(s.proxy_hits(), 1);
  25704. EXPECT_EQ(0, s.target_hits());
  25705. }
  25706. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25707. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25708. // IPv4 target matches.
  25709. ProxyAndTargetServers s;
  25710. Client cli("127.0.0.1", s.target_port());
  25711. cli.set_proxy("127.0.0.1", s.proxy_port());
  25712. cli.set_no_proxy({"0.0.0.0/0"});
  25713. auto res = cli.Get("/");
  25714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25715. EXPECT_EQ(0, s.proxy_hits());
  25716. EXPECT_EQ(1, s.target_hits());
  25717. }
  25718. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25719. ProxyAndTargetServers s;
  25720. Client cli("127.0.0.1", s.target_port());
  25721. cli.set_proxy("127.0.0.1", s.proxy_port());
  25722. cli.set_no_proxy({"127.0.0.1"});
  25723. auto res = cli.Get("/");
  25724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25725. EXPECT_EQ(0, s.proxy_hits());
  25726. EXPECT_EQ(1, s.target_hits());
  25727. }
  25728. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25729. ProxyAndTargetServers s;
  25730. Client cli("127.0.0.1", s.target_port());
  25731. cli.set_proxy("127.0.0.1", s.proxy_port());
  25732. cli.set_no_proxy({"127.0.0.0/33"});
  25733. auto res = cli.Get("/");
  25734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25735. EXPECT_GE(s.proxy_hits(), 1);
  25736. EXPECT_EQ(0, s.target_hits());
  25737. }
  25738. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25739. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25740. ProxyAndTargetServers s;
  25741. Client cli("127.0.0.1", s.target_port());
  25742. cli.set_proxy("127.0.0.1", s.proxy_port());
  25743. cli.set_no_proxy({"127.0.0.1/"});
  25744. auto res = cli.Get("/");
  25745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25746. EXPECT_GE(s.proxy_hits(), 1);
  25747. EXPECT_EQ(0, s.target_hits());
  25748. }
  25749. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25750. ProxyAndTargetServers s;
  25751. auto cli = make_client("internal.corp", s);
  25752. cli->set_proxy_basic_auth("u", "p");
  25753. cli->set_no_proxy({"internal.corp"});
  25754. auto res = cli->Get("/");
  25755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25756. EXPECT_EQ(1, s.target_hits());
  25757. EXPECT_EQ(0, s.proxy_hits());
  25758. EXPECT_FALSE(s.last_had_proxy_authz())
  25759. << "Proxy-Authorization must not be sent direct to the target";
  25760. }
  25761. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25762. ProxyAndTargetServers s;
  25763. auto cli = make_client("public.example", s);
  25764. cli->set_proxy_basic_auth("u", "p");
  25765. cli->set_no_proxy({"internal.corp"}); // does not match
  25766. auto res = cli->Get("/");
  25767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25768. EXPECT_GE(s.proxy_hits(), 1);
  25769. EXPECT_TRUE(s.last_had_proxy_authz());
  25770. }
  25771. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25772. std::atomic<int> hits{0};
  25773. std::atomic<int> hits_with_authz{0};
  25774. no_proxy_test::ScopedServer proxy_mock;
  25775. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25776. hits++;
  25777. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25778. if (req.target.find("/redir") != std::string::npos) {
  25779. res.set_redirect("http://other.example/landed");
  25780. } else {
  25781. res.set_content("via-proxy", "text/plain");
  25782. }
  25783. });
  25784. proxy_mock.listen();
  25785. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25786. hits = 0;
  25787. hits_with_authz = 0;
  25788. Client cli("public.example", 80);
  25789. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25790. cli.set_proxy_basic_auth(c.first, c.second);
  25791. cli.set_follow_location(true);
  25792. // The redirect to another host goes through the proxy as well
  25793. auto res = cli.Get("/redir");
  25794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25795. EXPECT_EQ(2, hits.load());
  25796. EXPECT_EQ(2, hits_with_authz.load());
  25797. }
  25798. }
  25799. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25800. ProxyAndTargetServers s;
  25801. auto cli = make_client("anything.test", s);
  25802. auto res = cli->Get("/");
  25803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25804. EXPECT_GE(s.proxy_hits(), 1);
  25805. EXPECT_EQ(0, s.target_hits());
  25806. }
  25807. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25808. ProxyAndTargetServers s;
  25809. auto cli = make_client("example.com", s);
  25810. cli->set_no_proxy({"example.com:8080"});
  25811. auto res = cli->Get("/");
  25812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25813. EXPECT_GE(s.proxy_hits(), 1);
  25814. EXPECT_EQ(0, s.target_hits());
  25815. }
  25816. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25817. ProxyAndTargetServers s;
  25818. auto cli = make_client("anything.test", s);
  25819. cli->set_no_proxy({"", " ", "\t"});
  25820. auto res = cli->Get("/");
  25821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25822. EXPECT_GE(s.proxy_hits(), 1);
  25823. EXPECT_EQ(0, s.target_hits());
  25824. }
  25825. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25826. // An entry with leading/trailing whitespace must still match — env-style
  25827. // values are commonly pasted with stray spaces and an implementation
  25828. // that feeds the raw token directly to inet_pton would fail to match
  25829. // valid CIDRs because of the spaces.
  25830. ProxyAndTargetServers s;
  25831. Client cli("127.0.0.1", s.target_port());
  25832. cli.set_proxy("127.0.0.1", s.proxy_port());
  25833. cli.set_no_proxy({" 127.0.0.0/8 "});
  25834. auto res = cli.Get("/");
  25835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25836. EXPECT_EQ(0, s.proxy_hits());
  25837. EXPECT_EQ(1, s.target_hits());
  25838. }
  25839. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25840. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25841. // go direct and must NOT carry Proxy-Authorization.
  25842. std::atomic<int> proxy_hits{0};
  25843. std::atomic<int> target_hits{0};
  25844. std::atomic<bool> target_saw_authz{false};
  25845. no_proxy_test::ScopedServer proxy_mock, target;
  25846. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25847. proxy_hits++;
  25848. res.status = 302;
  25849. res.set_header("Location", "http://127.0.0.1:" +
  25850. std::to_string(target.port()) + "/landed");
  25851. });
  25852. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25853. target_hits++;
  25854. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25855. res.set_content("direct", "text/plain");
  25856. });
  25857. proxy_mock.listen();
  25858. target.listen();
  25859. Client cli("public.example", target.port());
  25860. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25861. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25862. cli.set_proxy_basic_auth("u", "p");
  25863. cli.set_no_proxy({"127.0.0.1"});
  25864. cli.set_follow_location(true);
  25865. auto res = cli.Get("/redir");
  25866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25867. EXPECT_GE(proxy_hits.load(), 1);
  25868. EXPECT_GE(target_hits.load(), 1);
  25869. EXPECT_FALSE(target_saw_authz.load());
  25870. }
  25871. #ifdef CPPHTTPLIB_SSL_ENABLED
  25872. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25873. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25874. // proxy creds would be sent to the (possibly hostile) origin.
  25875. std::atomic<int> target_hits{0};
  25876. std::atomic<bool> target_saw_proxy_authz{false};
  25877. no_proxy_test::ScopedServer target;
  25878. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25879. target_hits++;
  25880. if (req.has_header("Proxy-Authorization")) {
  25881. target_saw_proxy_authz = true;
  25882. }
  25883. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25884. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25885. "nonce=\"abc\", algorithm=MD5");
  25886. });
  25887. target.listen();
  25888. // The proxy address is set to the target's port: the bypass MUST kick in;
  25889. // if it doesn't, the test still routes "via proxy" to the same server and
  25890. // the Proxy-Authorization assertion below catches the leak.
  25891. Client cli("evil.example", target.port());
  25892. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25893. cli.set_proxy("127.0.0.1", target.port());
  25894. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25895. cli.set_no_proxy({"evil.example"});
  25896. auto res = cli.Get("/x");
  25897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25898. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25899. EXPECT_EQ(1, target_hits.load());
  25900. EXPECT_FALSE(target_saw_proxy_authz.load());
  25901. }
  25902. #endif
  25903. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25904. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25905. std::atomic<int> proxy_hits{0};
  25906. std::atomic<int> bypass_hits{0};
  25907. std::atomic<bool> proxy_saw_c_url{false};
  25908. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25909. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25910. proxy_hits++;
  25911. if (req.path.find("/start") != std::string::npos) {
  25912. res.status = 302;
  25913. res.set_header("Location", "http://127.0.0.1:" +
  25914. std::to_string(bypass_server.port()) +
  25915. "/middle");
  25916. return;
  25917. }
  25918. if (req.path.find("/end") != std::string::npos) {
  25919. proxy_saw_c_url = true;
  25920. res.set_content("c-via-proxy", "text/plain");
  25921. return;
  25922. }
  25923. res.set_content("unexpected", "text/plain");
  25924. });
  25925. // public.example's "advertised" port is arbitrary (the request never lands
  25926. // there — it goes through the proxy), but use a dynamic value to stay
  25927. // friendly with sharded parallel runs.
  25928. int public_port = bypass_server.port();
  25929. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25930. bypass_hits++;
  25931. res.status = 302;
  25932. res.set_header("Location", "http://public.example:" +
  25933. std::to_string(public_port) + "/end");
  25934. });
  25935. proxy_mock.listen();
  25936. bypass_server.listen();
  25937. Client cli("public.example", public_port);
  25938. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25939. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25940. cli.set_no_proxy({"127.0.0.1"});
  25941. cli.set_follow_location(true);
  25942. auto res = cli.Get("/start");
  25943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25944. EXPECT_EQ(StatusCode::OK_200, res->status);
  25945. EXPECT_EQ("c-via-proxy", res->body);
  25946. EXPECT_GE(proxy_hits.load(), 2);
  25947. EXPECT_GE(bypass_hits.load(), 1);
  25948. EXPECT_TRUE(proxy_saw_c_url.load());
  25949. }
  25950. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25951. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25952. // request reconnects to the correct endpoint.
  25953. std::atomic<int> proxy_hits{0};
  25954. std::atomic<int> target_hits{0};
  25955. no_proxy_test::ScopedServer proxy_mock, target;
  25956. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25957. proxy_hits++;
  25958. res.set_content("via-proxy", "text/plain");
  25959. });
  25960. target.svr().Get(".*", [&](const Request &, Response &res) {
  25961. target_hits++;
  25962. res.set_content("direct", "text/plain");
  25963. });
  25964. proxy_mock.listen();
  25965. target.listen();
  25966. Client cli("public.example", target.port());
  25967. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25968. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25969. cli.set_keep_alive(true);
  25970. auto res1 = cli.Get("/a");
  25971. ASSERT_TRUE(res1);
  25972. EXPECT_EQ("via-proxy", res1->body);
  25973. EXPECT_EQ(1, proxy_hits.load());
  25974. EXPECT_EQ(0, target_hits.load());
  25975. cli.set_no_proxy({"public.example"});
  25976. auto res2 = cli.Get("/b");
  25977. ASSERT_TRUE(res2);
  25978. EXPECT_EQ("direct", res2->body);
  25979. EXPECT_EQ(1, proxy_hits.load());
  25980. EXPECT_EQ(1, target_hits.load());
  25981. }
  25982. // Forward declarations (see the base64_encode note).
  25983. namespace httplib {
  25984. namespace detail {
  25985. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  25986. int shutdown_socket(socket_t sock) noexcept;
  25987. } // namespace detail
  25988. } // namespace httplib
  25989. namespace proxy_tunnel_test {
  25990. const char *const kTunnelEstablished =
  25991. "HTTP/1.1 200 Connection established\r\n\r\n";
  25992. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  25993. using ConnectReply = std::function<std::string(const std::string &head)>;
  25994. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  25995. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  25996. class ScopedConnectProxy {
  25997. public:
  25998. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  25999. : forward_port_(forward_port), reply_(std::move(reply)) {
  26000. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26001. if (listen_sock_ == INVALID_SOCKET) { return; }
  26002. auto a = loopback(0);
  26003. auto addr = reinterpret_cast<sockaddr *>(&a);
  26004. socklen_t alen = sizeof(a);
  26005. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26006. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26007. ::listen(listen_sock_, 4) != 0) {
  26008. return;
  26009. }
  26010. port_ = ntohs(a.sin_port);
  26011. th_ = std::thread([this] { run(); });
  26012. }
  26013. ~ScopedConnectProxy() {
  26014. if (th_.joinable()) {
  26015. stop_ = true;
  26016. auto wake = connect_to(port_);
  26017. th_.join();
  26018. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26019. }
  26020. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26021. }
  26022. int port() const { return port_; }
  26023. int connect_hits() const { return connect_hits_.load(); }
  26024. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26025. std::string connect_request() const {
  26026. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26027. return connect_request_;
  26028. }
  26029. private:
  26030. static sockaddr_in loopback(int port) {
  26031. sockaddr_in a{};
  26032. a.sin_family = AF_INET;
  26033. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26034. a.sin_port = htons(static_cast<unsigned short>(port));
  26035. return a;
  26036. }
  26037. static socket_t connect_to(int port) {
  26038. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26039. if (sock == INVALID_SOCKET) { return sock; }
  26040. auto a = loopback(port);
  26041. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26042. detail::close_socket(sock);
  26043. return INVALID_SOCKET;
  26044. }
  26045. return sock;
  26046. }
  26047. static bool send_all(socket_t sock, const char *data, size_t size) {
  26048. while (size > 0) {
  26049. auto n = detail::send_socket(sock, data, size, 0);
  26050. if (n <= 0) { return false; }
  26051. data += n;
  26052. size -= static_cast<size_t>(n);
  26053. }
  26054. return true;
  26055. }
  26056. void run() {
  26057. for (;;) {
  26058. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26059. if (stop_) {
  26060. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26061. return;
  26062. }
  26063. if (client == INVALID_SOCKET) { continue; }
  26064. serve(client);
  26065. detail::close_socket(client);
  26066. }
  26067. }
  26068. void serve(socket_t client) {
  26069. std::string head;
  26070. char buf[2048];
  26071. while (head.find("\r\n\r\n") == std::string::npos) {
  26072. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26073. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26074. if (n <= 0) { return; }
  26075. head.append(buf, static_cast<size_t>(n));
  26076. }
  26077. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26078. connect_hits_++;
  26079. {
  26080. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26081. connect_request_ = head;
  26082. }
  26083. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26084. if (!send_all(client, res.data(), res.size()) ||
  26085. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26086. return;
  26087. }
  26088. auto origin = connect_to(forward_port_);
  26089. if (origin == INVALID_SOCKET) { return; }
  26090. // When either side stops, shut both down so the other pump returns too.
  26091. auto pump = [&](socket_t from, socket_t to) {
  26092. char b[8192];
  26093. for (;;) {
  26094. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26095. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26096. }
  26097. detail::shutdown_socket(client);
  26098. detail::shutdown_socket(origin);
  26099. };
  26100. std::thread up([&] { pump(client, origin); });
  26101. pump(origin, client);
  26102. up.join();
  26103. detail::close_socket(origin);
  26104. }
  26105. int forward_port_;
  26106. ConnectReply reply_;
  26107. socket_t listen_sock_ = INVALID_SOCKET;
  26108. int port_ = 0;
  26109. std::thread th_;
  26110. std::atomic<bool> stop_{false};
  26111. std::atomic<int> connect_hits_{0};
  26112. mutable std::mutex connect_request_mutex_;
  26113. std::string connect_request_;
  26114. };
  26115. } // namespace proxy_tunnel_test
  26116. #ifdef CPPHTTPLIB_SSL_ENABLED
  26117. namespace proxy_tunnel_test {
  26118. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26119. class ScopedSSLServer {
  26120. public:
  26121. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26122. port_ = svr_.bind_to_any_port("127.0.0.1");
  26123. }
  26124. ~ScopedSSLServer() {
  26125. svr_.stop();
  26126. if (th_.joinable()) { th_.join(); }
  26127. }
  26128. SSLServer &svr() { return svr_; }
  26129. int port() const { return port_; }
  26130. void listen() {
  26131. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26132. svr_.wait_until_ready();
  26133. }
  26134. private:
  26135. SSLServer svr_;
  26136. std::thread th_;
  26137. int port_ = 0;
  26138. };
  26139. // Sends one request through the CONNECT proxy to the TLS origin with a
  26140. // credential configured for each hop, and checks that each credential reaches
  26141. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26142. // origin's (every header in origin_headers) on the tunnelled request.
  26143. void CredentialsStayWithTheirHop(
  26144. const std::function<void(SSLClient &)> &set_credentials,
  26145. const std::string &scheme,
  26146. const std::vector<std::string> &origin_headers = {"Authorization"},
  26147. bool stream = false) {
  26148. std::atomic<int> origin_hits{0};
  26149. std::atomic<bool> origin_saw_proxy_authz{false};
  26150. std::atomic<bool> origin_saw_headers{false};
  26151. ScopedSSLServer origin;
  26152. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26153. origin_hits++;
  26154. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26155. origin_saw_headers =
  26156. std::all_of(origin_headers.begin(), origin_headers.end(),
  26157. [&](const std::string &h) { return req.has_header(h); });
  26158. res.set_content("ok", "text/plain");
  26159. });
  26160. origin.listen();
  26161. ScopedConnectProxy proxy(origin.port());
  26162. ASSERT_NE(0, proxy.port());
  26163. // Pinned to 127.0.0.1 for the same reason as the test below.
  26164. SSLClient cli("127.0.0.1", origin.port());
  26165. cli.enable_server_certificate_verification(false);
  26166. cli.set_proxy("127.0.0.1", proxy.port());
  26167. set_credentials(cli);
  26168. if (stream) {
  26169. auto handle = cli.open_stream("GET", "/x");
  26170. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26171. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26172. } else {
  26173. auto res = cli.Get("/x");
  26174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26175. EXPECT_EQ(StatusCode::OK_200, res->status);
  26176. }
  26177. EXPECT_EQ(1, origin_hits.load());
  26178. EXPECT_EQ(1, proxy.connect_hits());
  26179. EXPECT_TRUE(origin_saw_headers.load());
  26180. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26181. << "Proxy-Authorization must not be sent inside the tunnel";
  26182. auto connect_req = proxy.connect_request();
  26183. EXPECT_NE(std::string::npos,
  26184. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26185. for (const auto &h : origin_headers) {
  26186. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26187. << h << " must not be sent to the proxy on CONNECT";
  26188. }
  26189. }
  26190. } // namespace proxy_tunnel_test
  26191. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26192. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26193. [](SSLClient &cli) {
  26194. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26195. cli.set_basic_auth("origin-user", "origin-pass");
  26196. },
  26197. "Basic");
  26198. }
  26199. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26200. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26201. [](SSLClient &cli) {
  26202. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26203. cli.set_basic_auth("origin-user", "origin-pass");
  26204. },
  26205. "Basic", {"Authorization"}, true);
  26206. }
  26207. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26208. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26209. [](SSLClient &cli) {
  26210. cli.set_proxy_bearer_token_auth("proxy-token");
  26211. cli.set_bearer_token_auth("origin-token");
  26212. },
  26213. "Bearer");
  26214. }
  26215. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26216. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26217. [](SSLClient &cli) {
  26218. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26219. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26220. {"Cookie", "sid=origin-session"},
  26221. {"X-Api-Key", "origin-key"}});
  26222. },
  26223. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26224. }
  26225. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26226. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26227. // retry; otherwise proxy creds would be sent to the origin.
  26228. std::atomic<int> origin_hits{0};
  26229. std::atomic<bool> origin_saw_proxy_authz{false};
  26230. proxy_tunnel_test::ScopedSSLServer origin;
  26231. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26232. origin_hits++;
  26233. if (req.has_header("Proxy-Authorization")) {
  26234. origin_saw_proxy_authz = true;
  26235. }
  26236. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26237. res.set_header("Proxy-Authenticate",
  26238. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26239. "algorithm=MD5");
  26240. });
  26241. origin.listen();
  26242. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26243. ASSERT_NE(0, proxy.port());
  26244. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26245. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26246. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26247. // and answer with its own status, making this test flaky.
  26248. SSLClient cli("127.0.0.1", origin.port());
  26249. cli.enable_server_certificate_verification(false);
  26250. cli.set_proxy("127.0.0.1", proxy.port());
  26251. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26252. auto res = cli.Get("/x");
  26253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26254. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26255. EXPECT_EQ(1, origin_hits.load());
  26256. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26257. EXPECT_EQ(1, proxy.connect_hits());
  26258. }
  26259. #endif
  26260. namespace proxy_tunnel_test {
  26261. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26262. // anything else gets a 407 with `challenge`.
  26263. ConnectReply require_proxy_auth(const std::string &expected,
  26264. const std::string &challenge) {
  26265. return [=](const std::string &head) -> std::string {
  26266. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26267. std::string::npos) {
  26268. return kTunnelEstablished;
  26269. }
  26270. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26271. "Proxy-Authenticate: " +
  26272. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26273. };
  26274. }
  26275. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26276. // request, then echoes.
  26277. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26278. ws.send(
  26279. "authorization:" + req.get_header_value("Authorization") +
  26280. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26281. std::string msg;
  26282. while (ws.read(msg)) {
  26283. ws.send(msg);
  26284. }
  26285. }
  26286. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26287. class ScopedWebSocketOrigin {
  26288. public:
  26289. ScopedWebSocketOrigin() {
  26290. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26291. server_.listen();
  26292. }
  26293. int port() const { return server_.port(); }
  26294. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26295. std::string url() const {
  26296. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26297. }
  26298. private:
  26299. no_proxy_test::ScopedServer server_;
  26300. };
  26301. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26302. // passed as a constructor header, and checks that each reaches only its hop.
  26303. void WebSocketCredentialsStayWithTheirHop(
  26304. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26305. const std::string &proxy_authz, const std::string &origin_authz) {
  26306. ScopedWebSocketOrigin origin;
  26307. ScopedConnectProxy proxy(
  26308. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26309. ASSERT_NE(0, proxy.port());
  26310. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26311. client.set_proxy("127.0.0.1", proxy.port());
  26312. set_proxy_credentials(client);
  26313. auto res = client.connect();
  26314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26315. std::string msg;
  26316. ASSERT_TRUE(client.read(msg));
  26317. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26318. client.close();
  26319. EXPECT_EQ(1, proxy.connect_hits());
  26320. EXPECT_EQ(std::string::npos,
  26321. proxy.connect_request().find("\r\nAuthorization: "))
  26322. << "origin credentials must not be sent to the proxy";
  26323. }
  26324. } // namespace proxy_tunnel_test
  26325. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26326. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26327. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26328. ASSERT_NE(0, proxy.port());
  26329. ws::WebSocketClient client(origin.url());
  26330. client.set_proxy("127.0.0.1", proxy.port());
  26331. auto res = client.connect();
  26332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26333. std::string msg;
  26334. ASSERT_TRUE(client.read(msg));
  26335. ASSERT_TRUE(client.send("hello"));
  26336. ASSERT_TRUE(client.read(msg));
  26337. EXPECT_EQ("hello", msg);
  26338. client.close();
  26339. EXPECT_EQ(1, proxy.connect_hits());
  26340. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26341. auto connect_req = proxy.connect_request();
  26342. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26343. EXPECT_NE(std::string::npos,
  26344. connect_req.find("\r\nHost: " + target + "\r\n"));
  26345. }
  26346. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26347. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26348. [](ws::WebSocketClient &cli) {
  26349. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26350. },
  26351. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26352. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26353. }
  26354. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26355. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26356. [](ws::WebSocketClient &cli) {
  26357. cli.set_proxy_bearer_token_auth("proxy-token");
  26358. },
  26359. "Bearer proxy-token", "Bearer origin-token");
  26360. }
  26361. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26362. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26363. proxy_tunnel_test::ScopedConnectProxy proxy(
  26364. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26365. "Basic " + detail::base64_encode("proxy-user:"),
  26366. "Basic realm=\"proxy\""));
  26367. ASSERT_NE(0, proxy.port());
  26368. ws::WebSocketClient client(origin.url());
  26369. client.set_proxy("127.0.0.1", proxy.port());
  26370. client.set_proxy_basic_auth("proxy-user", "");
  26371. auto res = client.connect();
  26372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26373. client.close();
  26374. EXPECT_EQ(1, proxy.connect_hits());
  26375. }
  26376. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26377. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26378. proxy_tunnel_test::ScopedConnectProxy proxy(
  26379. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26380. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26381. ASSERT_NE(0, proxy.port());
  26382. ws::WebSocketClient client(origin.url());
  26383. client.set_proxy("127.0.0.1", proxy.port());
  26384. auto res = client.connect();
  26385. EXPECT_FALSE(res);
  26386. EXPECT_EQ(Error::ProxyConnection, res.error());
  26387. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26388. EXPECT_EQ("Basic realm=\"proxy\"",
  26389. res.get_header_value("Proxy-Authenticate"));
  26390. EXPECT_FALSE(client.is_open());
  26391. }
  26392. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26393. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26394. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26395. ASSERT_NE(0, proxy.port());
  26396. ws::WebSocketClient client(origin.url());
  26397. client.set_proxy("127.0.0.1", proxy.port());
  26398. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26399. client.set_no_proxy({"127.0.0.1"});
  26400. auto res = client.connect();
  26401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26402. std::string msg;
  26403. ASSERT_TRUE(client.read(msg));
  26404. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26405. << "proxy credentials must not reach a bypassed origin";
  26406. client.close();
  26407. EXPECT_EQ(0, proxy.connect_hits());
  26408. }
  26409. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26410. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26411. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26412. ASSERT_NE(0, proxy.port());
  26413. ws::WebSocketClient client(origin.url());
  26414. client.set_proxy("127.0.0.1", proxy.port());
  26415. ASSERT_TRUE(client.connect());
  26416. ASSERT_TRUE(client.connect());
  26417. client.close();
  26418. EXPECT_EQ(2, proxy.connect_hits());
  26419. }
  26420. #ifdef CPPHTTPLIB_SSL_ENABLED
  26421. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26422. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26423. proxy_tunnel_test::ScopedConnectProxy proxy(
  26424. origin.port(), [](const std::string &head) -> std::string {
  26425. if (head.find(
  26426. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26427. std::string::npos) {
  26428. return proxy_tunnel_test::kTunnelEstablished;
  26429. }
  26430. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26431. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26432. "nonce=\"abc\", algorithm=MD5\r\n"
  26433. "Content-Length: 0\r\n\r\n";
  26434. });
  26435. ASSERT_NE(0, proxy.port());
  26436. ws::WebSocketClient client(origin.url());
  26437. client.set_proxy("127.0.0.1", proxy.port());
  26438. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26439. auto res = client.connect();
  26440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26441. std::string msg;
  26442. ASSERT_TRUE(client.read(msg));
  26443. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26444. client.close();
  26445. EXPECT_EQ(2, proxy.connect_hits());
  26446. }
  26447. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26448. proxy_tunnel_test::ScopedSSLServer origin;
  26449. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26450. origin.listen();
  26451. proxy_tunnel_test::ScopedConnectProxy proxy(
  26452. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26453. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26454. ASSERT_NE(0, proxy.port());
  26455. ws::WebSocketClient client(
  26456. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26457. client.enable_server_certificate_verification(false);
  26458. client.set_proxy("127.0.0.1", proxy.port());
  26459. client.set_proxy_bearer_token_auth("proxy-token");
  26460. auto res = client.connect();
  26461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26462. std::string msg;
  26463. ASSERT_TRUE(client.read(msg));
  26464. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26465. << "Proxy-Authorization must not be sent inside the tunnel";
  26466. client.close();
  26467. EXPECT_EQ(1, proxy.connect_hits());
  26468. }
  26469. #endif