test.cc 1018 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. std::vector<std::string> get_ca_names(ctx_t ctx);
  69. } // namespace tls
  70. } // namespace httplib
  71. #endif
  72. using namespace std;
  73. using namespace httplib;
  74. const char *HOST = "localhost";
  75. static int get_base_port() {
  76. const char *shard = getenv("GTEST_SHARD_INDEX");
  77. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  78. }
  79. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  80. // New standalone tests MUST use svr.bind_to_any_port() instead.
  81. const int PORT = get_base_port();
  82. const string LONG_QUERY_VALUE = string(25000, '@');
  83. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  84. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  85. const string TOO_LONG_QUERY_URL =
  86. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  87. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  88. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  89. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  90. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  91. return file.name == key;
  92. });
  93. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  94. return *it;
  95. #else
  96. if (it != items.end()) { return *it; }
  97. throw std::runtime_error("invalid multipart form data name error");
  98. #endif
  99. }
  100. static void read_file(const std::string &path, std::string &out) {
  101. std::ifstream fs(path, std::ios_base::binary);
  102. if (!fs) {
  103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  104. return;
  105. #else
  106. throw std::runtime_error("File not found: " + path);
  107. #endif
  108. }
  109. fs.seekg(0, std::ios_base::end);
  110. auto size = fs.tellg();
  111. fs.seekg(0);
  112. out.resize(static_cast<size_t>(size));
  113. fs.read(&out[0], static_cast<std::streamsize>(size));
  114. }
  115. class UnixSocketTest : public ::testing::Test {
  116. protected:
  117. void TearDown() override { std::remove(pathname_.c_str()); }
  118. void client_GET(const std::string &addr) {
  119. httplib::Client cli{addr};
  120. cli.set_address_family(AF_UNIX);
  121. ASSERT_TRUE(cli.is_valid());
  122. const auto &result = cli.Get(pattern_);
  123. ASSERT_TRUE(result) << "error: " << result.error();
  124. const auto &resp = result.value();
  125. EXPECT_EQ(resp.status, StatusCode::OK_200);
  126. EXPECT_EQ(resp.body, content_);
  127. }
  128. static std::string make_sock_path() {
  129. const char *shard = getenv("GTEST_SHARD_INDEX");
  130. return shard ? std::string("./httplib-server-") + shard + ".sock"
  131. : "./httplib-server.sock";
  132. }
  133. const std::string pathname_{make_sock_path()};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. // ".//x.sock", which is not taken for a URL
  154. client_GET("./" + pathname_.substr(1));
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_TRUE(s0.is_peer_alive());
  247. EXPECT_EQ(0, close(fds[1]));
  248. EXPECT_FALSE(s0.is_peer_alive());
  249. return true;
  250. });
  251. EXPECT_EQ(0, close(fds[0]));
  252. }
  253. TEST(SocketStream, wait_writable_INET) {
  254. sockaddr_in addr;
  255. memset(&addr, 0, sizeof(addr));
  256. addr.sin_family = AF_INET;
  257. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  258. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  259. int disconnected_svr_sock = -1;
  260. std::thread svr{[&] {
  261. const int s = socket(AF_INET, SOCK_STREAM, 0);
  262. ASSERT_LE(0, s);
  263. // PORT + 1 is shared with the SSL redirect tests and with
  264. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  265. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  266. // because that happens on a worker thread the ASSERT does not stop the
  267. // test: it runs on and fails at the disconnected_svr_sock check instead.
  268. default_socket_options(s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. // wait_writable() returns true because select_write() only checks if the
  292. // send buffer has space. Peer disconnection is detected later by send().
  293. EXPECT_TRUE(ss.wait_writable());
  294. return true;
  295. });
  296. ASSERT_EQ(0, close(disconnected_svr_sock));
  297. }
  298. #endif // #ifndef _WIN32
  299. TEST(SetSocketOptTest, TcpNoDelay) {
  300. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  301. ASSERT_NE(sock, INVALID_SOCKET);
  302. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  303. int val = 0;
  304. socklen_t len = sizeof(val);
  305. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  306. reinterpret_cast<char *>(&val), &len));
  307. EXPECT_NE(val, 0);
  308. detail::close_socket(sock);
  309. }
  310. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  311. // accept() reports failures through WSAGetLastError() on Windows and through
  312. // errno everywhere else. Asking the wrong one is what made the accept loop
  313. // treat every recoverable failure as fatal on Windows.
  314. struct Classification {
  315. bool resource;
  316. bool transient;
  317. };
  318. auto classify = [](int err) {
  319. #ifdef _WIN32
  320. WSASetLastError(err);
  321. #else
  322. errno = err;
  323. #endif
  324. // Read both before asserting: an assertion may clobber the error slot.
  325. Classification c;
  326. c.resource = detail::is_accept_resource_error();
  327. c.transient = detail::is_accept_transient_error();
  328. return c;
  329. };
  330. #ifdef _WIN32
  331. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  332. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  333. WSAECONNRESET, WSAECONNABORTED};
  334. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  335. #else
  336. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  337. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  338. ECONNABORTED};
  339. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  340. #endif
  341. for (auto err : resource_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.resource) << "error " << err;
  344. EXPECT_FALSE(c.transient) << "error " << err;
  345. }
  346. for (auto err : transient_errors) {
  347. const auto c = classify(err);
  348. EXPECT_TRUE(c.transient) << "error " << err;
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. }
  351. for (auto err : fatal_errors) {
  352. const auto c = classify(err);
  353. EXPECT_FALSE(c.resource) << "error " << err;
  354. EXPECT_FALSE(c.transient) << "error " << err;
  355. }
  356. #ifdef _WIN32
  357. WSASetLastError(0);
  358. #else
  359. errno = 0;
  360. #endif
  361. }
  362. TEST(ClientTest, MoveConstructible) {
  363. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  365. }
  366. TEST(ClientTest, MoveAssignable) {
  367. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  368. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  369. }
  370. #ifdef _WIN32
  371. TEST(StartupTest, WSAStartup) {
  372. WSADATA wsaData;
  373. int ret = WSAStartup(0x0002, &wsaData);
  374. ASSERT_EQ(0, ret);
  375. }
  376. #endif
  377. TEST(DecodePathTest, PercentCharacter) {
  378. EXPECT_EQ(
  379. decode_path_component(
  380. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  381. U8("descrip=Gastos áéíóúñÑ 6"));
  382. }
  383. TEST(DecodePathTest, PercentCharacterNUL) {
  384. string expected;
  385. expected.push_back('x');
  386. expected.push_back('\0');
  387. expected.push_back('x');
  388. EXPECT_EQ(decode_path_component("x%00x"), expected);
  389. }
  390. TEST(DecodePathTest, UnicodeEncoding) {
  391. // %u0041 = 'A' (1-byte UTF-8)
  392. EXPECT_EQ("A", decode_path_component("%u0041"));
  393. // %u00E9 = 'é' (2-byte UTF-8)
  394. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  395. // %u3042 = 'あ' (3-byte UTF-8)
  396. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  397. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  398. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  399. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  400. // neighbours)
  401. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  402. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  403. }
  404. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  405. // A sign or whitespace inside the two-character escape window must not be
  406. // accepted as a valid percent-encoding; the sequence is passed through
  407. // literally, matching decode_uri_component / decode_path_component.
  408. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  409. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  410. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  411. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  412. // Well-formed escapes still decode.
  413. EXPECT_EQ("-", decode_query_component("%2D", false));
  414. EXPECT_EQ("A", decode_query_component("%41", false));
  415. }
  416. TEST(SanitizeFilenameTest, VariousPatterns) {
  417. // Path traversal
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  420. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  421. // Normal and edge cases
  422. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  423. EXPECT_EQ("filename.txt",
  424. httplib::sanitize_filename("/path/to/filename.txt"));
  425. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  426. EXPECT_EQ("", httplib::sanitize_filename(".."));
  427. EXPECT_EQ("", httplib::sanitize_filename(""));
  428. // Null bytes stripped
  429. EXPECT_EQ("safe.txt",
  430. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  431. // Whitespace-only rejected
  432. EXPECT_EQ("", httplib::sanitize_filename(" "));
  433. }
  434. // Forward declaration (see the base64_encode note below): split builds move the
  435. // definition into httplib.cc, so re-declaring it here lets the test link.
  436. namespace httplib {
  437. namespace detail {
  438. bool is_chunked_transfer_encoding(const Headers &headers);
  439. } // namespace detail
  440. } // namespace httplib
  441. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  442. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  443. auto make = [](std::initializer_list<const char *> lines) {
  444. Headers h;
  445. for (auto te : lines) {
  446. if (te) { h.emplace("Transfer-Encoding", te); }
  447. }
  448. return h;
  449. };
  450. // Sole coding, matched case-insensitively.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  454. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  458. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  463. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  464. // were received, into one list. Headers preserves that order, so the answer
  465. // is decided by the last coding of the last line and the order the lines
  466. // arrived in is significant.
  467. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  470. // The split can fall anywhere in the list.
  471. EXPECT_TRUE(
  472. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  473. EXPECT_FALSE(
  474. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  475. // A trailing line naming no coding leaves the list ending in nothing, so it
  476. // must not inherit the chunked from the line before it.
  477. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  478. }
  479. // Forward declarations (see the base64_encode note below).
  480. namespace httplib {
  481. namespace detail {
  482. bool parse_status_line(const char *line, std::string &version, int &status,
  483. std::string &reason);
  484. std::string file_extension(const std::string &path);
  485. std::string
  486. find_content_type(const std::string &path,
  487. const std::map<std::string, std::string> &user_data,
  488. const std::string &default_content_type);
  489. bool can_compress_content_type(const std::string &content_type);
  490. bool is_prohibited_header_name(const std::string &name);
  491. #ifdef CPPHTTPLIB_SSL_ENABLED
  492. bool match_hostname(const std::string &pattern, const std::string &hostname);
  493. #endif
  494. } // namespace detail
  495. } // namespace httplib
  496. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  497. struct {
  498. const char *line;
  499. const char *version;
  500. int status;
  501. const char *reason;
  502. } cases[] = {
  503. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  504. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  505. // The reason phrase may be empty, or left out along with its space.
  506. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  507. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  508. };
  509. for (const auto &c : cases) {
  510. std::string version;
  511. int status = 0;
  512. std::string reason = "unset";
  513. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  514. << c.line;
  515. EXPECT_EQ(c.version, version);
  516. EXPECT_EQ(c.status, status);
  517. EXPECT_EQ(c.reason, reason);
  518. }
  519. }
  520. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  521. const char *lines[] = {
  522. "HTTP/2 200 OK\r\n",
  523. "HTTP/1.2 200 OK\r\n",
  524. "HTTP/1.1 20 OK\r\n",
  525. "HTTP/1.1 2000 OK\r\n",
  526. "HTTP/1.1 2x0 OK\r\n",
  527. "HTTP/1.1 200 OK\r\n",
  528. "HTTP/1.1 200OK\r\n",
  529. "HTTP/1.1 200 O\rK\r\n",
  530. "HTTP/1.1 200 OK",
  531. "HTTP/1.1 200 OK\r\nX",
  532. "",
  533. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  534. "HTTP/1.1 200 OK\n",
  535. #endif
  536. };
  537. for (auto line : lines) {
  538. std::string version;
  539. int status = 0;
  540. std::string reason;
  541. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  542. << line;
  543. }
  544. }
  545. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  546. // Long enough to overflow the stack when matched with std::regex.
  547. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  548. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  549. std::string version;
  550. int status = 0;
  551. std::string reason;
  552. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  553. EXPECT_EQ(200, status);
  554. EXPECT_EQ(long_reason, reason);
  555. }
  556. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  557. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  558. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  559. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  560. EXPECT_EQ("", detail::file_extension("noext"));
  561. EXPECT_EQ("", detail::file_extension("a."));
  562. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  563. EXPECT_EQ("", detail::file_extension("a.b-c"));
  564. // Long enough to overflow the stack when matched with std::regex.
  565. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  566. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  567. }
  568. #ifdef CPPHTTPLIB_SSL_ENABLED
  569. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  570. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  573. // A wildcard needs two labels after it, in the leftmost label only
  574. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  575. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  576. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  577. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  578. EXPECT_FALSE(
  579. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  580. // No name may have an empty label
  581. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  582. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  583. }
  584. #endif
  585. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  586. detail::case_ignore::hash hash;
  587. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  588. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  589. // Long enough to overflow the stack if hashed one call per character.
  590. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  591. }
  592. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  593. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  594. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  595. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  596. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  597. // Same 26-bit hash as html, svg and js.
  598. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  601. }
  602. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  603. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  604. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  605. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  606. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  607. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  608. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  609. // Same 26-bit hash as application/json.
  610. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  611. }
  612. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  613. Request req;
  614. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  615. EXPECT_TRUE(req.is_multipart_form_data());
  616. std::string boundary;
  617. EXPECT_TRUE(detail::parse_multipart_boundary(
  618. req.get_header_value("Content-Type"), boundary));
  619. EXPECT_EQ("x", boundary);
  620. }
  621. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  622. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  623. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  624. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  625. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  626. // Same 26-bit hash as REMOTE_ADDR.
  627. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  628. }
  629. // Forward declaration: in split builds split.py strips `inline` and moves the
  630. // definition into httplib.cc, so detail::base64_encode is not visible from the
  631. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  632. // in both header-only and split builds.
  633. namespace httplib {
  634. namespace detail {
  635. std::string base64_encode(const std::string &in);
  636. } // namespace detail
  637. } // namespace httplib
  638. TEST(Base64EncodeTest, KnownAnswers) {
  639. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  640. // where the accumulator's top bit is already set before the next shift.
  641. EXPECT_EQ("", detail::base64_encode(""));
  642. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  643. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  644. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  645. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  646. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  647. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  648. // High bytes keep the top bit set across several rounds.
  649. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  650. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  651. }
  652. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  653. string unescapedCharacters = "-_.!~*'()";
  654. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  655. }
  656. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  657. string reservedCharacters = ";,/?:@&=+$";
  658. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  659. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  660. }
  661. TEST(ClientQueryOrder, PreserveOrder) {
  662. // This test reproduces Issue #2259: client may reorder query parameters
  663. // when sending a GET request. The expected behavior is that the client
  664. // preserves the original query string order when the caller supplied it
  665. // as part of the path.
  666. Server svr;
  667. svr.Get("/", [&](const Request &req, Response &res) {
  668. // Echo back the raw target so the test can assert ordering
  669. res.set_content(req.target, "text/plain");
  670. });
  671. std::thread t{[&] { svr.listen(HOST, PORT); }};
  672. auto se = detail::scope_exit([&] {
  673. svr.stop();
  674. t.join();
  675. ASSERT_FALSE(svr.is_running());
  676. });
  677. svr.wait_until_ready();
  678. Client cli(HOST, PORT);
  679. ASSERT_TRUE(cli.is_valid());
  680. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  681. auto res = cli.Get(original);
  682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  683. // Expect the echoed target to exactly match the original path (order
  684. // preserved)
  685. EXPECT_EQ(res->body, original);
  686. }
  687. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  688. string chineseCharacters = U8("中国語");
  689. string russianCharacters = U8("дом");
  690. string brazilianCharacters = U8("óculos");
  691. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  692. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  693. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  694. "%D0%B4%D0%BE%D0%BC");
  695. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  696. }
  697. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  698. string unescapedCharacters = "-_.!~*'()";
  699. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  700. }
  701. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  702. string reservedCharacters = ";,/?:@&=+$";
  703. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  704. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  705. }
  706. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  707. string chineseCharacters = U8("中国語");
  708. string russianCharacters = U8("дом");
  709. string brazilianCharacters = U8("óculos");
  710. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  711. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  712. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  713. "%D0%B4%D0%BE%D0%BC");
  714. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  715. }
  716. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  717. // Issue #2082 use case: encoding path component with ampersand
  718. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  719. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  720. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  721. }
  722. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  723. string unescapedCharacters = "-_.!~*'()";
  724. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  725. }
  726. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  727. string reservedCharacters = ";,/?:@&=+$#";
  728. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  729. }
  730. TEST(EncodeUriTest, TestUTF8Characters) {
  731. string chineseCharacters = U8("中国語");
  732. string russianCharacters = U8("дом");
  733. string brazilianCharacters = U8("óculos");
  734. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  735. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  736. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  737. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  738. }
  739. TEST(EncodeUriTest, TestCompleteUri) {
  740. string uri =
  741. "https://example.com/path/to/resource?query=value&param=test#fragment";
  742. EXPECT_EQ(
  743. httplib::encode_uri(uri),
  744. "https://example.com/path/to/resource?query=value&param=test#fragment");
  745. }
  746. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  747. string uri =
  748. "https://example.com/path with spaces/file name.html?q=hello world";
  749. EXPECT_EQ(httplib::encode_uri(uri),
  750. "https://example.com/path%20with%20spaces/"
  751. "file%20name.html?q=hello%20world");
  752. }
  753. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  754. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  755. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  756. }
  757. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  758. string unescapedCharacters = "-_.!~*'()";
  759. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  760. }
  761. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  762. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  763. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  764. string encodedBrazilian = "%C3%B3culos";
  765. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  767. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  768. }
  769. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  770. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  772. "Piri Tommy Villiers - on & on");
  773. }
  774. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  775. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  776. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  777. }
  778. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  779. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  780. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  781. }
  782. TEST(DecodeUriTest, TestUTF8Characters) {
  783. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  784. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  785. string encodedBrazilian = "%C3%B3culos";
  786. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  787. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  788. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  789. }
  790. TEST(DecodeUriTest, TestCompleteUri) {
  791. string encodedUri = "https://example.com/path%20with%20spaces/"
  792. "file%20name.html?q=hello%20world";
  793. EXPECT_EQ(
  794. httplib::decode_uri(encodedUri),
  795. "https://example.com/path with spaces/file name.html?q=hello world");
  796. }
  797. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  798. string original =
  799. "https://example.com/path with spaces/file name.html?q=hello world";
  800. string encoded = httplib::encode_uri(original);
  801. string decoded = httplib::decode_uri(encoded);
  802. EXPECT_EQ(decoded, original);
  803. }
  804. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  805. // decode_uri is the inverse of encode_uri: an escaped reserved character
  806. // stays encoded so it is not promoted into a real delimiter, while
  807. // non-reserved escapes still decode (like JS decodeURI).
  808. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  809. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  810. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  811. "%3F%3A%40%26%3D%2B%24%2C%3B");
  812. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  813. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  814. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  815. "http://example.com/a%2Fb");
  816. // decode_uri_component still decodes the reserved character.
  817. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  818. }
  819. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  820. string original = "Piri Tommy Villiers - on & on";
  821. string encoded = httplib::encode_uri_component(original);
  822. string decoded = httplib::decode_uri_component(encoded);
  823. EXPECT_EQ(decoded, original);
  824. }
  825. TEST(TrimTests, TrimStringTests) {
  826. EXPECT_EQ("abc", detail::trim_copy("abc"));
  827. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  828. EXPECT_TRUE(detail::trim_copy("").empty());
  829. }
  830. TEST(AsciiTest, LocaleIndependentClassification) {
  831. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  832. // which consult the global C locale: std::isalnum(0xC5) can return true
  833. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  834. // helpers must classify every byte by the ASCII grammar alone.
  835. for (int i = 0; i < 256; i++) {
  836. auto c = static_cast<char>(i);
  837. auto is_digit = i >= '0' && i <= '9';
  838. auto is_upper = i >= 'A' && i <= 'Z';
  839. auto is_lower = i >= 'a' && i <= 'z';
  840. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  841. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  842. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  843. << "byte " << i;
  844. }
  845. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  846. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  847. // Non-ASCII bytes must be percent-encoded, never passed through as
  848. // alphanumeric.
  849. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  850. }
  851. TEST(FromCharsTest, Double) {
  852. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  853. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  854. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  855. auto parse = [](const std::string &s, double &v) {
  856. return detail::from_chars(s.data(), s.data() + s.size(), v);
  857. };
  858. double v = -1.0;
  859. // Representative quality values.
  860. EXPECT_EQ(parse("0", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.0);
  862. EXPECT_EQ(parse("1", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 1.0);
  864. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 0.8);
  866. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.001);
  868. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. // A missing integer or fractional part is tolerated.
  871. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  872. EXPECT_DOUBLE_EQ(v, 0.5);
  873. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 5.0);
  875. // Values outside [0, 1] still parse; the caller range-checks them.
  876. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  877. EXPECT_DOUBLE_EQ(v, 123.456);
  878. // Stops at the first byte that is not part of the number and reports where.
  879. std::string trailing = "0.9, text/html";
  880. auto r = parse(trailing, v);
  881. EXPECT_EQ(r.ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 0.9);
  883. EXPECT_EQ(*r.ptr, ',');
  884. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  885. // outright, and an 'e'/'E' simply ends the number.
  886. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  888. std::string exp_input = "1.5e3";
  889. r = parse(exp_input, v);
  890. EXPECT_EQ(r.ec, std::errc{});
  891. EXPECT_DOUBLE_EQ(v, 1.5);
  892. EXPECT_EQ(*r.ptr, 'e');
  893. // Invalid inputs.
  894. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  898. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  899. // Pathological but well-formed inputs must stay bounded (no overflow, no
  900. // out-of-bounds table access) and stay within [0, 1] for the caller.
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  902. std::errc{});
  903. EXPECT_DOUBLE_EQ(v, 0.0);
  904. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  905. std::errc{});
  906. EXPECT_GE(v, 0.0);
  907. EXPECT_LE(v, 1.0);
  908. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  909. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  910. }
  911. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  912. // Simple case without quality values
  913. std::vector<std::string> result1;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html,application/json,text/plain", result1));
  916. EXPECT_EQ(result1.size(), 3U);
  917. EXPECT_EQ(result1[0], "text/html");
  918. EXPECT_EQ(result1[1], "application/json");
  919. EXPECT_EQ(result1[2], "text/plain");
  920. // With quality values
  921. std::vector<std::string> result2;
  922. EXPECT_TRUE(detail::parse_accept_header(
  923. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  924. EXPECT_EQ(result2.size(), 3U);
  925. EXPECT_EQ(result2[0], "application/json"); // highest q value
  926. EXPECT_EQ(result2[1], "text/html");
  927. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  928. }
  929. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  930. // Mixed with and without quality values
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(
  933. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  934. EXPECT_EQ(result.size(), 3U);
  935. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  936. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  937. EXPECT_EQ(result[2], "application/json"); // q=0.5
  938. }
  939. TEST(ParseAcceptHeaderTest, EdgeCases) {
  940. // Empty header
  941. std::vector<std::string> empty_result;
  942. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  943. EXPECT_TRUE(empty_result.empty());
  944. // Single type
  945. std::vector<std::string> single_result;
  946. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  947. EXPECT_EQ(single_result.size(), 1U);
  948. EXPECT_EQ(single_result[0], "application/json");
  949. // Wildcard types
  950. std::vector<std::string> wildcard_result;
  951. EXPECT_TRUE(detail::parse_accept_header(
  952. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  953. EXPECT_EQ(wildcard_result.size(), 3U);
  954. EXPECT_EQ(wildcard_result[0], "application/json");
  955. EXPECT_EQ(wildcard_result[1], "text/*");
  956. EXPECT_EQ(wildcard_result[2], "*/*");
  957. }
  958. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  959. // Common browser Accept header
  960. std::vector<std::string> browser_result;
  961. EXPECT_TRUE(
  962. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  963. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  964. browser_result));
  965. EXPECT_EQ(browser_result.size(), 6U);
  966. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  970. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  971. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  972. // API client header
  973. std::vector<std::string> api_result;
  974. EXPECT_TRUE(detail::parse_accept_header(
  975. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  976. api_result));
  977. EXPECT_EQ(api_result.size(), 3U);
  978. EXPECT_EQ(api_result[0], "application/json");
  979. EXPECT_EQ(api_result[1], "application/xml");
  980. EXPECT_EQ(api_result[2], "text/plain");
  981. }
  982. TEST(ParseAcceptHeaderTest, SpecialCases) {
  983. // Quality value with 3 decimal places
  984. std::vector<std::string> decimal_result;
  985. EXPECT_TRUE(detail::parse_accept_header(
  986. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  987. EXPECT_EQ(decimal_result.size(), 2U);
  988. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  989. EXPECT_EQ(decimal_result[1], "text/html");
  990. // Zero quality (should still be included but with lowest priority)
  991. std::vector<std::string> zero_q_result;
  992. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  993. zero_q_result));
  994. EXPECT_EQ(zero_q_result.size(), 2U);
  995. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  996. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  997. // No spaces around commas
  998. std::vector<std::string> no_space_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1001. no_space_result));
  1002. EXPECT_EQ(no_space_result.size(), 3U);
  1003. EXPECT_EQ(no_space_result[0], "text/html");
  1004. EXPECT_EQ(no_space_result[1], "application/json");
  1005. EXPECT_EQ(no_space_result[2], "text/plain");
  1006. }
  1007. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1008. // Quality values always use '.' as the decimal separator, so parsing must
  1009. // not depend on the process locale. An embedding application may have
  1010. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1011. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1012. std::string saved = cur ? cur : "C";
  1013. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1014. "fr_FR.UTF-8"};
  1015. bool switched = false;
  1016. for (const auto loc : comma_locales) {
  1017. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1018. std::localeconv()->decimal_point[0] == ',') {
  1019. switched = true;
  1020. break;
  1021. }
  1022. }
  1023. if (!switched) {
  1024. std::setlocale(LC_NUMERIC, saved.c_str());
  1025. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1026. }
  1027. // The higher-weighted type appears later in the list, so a correct parse
  1028. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1029. // sensitive parse reads both weights as 0 and leaves the original order.
  1030. std::vector<std::string> result;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "application/json;q=0.1,text/html;q=0.9", result));
  1033. ASSERT_EQ(result.size(), 2U);
  1034. EXPECT_EQ(result[0], "text/html");
  1035. EXPECT_EQ(result[1], "application/json");
  1036. std::setlocale(LC_NUMERIC, saved.c_str());
  1037. }
  1038. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1039. std::vector<std::string> result;
  1040. // Invalid quality value (> 1.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1043. // Invalid quality value (< 0.0)
  1044. EXPECT_FALSE(
  1045. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1046. // Invalid quality value (not a number)
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=invalid,application/json", result));
  1049. // A valid numeric prefix does not make the entire quality value valid.
  1050. EXPECT_FALSE(detail::parse_accept_header(
  1051. "text/html;q=0.5junk,application/json", result));
  1052. // Empty quality value
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("text/html;q=,application/json", result));
  1055. // Invalid media type format (no slash and not wildcard)
  1056. EXPECT_FALSE(
  1057. detail::parse_accept_header("invalidtype,application/json", result));
  1058. // Valid cases should still work
  1059. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*/*");
  1062. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "*");
  1065. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "text/*");
  1068. }
  1069. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1070. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1071. // and must not be answered with 400 Bad Request.
  1072. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1073. struct {
  1074. const char *value;
  1075. std::vector<std::string> expected;
  1076. } cases[] = {
  1077. {",application/json", {"application/json"}},
  1078. {"text/html,", {"text/html"}},
  1079. {"text/html,,*/*", {"text/html", "*/*"}},
  1080. // An empty element may be spelled with whitespace in it
  1081. {"text/html, , application/json", {"text/html", "application/json"}},
  1082. // Nothing but empty elements is an empty list, which means the same
  1083. // thing as no Accept header at all
  1084. {",,,", {}},
  1085. // Quality values still apply across ignored empty elements
  1086. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1087. };
  1088. for (const auto &c : cases) {
  1089. std::vector<std::string> result;
  1090. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1091. << "value: " << c.value;
  1092. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1093. }
  1094. // An invalid entry is still rejected when empty elements surround it
  1095. std::vector<std::string> result;
  1096. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1097. }
  1098. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1099. // or ';' inside one does not end the list element or the parameter. Section
  1100. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1101. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1102. struct {
  1103. const char *value;
  1104. std::vector<std::string> expected;
  1105. } cases[] = {
  1106. {"text/html;profile=\"a,b\",application/json",
  1107. {"text/html", "application/json"}},
  1108. // A "q=" inside a quoted value is not the weight
  1109. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1110. {"text/html", "application/json"}},
  1111. // The weight after a quoted value still applies
  1112. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1113. {"application/json", "text/html"}},
  1114. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1115. {"application/json", "text/html"}},
  1116. {"text/html;profile=\"a\\\"b\",application/json",
  1117. {"text/html", "application/json"}},
  1118. // An escaped backslash does not escape the '"' after it
  1119. {"text/html;profile=\"a\\\\\",application/json",
  1120. {"text/html", "application/json"}},
  1121. };
  1122. for (const auto &c : cases) {
  1123. std::vector<std::string> result;
  1124. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1125. << "value: " << c.value;
  1126. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1127. }
  1128. }
  1129. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1130. Server svr;
  1131. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1132. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1133. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1134. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1135. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1136. res.set_content("ok", "text/plain");
  1137. });
  1138. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1139. EXPECT_TRUE(false);
  1140. res.set_content("bad request", "text/plain");
  1141. });
  1142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1143. auto se = detail::scope_exit([&] {
  1144. svr.stop();
  1145. listen_thread.join();
  1146. ASSERT_FALSE(svr.is_running());
  1147. });
  1148. svr.wait_until_ready();
  1149. Client cli("localhost", PORT);
  1150. {
  1151. auto res = cli.Get(
  1152. "/accept_ok",
  1153. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. auto res = cli.Get("/accept_bad_request",
  1159. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1162. }
  1163. }
  1164. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1165. Server svr;
  1166. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1167. res.set_content("ok", "text/plain");
  1168. });
  1169. std::atomic<int> start_count{0};
  1170. std::atomic<bool> running_when_called{false};
  1171. svr.set_start_handler([&]() {
  1172. running_when_called = svr.is_running();
  1173. start_count++;
  1174. });
  1175. auto port = svr.bind_to_any_port(HOST);
  1176. std::thread t([&]() { svr.listen_after_bind(); });
  1177. auto se = detail::scope_exit([&] {
  1178. svr.stop();
  1179. t.join();
  1180. ASSERT_FALSE(svr.is_running());
  1181. });
  1182. svr.wait_until_ready();
  1183. // A successful request proves the accept loop is running, which the start
  1184. // handler precedes; so by now the handler must have run exactly once.
  1185. Client cli(HOST, port);
  1186. cli.set_connection_timeout(std::chrono::seconds(5));
  1187. auto res = cli.Get("/");
  1188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1189. EXPECT_EQ(StatusCode::OK_200, res->status);
  1190. EXPECT_EQ(1, start_count.load());
  1191. EXPECT_TRUE(running_when_called.load());
  1192. }
  1193. TEST(DivideTest, DivideStringTests) {
  1194. auto divide = [](const std::string &str, char d) {
  1195. std::string lhs;
  1196. std::string rhs;
  1197. detail::divide(str, d,
  1198. [&](const char *lhs_data, std::size_t lhs_size,
  1199. const char *rhs_data, std::size_t rhs_size) {
  1200. lhs.assign(lhs_data, lhs_size);
  1201. rhs.assign(rhs_data, rhs_size);
  1202. });
  1203. return std::make_pair(std::move(lhs), std::move(rhs));
  1204. };
  1205. {
  1206. const auto res = divide("", '=');
  1207. EXPECT_EQ(res.first, "");
  1208. EXPECT_EQ(res.second, "");
  1209. }
  1210. {
  1211. const auto res = divide("=", '=');
  1212. EXPECT_EQ(res.first, "");
  1213. EXPECT_EQ(res.second, "");
  1214. }
  1215. {
  1216. const auto res = divide(" ", '=');
  1217. EXPECT_EQ(res.first, " ");
  1218. EXPECT_EQ(res.second, "");
  1219. }
  1220. {
  1221. const auto res = divide("a", '=');
  1222. EXPECT_EQ(res.first, "a");
  1223. EXPECT_EQ(res.second, "");
  1224. }
  1225. {
  1226. const auto res = divide("a=", '=');
  1227. EXPECT_EQ(res.first, "a");
  1228. EXPECT_EQ(res.second, "");
  1229. }
  1230. {
  1231. const auto res = divide("=b", '=');
  1232. EXPECT_EQ(res.first, "");
  1233. EXPECT_EQ(res.second, "b");
  1234. }
  1235. {
  1236. const auto res = divide("a=b", '=');
  1237. EXPECT_EQ(res.first, "a");
  1238. EXPECT_EQ(res.second, "b");
  1239. }
  1240. {
  1241. const auto res = divide("a=b=", '=');
  1242. EXPECT_EQ(res.first, "a");
  1243. EXPECT_EQ(res.second, "b=");
  1244. }
  1245. {
  1246. const auto res = divide("a=b=c", '=');
  1247. EXPECT_EQ(res.first, "a");
  1248. EXPECT_EQ(res.second, "b=c");
  1249. }
  1250. }
  1251. TEST(SplitTest, ParseQueryString) {
  1252. string s = "key1=val1&key2=val2&key3=val3";
  1253. Params dic;
  1254. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1255. [&](const char *b, const char *e) {
  1256. string key, val;
  1257. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1258. if (key.empty()) {
  1259. key.assign(b2, e2);
  1260. } else {
  1261. val.assign(b2, e2);
  1262. }
  1263. });
  1264. dic.emplace(key, val);
  1265. });
  1266. EXPECT_EQ("val1", dic.find("key1")->second);
  1267. EXPECT_EQ("val2", dic.find("key2")->second);
  1268. EXPECT_EQ("val3", dic.find("key3")->second);
  1269. }
  1270. TEST(SplitTest, ParseInvalidQueryTests) {
  1271. {
  1272. string s = " ";
  1273. Params dict;
  1274. detail::parse_query_text(s, dict);
  1275. EXPECT_TRUE(dict.empty());
  1276. }
  1277. {
  1278. string s = " = =";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. }
  1284. TEST(ParseQueryTest, ParseQueryString) {
  1285. {
  1286. std::string s = "key1=val1&key2=val2&key3=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("val1", dic.find("key1")->second);
  1290. EXPECT_EQ("val2", dic.find("key2")->second);
  1291. EXPECT_EQ("val3", dic.find("key3")->second);
  1292. }
  1293. {
  1294. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1295. Params dic;
  1296. detail::parse_query_text(s, dic);
  1297. EXPECT_EQ("", dic.find("key1")->second);
  1298. EXPECT_EQ("val1", dic.find("key2")->second);
  1299. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1300. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1301. }
  1302. }
  1303. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1304. Params dic;
  1305. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1306. dic.emplace("key1", "val1");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1308. dic.emplace("key2", "val2");
  1309. dic.emplace("key3", "val3");
  1310. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1311. }
  1312. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1313. Params params;
  1314. params.emplace("a", "1");
  1315. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1316. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1317. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1318. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1319. // Long enough to overflow the stack when matched with std::regex.
  1320. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1321. EXPECT_EQ("/p?" + long_query + "&a=1",
  1322. append_query_params("/p?" + long_query, params));
  1323. }
  1324. // Joins every entry of a Headers or Params into "key=value " so a whole
  1325. // traversal can be compared in one assertion. Both are instantiations of the
  1326. // same insertion-ordered container, so one helper serves both.
  1327. template <typename Map> static std::string entries_to_string(const Map &m) {
  1328. std::string s;
  1329. for (const auto &entry : m) {
  1330. s += entry.first + "=" + entry.second + " ";
  1331. }
  1332. return s;
  1333. }
  1334. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1335. // Params used to be a std::multimap, which sorted by name and handed the
  1336. // caller's query back alphabetised. A client signing its query string could
  1337. // not reproduce the order it asked for.
  1338. Params dic;
  1339. dic.emplace("zulu", "1");
  1340. dic.emplace("alpha", "2");
  1341. dic.emplace("mike", "3");
  1342. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1343. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1344. }
  1345. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1346. Params dic;
  1347. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1349. }
  1350. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1351. Request req;
  1352. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1353. req.params);
  1354. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag"));
  1356. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1357. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1358. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1359. EXPECT_EQ("", req.get_param_value("tag", 3));
  1360. }
  1361. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1362. // Params shares its container with Headers, which matches field names
  1363. // case-insensitively. Parameter names must not pick that up.
  1364. Params dic;
  1365. dic.emplace("Key", "upper");
  1366. dic.emplace("key", "lower");
  1367. EXPECT_EQ(2U, dic.size());
  1368. EXPECT_EQ(1U, dic.count("Key"));
  1369. EXPECT_EQ(1U, dic.count("key"));
  1370. EXPECT_EQ("upper", dic.find("Key")->second);
  1371. EXPECT_EQ("lower", dic.find("key")->second);
  1372. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1373. }
  1374. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1375. Server svr;
  1376. std::string order;
  1377. svr.Get("/order", [&](const Request &req, Response &res) {
  1378. order = entries_to_string(req.params);
  1379. res.set_content("ok", "text/plain");
  1380. });
  1381. auto port = svr.bind_to_any_port(HOST);
  1382. thread t = thread([&] { svr.listen_after_bind(); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. t.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, port);
  1390. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1391. ASSERT_TRUE(res);
  1392. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1393. }
  1394. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1395. Server svr;
  1396. std::string field_order, file_order;
  1397. svr.Post("/order", [&](const Request &req, Response &res) {
  1398. for (const auto &field : req.form.fields) {
  1399. field_order += field.first + "=" + field.second.content + " ";
  1400. }
  1401. for (const auto &file : req.form.files) {
  1402. file_order += file.first + "=" + file.second.filename + " ";
  1403. }
  1404. res.set_content("ok", "text/plain");
  1405. });
  1406. auto port = svr.bind_to_any_port(HOST);
  1407. thread t = thread([&] { svr.listen_after_bind(); });
  1408. auto se = detail::scope_exit([&] {
  1409. svr.stop();
  1410. t.join();
  1411. ASSERT_FALSE(svr.is_running());
  1412. });
  1413. svr.wait_until_ready();
  1414. UploadFormDataItems items = {
  1415. {"zulu", "1", "", ""},
  1416. {"alpha", "2", "", ""},
  1417. {"mike", "3", "", ""},
  1418. {"zebra", "z", "z.txt", "text/plain"},
  1419. {"apple", "a", "a.txt", "text/plain"},
  1420. };
  1421. Client cli(HOST, port);
  1422. auto res = cli.Post("/order", items);
  1423. ASSERT_TRUE(res);
  1424. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1425. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1426. }
  1427. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1428. Server svr;
  1429. std::vector<std::string> values;
  1430. std::string first, second, out_of_range, order;
  1431. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1432. values = req.form.get_fields("tag");
  1433. first = req.form.get_field("tag", 0);
  1434. second = req.form.get_field("tag", 1);
  1435. out_of_range = req.form.get_field("tag", 2);
  1436. for (const auto &field : req.form.fields) {
  1437. order += field.first + "=" + field.second.content + " ";
  1438. }
  1439. res.set_content("ok", "text/plain");
  1440. });
  1441. auto port = svr.bind_to_any_port(HOST);
  1442. thread t = thread([&] { svr.listen_after_bind(); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. t.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1450. // not adjacent in the container.
  1451. UploadFormDataItems items = {
  1452. {"tag", "first", "", ""},
  1453. {"other", "x", "", ""},
  1454. {"tag", "second", "", ""},
  1455. };
  1456. Client cli(HOST, port);
  1457. auto res = cli.Post("/repeated", items);
  1458. ASSERT_TRUE(res);
  1459. ASSERT_EQ(2U, values.size());
  1460. EXPECT_EQ("first", values[0]);
  1461. EXPECT_EQ("second", values[1]);
  1462. EXPECT_EQ("first", first);
  1463. EXPECT_EQ("second", second);
  1464. // std::multimap already kept entries sharing a name in insertion order, so
  1465. // everything above passes without this change too. The whole traversal is
  1466. // what tells the two apart: sorting by name would hoist "other" to the front
  1467. // and the two "tag" parts would end up adjacent.
  1468. EXPECT_EQ("tag=first other=x tag=second ", order);
  1469. // Advancing past the last entry of a name used to run off the container;
  1470. // the container's saturating increment makes it return the default instead.
  1471. EXPECT_EQ("", out_of_range);
  1472. }
  1473. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1474. Server svr;
  1475. std::string file_names;
  1476. svr.Post("/upload", [&](const Request &req, Response &res) {
  1477. for (const auto &file : req.form.files) {
  1478. file_names += file.first + "|" + file.second.filename + " ";
  1479. }
  1480. res.set_content("ok", "text/plain");
  1481. });
  1482. auto port = svr.bind_to_any_port(HOST);
  1483. thread t = thread([&] { svr.listen_after_bind(); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. t.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. // A trailing backslash would otherwise escape the closing quote.
  1491. UploadFormDataItems items = {
  1492. {"dir\\", "x", "a.txt", "text/plain"},
  1493. {"b", "y", "a\\\\b.txt", "text/plain"},
  1494. };
  1495. Client cli(HOST, port);
  1496. auto res = cli.Post("/upload", items);
  1497. ASSERT_TRUE(res);
  1498. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1499. }
  1500. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1501. // Server::read_content() keeps a FormFields::iterator alive across the
  1502. // content callbacks that fill the part it points at. The container is
  1503. // vector-backed, so a later emplace can reallocate and invalidate an older
  1504. // iterator; 64 parts grow the vector through seven reallocations, which
  1505. // checks that every part's content still lands in its own entry.
  1506. const size_t part_count = 64;
  1507. // One formula for both the parts sent and the values expected back, so the
  1508. // two cannot drift apart.
  1509. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1510. auto content_of = [](size_t i) {
  1511. return std::string(64, static_cast<char>('a' + (i % 26)));
  1512. };
  1513. Server svr;
  1514. std::vector<std::pair<std::string, std::string>> received;
  1515. svr.Post("/many", [&](const Request &req, Response &res) {
  1516. for (const auto &field : req.form.fields) {
  1517. received.emplace_back(field.first, field.second.content);
  1518. }
  1519. res.set_content("ok", "text/plain");
  1520. });
  1521. auto port = svr.bind_to_any_port(HOST);
  1522. thread t = thread([&] { svr.listen_after_bind(); });
  1523. auto se = detail::scope_exit([&] {
  1524. svr.stop();
  1525. t.join();
  1526. ASSERT_FALSE(svr.is_running());
  1527. });
  1528. svr.wait_until_ready();
  1529. UploadFormDataItems items;
  1530. for (size_t i = 0; i < part_count; i++) {
  1531. items.push_back({name_of(i), content_of(i), "", ""});
  1532. }
  1533. Client cli(HOST, port);
  1534. auto res = cli.Post("/many", items);
  1535. ASSERT_TRUE(res);
  1536. ASSERT_EQ(part_count, received.size());
  1537. for (size_t i = 0; i < part_count; i++) {
  1538. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1539. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1540. }
  1541. }
  1542. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1543. string content_type = "multipart/form-data; boundary=something";
  1544. string boundary;
  1545. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(boundary, "something");
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1550. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1551. string boundary;
  1552. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1553. EXPECT_TRUE(ret);
  1554. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1557. string content_type =
  1558. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1559. string boundary;
  1560. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1561. EXPECT_TRUE(ret);
  1562. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1565. string content_type =
  1566. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1567. string boundary;
  1568. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1569. EXPECT_TRUE(ret);
  1570. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1571. }
  1572. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1573. const string boundary(70, 'a');
  1574. string content_type = "multipart/form-data; boundary=" + boundary;
  1575. string parsed;
  1576. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1577. EXPECT_TRUE(ret);
  1578. EXPECT_EQ(parsed, boundary);
  1579. }
  1580. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1581. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1582. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1583. string parsed;
  1584. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1585. EXPECT_FALSE(ret);
  1586. }
  1587. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1588. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1589. // is 72 characters on the wire and still valid.
  1590. const string boundary(70, 'a');
  1591. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1592. string parsed;
  1593. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1594. EXPECT_EQ(parsed, boundary);
  1595. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1596. parsed.clear();
  1597. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1598. }
  1599. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1600. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1601. // The parameter parser must not treat that '=' as the key/value separator.
  1602. string content_type =
  1603. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1604. "charset=UTF-8";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1608. }
  1609. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1610. // A ';' inside the quoted-string is part of the value, not a parameter
  1611. // separator, so it must not truncate the boundary.
  1612. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1613. string parsed;
  1614. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1615. EXPECT_EQ(parsed, "a;b");
  1616. }
  1617. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1621. EXPECT_EQ("a\\b", parsed);
  1622. EXPECT_TRUE(detail::parse_multipart_boundary(
  1623. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1624. EXPECT_EQ("a\"b", parsed);
  1625. }
  1626. TEST(ParseDispositionParamsTest, QuotedValues) {
  1627. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1628. // ';' and '=' are ordinary characters inside one.
  1629. struct {
  1630. const char *value;
  1631. std::vector<std::pair<const char *, const char *>> expected;
  1632. } cases[] = {
  1633. {"name=\"file1\"; filename=\"a.txt\"",
  1634. {{"name", "file1"}, {"filename", "a.txt"}}},
  1635. // Whitespace around '=' and ';' is still trimmed
  1636. {"name=\"file2\" ;filename = \"a.html\"",
  1637. {{"name", "file2"}, {"filename", "a.html"}}},
  1638. // '=' inside the value used to leave only the text after the last one
  1639. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1640. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1641. {"name=\"x=y\"", {{"name", "x=y"}}},
  1642. // ';' inside the value used to truncate the pair and leave a bogus one
  1643. {"name=\"file3\"; filename=\"a;b.txt\"",
  1644. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1645. // An unquoted value keeps working, and so does filename*
  1646. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1647. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1648. // A parameter with no key is dropped rather than turned into one whose
  1649. // key is the value
  1650. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1651. // An escaped quote does not end the value
  1652. {"name=\"a\\\"; filename=evil.php\"",
  1653. {{"name", "a\"; filename=evil.php"}}},
  1654. // Other backslashes, as in a Windows path, are kept
  1655. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1656. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1657. };
  1658. for (const auto &c : cases) {
  1659. Params params;
  1660. detail::parse_disposition_params(c.value, params);
  1661. for (const auto &kv : c.expected) {
  1662. auto it = params.find(kv.first);
  1663. ASSERT_NE(it, params.end())
  1664. << "value: " << c.value << ", key: " << kv.first;
  1665. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1666. }
  1667. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1668. }
  1669. }
  1670. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1671. Server svr;
  1672. std::string filename;
  1673. std::string content;
  1674. svr.Post("/upload", [&](const Request &req, Response &) {
  1675. const auto &file = req.form.get_file("file");
  1676. filename = file.filename;
  1677. content = file.content;
  1678. });
  1679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1680. auto se = detail::scope_exit([&] {
  1681. svr.stop();
  1682. thread.join();
  1683. ASSERT_FALSE(svr.is_running());
  1684. });
  1685. svr.wait_until_ready();
  1686. std::string body = "--B\r\n"
  1687. "Content-Disposition: form-data; name=\"file\"; "
  1688. "filename=\"a.txt\"\r\n"
  1689. "Content-Type: text/plain\r\n"
  1690. "\r\n"
  1691. "hello\r\n"
  1692. "--B--\r\n";
  1693. Client cli(HOST, PORT);
  1694. auto res = cli.Post(
  1695. "/upload",
  1696. [&](size_t offset, DataSink &sink) {
  1697. if (offset < body.size()) {
  1698. sink.write(&body[offset], 1);
  1699. } else {
  1700. sink.done();
  1701. }
  1702. return true;
  1703. },
  1704. "multipart/form-data; boundary=B");
  1705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1706. EXPECT_EQ(StatusCode::OK_200, res->status);
  1707. EXPECT_EQ("a.txt", filename);
  1708. EXPECT_EQ("hello", content);
  1709. }
  1710. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1711. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1712. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1713. Server svr;
  1714. std::string field_value, file_name, file_filename;
  1715. bool has_field = false, has_file = false;
  1716. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1717. has_field = req.form.has_field("x=y");
  1718. field_value = req.form.get_field("x=y");
  1719. has_file = req.form.has_file("file1");
  1720. const auto &file = req.form.get_file("file1");
  1721. file_name = file.name;
  1722. file_filename = file.filename;
  1723. res.set_content("ok", "text/plain");
  1724. });
  1725. auto port = svr.bind_to_any_port(HOST);
  1726. thread t = thread([&] { svr.listen_after_bind(); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. t.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. UploadFormDataItems items = {
  1734. {"x=y", "field-value", "", ""},
  1735. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1736. };
  1737. Client cli(HOST, port);
  1738. auto res = cli.Post("/quoted", items);
  1739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1740. ASSERT_EQ(StatusCode::OK_200, res->status);
  1741. EXPECT_TRUE(has_field);
  1742. EXPECT_EQ("field-value", field_value);
  1743. EXPECT_TRUE(has_file);
  1744. EXPECT_EQ("file1", file_name);
  1745. EXPECT_EQ("a;b=report.pdf", file_filename);
  1746. }
  1747. TEST(GetHeaderValueTest, DefaultValue) {
  1748. Headers headers = {{"Dummy", "Dummy"}};
  1749. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1750. EXPECT_STREQ("text/plain", val);
  1751. }
  1752. TEST(GetHeaderValueTest, DefaultValueInt) {
  1753. Headers headers = {{"Dummy", "Dummy"}};
  1754. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1755. EXPECT_EQ(100ull, val);
  1756. }
  1757. TEST(GetHeaderValueTest, RegularValue) {
  1758. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1759. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1760. EXPECT_STREQ("text/html", val);
  1761. }
  1762. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1763. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1764. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1765. EXPECT_STREQ("text/html", val);
  1766. }
  1767. TEST(GetHeaderValueTest, SetContent) {
  1768. Response res;
  1769. res.set_content("html", "text/html");
  1770. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1771. res.set_content("text", "text/plain");
  1772. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1773. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueInt) {
  1776. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1778. EXPECT_EQ(100ull, val);
  1779. }
  1780. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1781. Headers headers = {{"Content-Length", "x"}};
  1782. auto is_invalid_value = false;
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1784. is_invalid_value);
  1785. EXPECT_EQ(0ull, val);
  1786. EXPECT_TRUE(is_invalid_value);
  1787. }
  1788. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1789. // An all-digit value that overflows size_t must be reported as invalid, not
  1790. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1791. // a large length to a small one on 32-bit builds, leaving the framing length
  1792. // wrong while is_invalid_value stayed false.
  1793. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1794. auto is_invalid_value = false;
  1795. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1796. is_invalid_value);
  1797. EXPECT_TRUE(is_invalid_value);
  1798. // A well-formed length is unaffected.
  1799. Headers ok = {{"Content-Length", "1234"}};
  1800. is_invalid_value = false;
  1801. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_EQ(1234ull, val);
  1804. EXPECT_FALSE(is_invalid_value);
  1805. }
  1806. TEST(GetHeaderValueTest, Range) {
  1807. {
  1808. Headers headers = {make_range_header({{1, -1}})};
  1809. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1810. EXPECT_STREQ("bytes=1-", val);
  1811. }
  1812. {
  1813. Headers headers = {make_range_header({{-1, 1}})};
  1814. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1815. EXPECT_STREQ("bytes=-1", val);
  1816. }
  1817. {
  1818. Headers headers = {make_range_header({{1, 10}})};
  1819. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1820. EXPECT_STREQ("bytes=1-10", val);
  1821. }
  1822. {
  1823. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1824. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1825. EXPECT_STREQ("bytes=1-10, 100-", val);
  1826. }
  1827. {
  1828. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1829. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1830. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1831. }
  1832. {
  1833. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1834. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1835. EXPECT_STREQ("bytes=0-0, -1", val);
  1836. }
  1837. }
  1838. TEST(BearerTokenAuthTest, SchemeValidation) {
  1839. // A value shorter than "Bearer " must not throw from the fixed-length
  1840. // substr, and a non-Bearer scheme must not be reported as a token.
  1841. struct {
  1842. const char *value;
  1843. const char *expected;
  1844. } cases[] = {
  1845. {"x", ""},
  1846. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1847. {"Bearer abc123", "abc123"},
  1848. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1849. };
  1850. for (const auto &c : cases) {
  1851. Request req;
  1852. req.set_header("Authorization", c.value);
  1853. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1854. }
  1855. }
  1856. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1857. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1858. // to depend on the standard library (libstdc++ handed back duplicates in
  1859. // reverse insertion order, libc++ in insertion order).
  1860. Request req;
  1861. req.set_header("Accept-Encoding", "gzip");
  1862. req.set_header("Accept-Encoding", "deflate");
  1863. req.set_header("Accept-Encoding", "br");
  1864. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1866. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1867. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1868. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1869. }
  1870. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1871. Request req;
  1872. req.set_header("X-Test", "only");
  1873. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1875. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1876. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1877. }
  1878. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1879. Request req;
  1880. req.set_header("X-First", "1");
  1881. req.set_header("X-Test", "2");
  1882. req.params.emplace("first", "1");
  1883. req.params.emplace("test", "2");
  1884. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1885. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1886. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1887. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1888. // The second one is negative when read as a signed value
  1889. const auto max_id = (std::numeric_limits<size_t>::max)();
  1890. for (auto id : {max_id / 2, max_id}) {
  1891. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1892. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1893. EXPECT_EQ("", req.get_param_value("test", id));
  1894. EXPECT_EQ("", req.form.get_field("test", id));
  1895. EXPECT_EQ("", req.form.get_file("test", id).content);
  1896. }
  1897. }
  1898. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1899. Headers headers;
  1900. headers.emplace("Host", "example.com");
  1901. headers.emplace("Accept-Encoding", "gzip");
  1902. headers.emplace("User-Agent", "test");
  1903. headers.emplace("Accept-Encoding", "deflate");
  1904. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1905. "Accept-Encoding=deflate ",
  1906. entries_to_string(headers));
  1907. }
  1908. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1909. Headers headers = {{"Content-Type", "text/html"},
  1910. {"CONTENT-TYPE", "text/xml"}};
  1911. EXPECT_EQ(2U, headers.count("content-type"));
  1912. auto it = headers.find("content-type");
  1913. ASSERT_TRUE(it != headers.end());
  1914. EXPECT_EQ("text/html", it->second);
  1915. }
  1916. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1917. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1918. // drop only those fields and leave everything positioned between them.
  1919. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1920. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1921. auto rng = headers.equal_range("a");
  1922. headers.erase(rng.first, rng.second);
  1923. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1924. }
  1925. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1926. Headers headers = {
  1927. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1928. EXPECT_EQ(3U, headers.erase("A"));
  1929. EXPECT_EQ(0U, headers.count("A"));
  1930. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1933. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1934. headers.emplace_front("Host", "example.com");
  1935. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1936. entries_to_string(headers));
  1937. }
  1938. TEST(ParseHeaderValueTest, Range) {
  1939. {
  1940. Ranges ranges;
  1941. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1944. }
  1945. {
  1946. Ranges ranges;
  1947. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1948. EXPECT_TRUE(ret);
  1949. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1960. EXPECT_FALSE(ret);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1965. EXPECT_TRUE(ret);
  1966. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret =
  1971. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1990. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1991. EXPECT_FALSE(
  1992. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1993. EXPECT_TRUE(ranges.empty());
  1994. }
  1995. {
  1996. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1997. // remainder of the representation, so it stays accepted.
  1998. Ranges ranges;
  1999. auto ret =
  2000. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2001. EXPECT_TRUE(ret);
  2002. ASSERT_EQ(1u, ranges.size());
  2003. EXPECT_EQ(0, ranges[0].first);
  2004. EXPECT_EQ(-1, ranges[0].second);
  2005. }
  2006. // RFC 9110 14.1: range unit names are case-insensitive.
  2007. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2008. Ranges ranges;
  2009. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2010. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2011. }
  2012. }
  2013. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding", "gzip");
  2016. Response res;
  2017. res.set_header("Content-Type", "text/plain");
  2018. auto ret = detail::encoding_type(req, res);
  2019. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2020. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2021. #else
  2022. EXPECT_TRUE(ret == detail::EncodingType::None);
  2023. #endif
  2024. }
  2025. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2033. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2034. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2035. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2036. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2037. #else
  2038. EXPECT_TRUE(ret == detail::EncodingType::None);
  2039. #endif
  2040. }
  2041. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2042. Request req;
  2043. req.set_header("Accept-Encoding",
  2044. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2045. Response res;
  2046. res.set_header("Content-Type", "text/plain");
  2047. auto ret = detail::encoding_type(req, res);
  2048. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2050. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2052. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2053. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2054. #else
  2055. EXPECT_TRUE(ret == detail::EncodingType::None);
  2056. #endif
  2057. }
  2058. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2059. // All supported encodings rejected with q=0 should return None
  2060. Request req;
  2061. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2062. Response res;
  2063. res.set_header("Content-Type", "text/plain");
  2064. auto ret = detail::encoding_type(req, res);
  2065. EXPECT_TRUE(ret == detail::EncodingType::None);
  2066. }
  2067. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2068. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2069. Request req;
  2070. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2071. Response res;
  2072. res.set_header("Content-Type", "text/plain");
  2073. auto ret = detail::encoding_type(req, res);
  2074. EXPECT_TRUE(ret == detail::EncodingType::None);
  2075. }
  2076. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2077. Request req;
  2078. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2079. Response res;
  2080. res.set_header("Content-Type", "text/plain");
  2081. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2082. }
  2083. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2084. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2085. Request req;
  2086. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2087. Response res;
  2088. res.set_header("Content-Type", "text/plain");
  2089. auto ret = detail::encoding_type(req, res);
  2090. EXPECT_TRUE(ret == detail::EncodingType::None);
  2091. }
  2092. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2093. // RFC 7231: Accept-Encoding values are case-insensitive
  2094. Request req;
  2095. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2096. Response res;
  2097. res.set_header("Content-Type", "text/plain");
  2098. auto ret = detail::encoding_type(req, res);
  2099. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2100. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2101. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2102. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2103. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2104. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2105. #else
  2106. EXPECT_TRUE(ret == detail::EncodingType::None);
  2107. #endif
  2108. }
  2109. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2110. // q value should determine priority, not hardcoded order
  2111. Request req;
  2112. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2113. Response res;
  2114. res.set_header("Content-Type", "text/plain");
  2115. auto ret = detail::encoding_type(req, res);
  2116. // gzip has highest q=1.0, so it should be selected even though
  2117. // br and zstd are also supported
  2118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2120. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2121. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2122. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2123. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2124. #else
  2125. EXPECT_TRUE(ret == detail::EncodingType::None);
  2126. #endif
  2127. }
  2128. TEST(BufferStreamTest, read) {
  2129. detail::BufferStream strm1;
  2130. Stream &strm = strm1;
  2131. EXPECT_EQ(5, strm.write("hello"));
  2132. char buf[512];
  2133. EXPECT_EQ(2, strm.read(buf, 2));
  2134. EXPECT_EQ('h', buf[0]);
  2135. EXPECT_EQ('e', buf[1]);
  2136. EXPECT_EQ(2, strm.read(buf, 2));
  2137. EXPECT_EQ('l', buf[0]);
  2138. EXPECT_EQ('l', buf[1]);
  2139. EXPECT_EQ(1, strm.read(buf, 1));
  2140. EXPECT_EQ('o', buf[0]);
  2141. EXPECT_EQ(0, strm.read(buf, 1));
  2142. }
  2143. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2144. auto host = "www.httpwatch.com";
  2145. auto ip = hosted_at(host);
  2146. EXPECT_EQ("23.96.13.243", ip);
  2147. std::vector<std::string> addrs;
  2148. hosted_at(host, addrs);
  2149. EXPECT_EQ(1u, addrs.size());
  2150. }
  2151. #if 0 // It depends on each test environment...
  2152. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2153. auto host = "www.youtube.com";
  2154. std::vector<std::string> addrs;
  2155. hosted_at(host, addrs);
  2156. EXPECT_EQ(20u, addrs.size());
  2157. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2158. EXPECT_TRUE(it != addrs.end());
  2159. }
  2160. #endif
  2161. class ChunkedEncodingTest : public ::testing::Test {
  2162. protected:
  2163. ChunkedEncodingTest()
  2164. : cli_(HOST, PORT)
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. ,
  2167. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2168. #endif
  2169. {
  2170. cli_.set_connection_timeout(2);
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. cli_.enable_server_certificate_verification(false);
  2173. #endif
  2174. }
  2175. virtual void SetUp() {
  2176. read_file("./image.jpg", image_data_);
  2177. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2178. res.set_content("Hello World!", "text/plain");
  2179. });
  2180. svr_.Get(
  2181. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2182. res.set_chunked_content_provider(
  2183. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2184. size_t remaining = image_data_.size() - offset;
  2185. if (remaining == 0) {
  2186. sink.done();
  2187. } else {
  2188. constexpr size_t CHUNK_SIZE = 1024;
  2189. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2190. sink.write(&image_data_[offset], send_size);
  2191. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2192. }
  2193. return true;
  2194. });
  2195. });
  2196. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2197. svr_.wait_until_ready();
  2198. }
  2199. virtual void TearDown() {
  2200. svr_.stop();
  2201. if (!request_threads_.empty()) {
  2202. std::this_thread::sleep_for(std::chrono::seconds(1));
  2203. for (auto &t : request_threads_) {
  2204. t.join();
  2205. }
  2206. }
  2207. t_.join();
  2208. }
  2209. #ifdef CPPHTTPLIB_SSL_ENABLED
  2210. SSLClient cli_;
  2211. SSLServer svr_;
  2212. #else
  2213. Client cli_;
  2214. Server svr_;
  2215. #endif
  2216. thread t_;
  2217. std::vector<thread> request_threads_;
  2218. std::string image_data_;
  2219. };
  2220. TEST_F(ChunkedEncodingTest, NormalGet) {
  2221. auto res = cli_.Get("/chunked");
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. std::string out;
  2224. read_file("./image.jpg", out);
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(out, res->body);
  2227. }
  2228. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2229. std::string body;
  2230. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2231. body.append(data, data_length);
  2232. return true;
  2233. });
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get(
  2243. "/chunked",
  2244. [&](const Response &response) {
  2245. EXPECT_EQ(StatusCode::OK_200, response.status);
  2246. return true;
  2247. },
  2248. [&](const char *data, size_t data_length) {
  2249. body.append(data, data_length);
  2250. return true;
  2251. });
  2252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2253. std::string out;
  2254. read_file("./image.jpg", out);
  2255. EXPECT_EQ(StatusCode::OK_200, res->status);
  2256. EXPECT_EQ(out, body);
  2257. }
  2258. TEST(RangeTest, FromHTTPBin_Online) {
  2259. auto host = "httpbingo.org";
  2260. auto path = std::string{"/range/32"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(5);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. }
  2275. {
  2276. Headers headers = {make_range_header({{1, -1}})};
  2277. auto res = cli.Get(path, headers);
  2278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2279. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2281. }
  2282. {
  2283. Headers headers = {make_range_header({{1, 10}})};
  2284. auto res = cli.Get(path, headers);
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("bcdefghijk", res->body);
  2287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2288. }
  2289. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2290. // entire resource, while the original httpbin returned 200. Both are
  2291. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2292. {
  2293. Headers headers = {make_range_header({{0, 31}})};
  2294. auto res = cli.Get(path, headers);
  2295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2296. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2297. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2298. res->status == StatusCode::PartialContent_206);
  2299. }
  2300. {
  2301. Headers headers = {make_range_header({{0, -1}})};
  2302. auto res = cli.Get(path, headers);
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2305. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2306. res->status == StatusCode::PartialContent_206);
  2307. }
  2308. // go-httpbin returns 206 with clamped range for over-range requests,
  2309. // while the original httpbin returned 416. Both behaviors are observed
  2310. // in real servers, so we only verify the request succeeds.
  2311. {
  2312. Headers headers = {make_range_header({{0, 32}})};
  2313. auto res = cli.Get(path, headers);
  2314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2315. }
  2316. }
  2317. TEST(RangeTest, IgnoredForPost) {
  2318. Server svr;
  2319. svr.Post("/", [](const Request &, Response &res) {
  2320. res.set_content("abcdefg", "text/plain");
  2321. });
  2322. auto port = svr.bind_to_any_port(HOST);
  2323. ASSERT_GT(port, 0);
  2324. thread t = thread([&] { svr.listen_after_bind(); });
  2325. auto se = detail::scope_exit([&] {
  2326. svr.stop();
  2327. t.join();
  2328. ASSERT_FALSE(svr.is_running());
  2329. });
  2330. svr.wait_until_ready();
  2331. Client cli(HOST, port);
  2332. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2333. auto res = cli.Post("/", Headers{{"Range", range}});
  2334. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2335. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2336. EXPECT_EQ("abcdefg", res->body) << range;
  2337. }
  2338. }
  2339. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2340. auto host = "unresolvableaddress.local";
  2341. auto path = std::string{"/"};
  2342. #ifdef CPPHTTPLIB_SSL_ENABLED
  2343. auto port = 443;
  2344. SSLClient cli(host, port);
  2345. #else
  2346. auto port = 80;
  2347. Client cli(host, port);
  2348. #endif
  2349. cli.set_connection_timeout(1);
  2350. {
  2351. auto res = cli.Get(path);
  2352. ASSERT_FALSE(res);
  2353. }
  2354. std::this_thread::sleep_for(std::chrono::seconds(8));
  2355. }
  2356. #if defined(__linux__) && defined(__GLIBC__) && \
  2357. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2358. // Forward declaration: in split builds split.py strips `inline` and moves the
  2359. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2360. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2361. // against the symbol in both header-only and split builds.
  2362. namespace httplib {
  2363. namespace detail {
  2364. int getaddrinfo_with_timeout(const char *node, const char *service,
  2365. const struct addrinfo *hints,
  2366. struct addrinfo **res, time_t timeout_sec);
  2367. } // namespace detail
  2368. } // namespace httplib
  2369. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2370. //
  2371. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2372. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2373. // gai_suspend() call hits the connection timeout the function calls
  2374. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2375. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2376. // still alive and still references the now-destroyed stack frame.
  2377. //
  2378. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2379. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2380. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2381. // and runs them in a container.
  2382. namespace {
  2383. bool should_run_issue_2431_tests() {
  2384. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2385. return v && *v && std::string(v) != "0";
  2386. }
  2387. std::string unique_unresolvable_host(int n) {
  2388. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2389. // glibc still asks the configured nameserver — which is exactly the path
  2390. // we want to exercise. A unique label per call avoids the resolver cache.
  2391. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2392. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2393. std::to_string(n) + ".invalid";
  2394. }
  2395. } // namespace
  2396. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2397. if (!should_run_issue_2431_tests()) {
  2398. GTEST_SKIP()
  2399. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2400. }
  2401. for (int i = 0; i < 8; ++i) {
  2402. struct addrinfo hints;
  2403. memset(&hints, 0, sizeof(hints));
  2404. hints.ai_family = AF_UNSPEC;
  2405. hints.ai_socktype = SOCK_STREAM;
  2406. auto host = unique_unresolvable_host(i);
  2407. struct addrinfo *result = nullptr;
  2408. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2409. &result, /*timeout_sec=*/1);
  2410. if (rc == 0 && result) { freeaddrinfo(result); }
  2411. }
  2412. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2413. // stack region they still believe holds their gaicb.
  2414. std::this_thread::sleep_for(std::chrono::seconds(3));
  2415. }
  2416. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2417. if (!should_run_issue_2431_tests()) {
  2418. GTEST_SKIP()
  2419. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2420. }
  2421. std::atomic<bool> stop{false};
  2422. std::vector<std::thread> threads;
  2423. for (int t = 0; t < 8; ++t) {
  2424. threads.emplace_back([t, &stop] {
  2425. int i = 0;
  2426. while (!stop.load(std::memory_order_relaxed)) {
  2427. struct addrinfo hints;
  2428. memset(&hints, 0, sizeof(hints));
  2429. hints.ai_family = AF_UNSPEC;
  2430. hints.ai_socktype = SOCK_STREAM;
  2431. auto host = unique_unresolvable_host(t * 100000 + i++);
  2432. struct addrinfo *result = nullptr;
  2433. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2434. &result, /*timeout_sec=*/1);
  2435. if (rc == 0 && result) { freeaddrinfo(result); }
  2436. }
  2437. });
  2438. }
  2439. std::this_thread::sleep_for(std::chrono::seconds(8));
  2440. stop.store(true, std::memory_order_relaxed);
  2441. for (auto &th : threads) {
  2442. th.join();
  2443. }
  2444. std::this_thread::sleep_for(std::chrono::seconds(3));
  2445. }
  2446. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2447. if (!should_run_issue_2431_tests()) {
  2448. GTEST_SKIP()
  2449. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2450. }
  2451. std::atomic<bool> stop{false};
  2452. std::vector<std::thread> threads;
  2453. for (int t = 0; t < 8; ++t) {
  2454. threads.emplace_back([t, &stop] {
  2455. int i = 0;
  2456. while (!stop.load(std::memory_order_relaxed)) {
  2457. auto host = unique_unresolvable_host(t * 100000 + i++);
  2458. Client cli(host, 80);
  2459. cli.set_connection_timeout(1, 0);
  2460. cli.set_read_timeout(1, 0);
  2461. cli.set_write_timeout(1, 0);
  2462. (void)cli.Get("/");
  2463. }
  2464. });
  2465. }
  2466. std::this_thread::sleep_for(std::chrono::seconds(8));
  2467. stop.store(true, std::memory_order_relaxed);
  2468. for (auto &th : threads) {
  2469. th.join();
  2470. }
  2471. std::this_thread::sleep_for(std::chrono::seconds(3));
  2472. }
  2473. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2474. TEST(ConnectionErrorTest, InvalidHost) {
  2475. auto host = "-abcde.com";
  2476. #ifdef CPPHTTPLIB_SSL_ENABLED
  2477. auto port = 443;
  2478. SSLClient cli(host, port);
  2479. #else
  2480. auto port = 80;
  2481. Client cli(host, port);
  2482. #endif
  2483. cli.set_connection_timeout(std::chrono::seconds(2));
  2484. auto res = cli.Get("/");
  2485. ASSERT_TRUE(!res);
  2486. EXPECT_EQ(Error::Connection, res.error());
  2487. }
  2488. TEST(ConnectionErrorTest, InvalidHost2) {
  2489. auto host = "httpcan.org/";
  2490. #ifdef CPPHTTPLIB_SSL_ENABLED
  2491. SSLClient cli(host);
  2492. #else
  2493. Client cli(host);
  2494. #endif
  2495. cli.set_connection_timeout(std::chrono::seconds(2));
  2496. auto res = cli.Get("/");
  2497. ASSERT_TRUE(!res);
  2498. EXPECT_EQ(Error::Connection, res.error());
  2499. }
  2500. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2501. auto host = "httpcan.org/";
  2502. #ifdef CPPHTTPLIB_SSL_ENABLED
  2503. SSLClient cli(host);
  2504. #else
  2505. Client cli(host);
  2506. #endif
  2507. cli.set_connection_timeout(std::chrono::seconds(2));
  2508. auto res = cli.Get("/");
  2509. ASSERT_TRUE(!res);
  2510. stringstream s;
  2511. s << "error code: " << res.error();
  2512. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2513. }
  2514. TEST(ConnectionErrorTest, InvalidPort) {
  2515. auto host = "localhost";
  2516. auto port = 44380;
  2517. #ifdef CPPHTTPLIB_SSL_ENABLED
  2518. SSLClient cli(host, port);
  2519. #else
  2520. Client cli(host, port);
  2521. #endif
  2522. cli.set_connection_timeout(std::chrono::seconds(2));
  2523. auto res = cli.Get("/");
  2524. ASSERT_TRUE(!res);
  2525. EXPECT_TRUE(Error::Connection == res.error() ||
  2526. Error::ConnectionTimeout == res.error());
  2527. }
  2528. TEST(ConnectionErrorTest, Timeout_Online) {
  2529. auto host = "google.com";
  2530. #ifdef CPPHTTPLIB_SSL_ENABLED
  2531. auto port = 44380;
  2532. SSLClient cli(host, port);
  2533. #else
  2534. auto port = 8080;
  2535. Client cli(host, port);
  2536. #endif
  2537. cli.set_connection_timeout(std::chrono::seconds(2));
  2538. // only probe one address type so that the error reason
  2539. // correlates to the timed-out IPv4, not the unsupported
  2540. // IPv6 connection attempt
  2541. cli.set_address_family(AF_INET);
  2542. auto res = cli.Get("/");
  2543. ASSERT_TRUE(!res);
  2544. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2545. }
  2546. TEST(CancelTest, NoCancel_Online) {
  2547. auto host = "httpbingo.org";
  2548. auto path = std::string{"/range/32"};
  2549. #ifdef CPPHTTPLIB_SSL_ENABLED
  2550. auto port = 443;
  2551. SSLClient cli(host, port);
  2552. #else
  2553. auto port = 80;
  2554. Client cli(host, port);
  2555. #endif
  2556. cli.set_connection_timeout(std::chrono::seconds(5));
  2557. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2559. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2560. EXPECT_EQ(StatusCode::OK_200, res->status);
  2561. }
  2562. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2563. // Use /bytes with a large payload so that the DownloadProgress callback
  2564. // (which only fires for Content-Length responses) is invoked before the
  2565. // entire body is received, giving cancellation a chance to fire.
  2566. auto host = "httpbingo.org";
  2567. auto path = std::string{"/bytes/524288"};
  2568. #ifdef CPPHTTPLIB_SSL_ENABLED
  2569. auto port = 443;
  2570. SSLClient cli(host, port);
  2571. #else
  2572. auto port = 80;
  2573. Client cli(host, port);
  2574. #endif
  2575. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2576. cli.set_connection_timeout(std::chrono::seconds(5));
  2577. ASSERT_TRUE(!res);
  2578. EXPECT_EQ(Error::Canceled, res.error());
  2579. }
  2580. TEST(CancelTest, WithCancelLargePayload_Online) {
  2581. auto host = "httpbingo.org";
  2582. auto path = std::string{"/bytes/524288"};
  2583. #ifdef CPPHTTPLIB_SSL_ENABLED
  2584. auto port = 443;
  2585. SSLClient cli(host, port);
  2586. #else
  2587. auto port = 80;
  2588. Client cli(host, port);
  2589. #endif
  2590. cli.set_connection_timeout(std::chrono::seconds(5));
  2591. uint32_t count = 0;
  2592. auto res =
  2593. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2594. ASSERT_TRUE(!res);
  2595. EXPECT_EQ(Error::Canceled, res.error());
  2596. }
  2597. TEST(CancelTest, NoCancelPost) {
  2598. Server svr;
  2599. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2600. res.set_content("Hello World!", "text/plain");
  2601. });
  2602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2603. auto se = detail::scope_exit([&] {
  2604. svr.stop();
  2605. thread.join();
  2606. ASSERT_FALSE(svr.is_running());
  2607. });
  2608. svr.wait_until_ready();
  2609. Client cli(HOST, PORT);
  2610. cli.set_connection_timeout(std::chrono::seconds(5));
  2611. auto res =
  2612. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2613. "application/json", [](uint64_t, uint64_t) { return true; });
  2614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2615. EXPECT_EQ("Hello World!", res->body);
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. }
  2618. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2619. Server svr;
  2620. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2621. res.set_content("Hello World!", "text/plain");
  2622. });
  2623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli(HOST, PORT);
  2631. cli.set_connection_timeout(std::chrono::seconds(5));
  2632. auto res =
  2633. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2634. "application/json", [](uint64_t, uint64_t) { return false; });
  2635. ASSERT_TRUE(!res);
  2636. EXPECT_EQ(Error::Canceled, res.error());
  2637. }
  2638. TEST(CancelTest, WithCancelLargePayloadPost) {
  2639. Server svr;
  2640. svr.set_payload_max_length(200 * 1024 * 1024);
  2641. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2642. res.set_content(LARGE_DATA, "text/plain");
  2643. });
  2644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. Client cli(HOST, PORT);
  2652. cli.set_payload_max_length(200 * 1024 * 1024);
  2653. cli.set_connection_timeout(std::chrono::seconds(5));
  2654. auto res =
  2655. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2656. "application/json", [](uint64_t, uint64_t) { return false; });
  2657. ASSERT_TRUE(!res);
  2658. EXPECT_EQ(Error::Canceled, res.error());
  2659. }
  2660. TEST(CancelTest, NoCancelPut) {
  2661. Server svr;
  2662. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2663. res.set_content("Hello World!", "text/plain");
  2664. });
  2665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2666. auto se = detail::scope_exit([&] {
  2667. svr.stop();
  2668. thread.join();
  2669. ASSERT_FALSE(svr.is_running());
  2670. });
  2671. svr.wait_until_ready();
  2672. Client cli(HOST, PORT);
  2673. cli.set_connection_timeout(std::chrono::seconds(5));
  2674. auto res =
  2675. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2676. "application/json", [](uint64_t, uint64_t) { return true; });
  2677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2678. EXPECT_EQ("Hello World!", res->body);
  2679. EXPECT_EQ(StatusCode::OK_200, res->status);
  2680. }
  2681. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2682. Server svr;
  2683. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2684. res.set_content("Hello World!", "text/plain");
  2685. });
  2686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2687. auto se = detail::scope_exit([&] {
  2688. svr.stop();
  2689. thread.join();
  2690. ASSERT_FALSE(svr.is_running());
  2691. });
  2692. svr.wait_until_ready();
  2693. Client cli(HOST, PORT);
  2694. cli.set_connection_timeout(std::chrono::seconds(5));
  2695. auto res =
  2696. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2697. "application/json", [](uint64_t, uint64_t) { return false; });
  2698. ASSERT_TRUE(!res);
  2699. EXPECT_EQ(Error::Canceled, res.error());
  2700. }
  2701. TEST(CancelTest, WithCancelLargePayloadPut) {
  2702. Server svr;
  2703. svr.set_payload_max_length(200 * 1024 * 1024);
  2704. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2705. res.set_content(LARGE_DATA, "text/plain");
  2706. });
  2707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2708. auto se = detail::scope_exit([&] {
  2709. svr.stop();
  2710. thread.join();
  2711. ASSERT_FALSE(svr.is_running());
  2712. });
  2713. svr.wait_until_ready();
  2714. Client cli(HOST, PORT);
  2715. cli.set_payload_max_length(200 * 1024 * 1024);
  2716. cli.set_connection_timeout(std::chrono::seconds(5));
  2717. auto res =
  2718. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2719. "application/json", [](uint64_t, uint64_t) { return false; });
  2720. ASSERT_TRUE(!res);
  2721. EXPECT_EQ(Error::Canceled, res.error());
  2722. }
  2723. TEST(CancelTest, NoCancelPatch) {
  2724. Server svr;
  2725. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2726. res.set_content("Hello World!", "text/plain");
  2727. });
  2728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2729. auto se = detail::scope_exit([&] {
  2730. svr.stop();
  2731. thread.join();
  2732. ASSERT_FALSE(svr.is_running());
  2733. });
  2734. svr.wait_until_ready();
  2735. Client cli(HOST, PORT);
  2736. cli.set_connection_timeout(std::chrono::seconds(5));
  2737. auto res =
  2738. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2739. "application/json", [](uint64_t, uint64_t) { return true; });
  2740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2741. EXPECT_EQ("Hello World!", res->body);
  2742. EXPECT_EQ(StatusCode::OK_200, res->status);
  2743. }
  2744. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2745. Server svr;
  2746. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2747. res.set_content("Hello World!", "text/plain");
  2748. });
  2749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2750. auto se = detail::scope_exit([&] {
  2751. svr.stop();
  2752. thread.join();
  2753. ASSERT_FALSE(svr.is_running());
  2754. });
  2755. svr.wait_until_ready();
  2756. Client cli(HOST, PORT);
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. auto res =
  2759. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2760. "application/json", [](uint64_t, uint64_t) { return false; });
  2761. ASSERT_TRUE(!res);
  2762. EXPECT_EQ(Error::Canceled, res.error());
  2763. }
  2764. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2765. Server svr;
  2766. svr.set_payload_max_length(200 * 1024 * 1024);
  2767. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2768. res.set_content(LARGE_DATA, "text/plain");
  2769. });
  2770. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2771. auto se = detail::scope_exit([&] {
  2772. svr.stop();
  2773. thread.join();
  2774. ASSERT_FALSE(svr.is_running());
  2775. });
  2776. svr.wait_until_ready();
  2777. Client cli(HOST, PORT);
  2778. cli.set_payload_max_length(200 * 1024 * 1024);
  2779. cli.set_connection_timeout(std::chrono::seconds(5));
  2780. auto res =
  2781. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2782. "application/json", [](uint64_t, uint64_t) { return false; });
  2783. ASSERT_TRUE(!res);
  2784. EXPECT_EQ(Error::Canceled, res.error());
  2785. }
  2786. TEST(CancelTest, NoCancelDelete) {
  2787. Server svr;
  2788. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2789. res.set_content("Hello World!", "text/plain");
  2790. });
  2791. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2792. auto se = detail::scope_exit([&] {
  2793. svr.stop();
  2794. thread.join();
  2795. ASSERT_FALSE(svr.is_running());
  2796. });
  2797. svr.wait_until_ready();
  2798. Client cli(HOST, PORT);
  2799. cli.set_connection_timeout(std::chrono::seconds(5));
  2800. auto res =
  2801. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2802. "application/json", [](uint64_t, uint64_t) { return true; });
  2803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2804. EXPECT_EQ("Hello World!", res->body);
  2805. EXPECT_EQ(StatusCode::OK_200, res->status);
  2806. }
  2807. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2808. Server svr;
  2809. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2810. res.set_content("Hello World!", "text/plain");
  2811. });
  2812. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2813. auto se = detail::scope_exit([&] {
  2814. svr.stop();
  2815. thread.join();
  2816. ASSERT_FALSE(svr.is_running());
  2817. });
  2818. svr.wait_until_ready();
  2819. Client cli(HOST, PORT);
  2820. cli.set_connection_timeout(std::chrono::seconds(5));
  2821. auto res =
  2822. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2823. "application/json", [](uint64_t, uint64_t) { return false; });
  2824. ASSERT_TRUE(!res);
  2825. EXPECT_EQ(Error::Canceled, res.error());
  2826. }
  2827. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2828. Server svr;
  2829. svr.set_payload_max_length(200 * 1024 * 1024);
  2830. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2831. res.set_content(LARGE_DATA, "text/plain");
  2832. });
  2833. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2834. auto se = detail::scope_exit([&] {
  2835. svr.stop();
  2836. thread.join();
  2837. ASSERT_FALSE(svr.is_running());
  2838. });
  2839. svr.wait_until_ready();
  2840. Client cli(HOST, PORT);
  2841. cli.set_payload_max_length(200 * 1024 * 1024);
  2842. cli.set_connection_timeout(std::chrono::seconds(5));
  2843. auto res =
  2844. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2845. "application/json", [](uint64_t, uint64_t) { return false; });
  2846. ASSERT_TRUE(!res);
  2847. EXPECT_EQ(Error::Canceled, res.error());
  2848. }
  2849. static std::string remove_whitespace(const std::string &input) {
  2850. std::string output;
  2851. output.reserve(input.size());
  2852. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2853. [](unsigned char c) { return !std::isspace(c); });
  2854. return output;
  2855. }
  2856. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2857. auto host = "httpbingo.org";
  2858. auto path = std::string{"/basic-auth/hello/world"};
  2859. #ifdef CPPHTTPLIB_SSL_ENABLED
  2860. auto port = 443;
  2861. SSLClient cli(host, port);
  2862. #else
  2863. auto port = 80;
  2864. Client cli(host, port);
  2865. #endif
  2866. {
  2867. auto res = cli.Get(path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2870. }
  2871. {
  2872. auto res = cli.Get(
  2873. path, Headers{make_basic_authentication_header("hello", "world")});
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. auto body = remove_whitespace(res->body);
  2876. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2877. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. {
  2881. cli.set_basic_auth("hello", "world");
  2882. auto res = cli.Get(path);
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. auto body = remove_whitespace(res->body);
  2885. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2886. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2887. EXPECT_EQ(StatusCode::OK_200, res->status);
  2888. }
  2889. {
  2890. cli.set_basic_auth("hello", "bad");
  2891. auto res = cli.Get(path);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2894. }
  2895. {
  2896. cli.set_basic_auth("bad", "world");
  2897. auto res = cli.Get(path);
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2900. }
  2901. }
  2902. #ifdef CPPHTTPLIB_SSL_ENABLED
  2903. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2904. auto host = "httpbingo.org";
  2905. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2906. auto paths = std::vector<std::string>{
  2907. "/digest-auth/auth/hello/world/MD5",
  2908. "/digest-auth/auth/hello/world/SHA-256",
  2909. };
  2910. auto port = 443;
  2911. SSLClient cli(host, port);
  2912. {
  2913. auto res = cli.Get(unauth_path);
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2916. }
  2917. {
  2918. cli.set_digest_auth("hello", "world");
  2919. for (const auto &path : paths) {
  2920. auto res = cli.Get(path.c_str());
  2921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2922. auto body = remove_whitespace(res->body);
  2923. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2924. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2925. EXPECT_EQ(StatusCode::OK_200, res->status);
  2926. }
  2927. cli.set_digest_auth("hello", "bad");
  2928. for (const auto &path : paths) {
  2929. auto res = cli.Get(path.c_str());
  2930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2931. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2932. }
  2933. }
  2934. }
  2935. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2936. // comma-separated list of challenges, and each challenge may itself carry a
  2937. // comma-separated auth-param list, so a server can legally offer Basic
  2938. // before Digest, either as two field lines or packed into one. Runs one 401
  2939. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2940. // value() joins them in receipt order) and checks that the retry carries a
  2941. // well-formed Digest Authorization header naming expected_realm.
  2942. static void
  2943. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2944. const std::string &expected_realm) {
  2945. std::atomic<int> hits{0};
  2946. Server svr;
  2947. svr.Get("/x", [&](const Request &req, Response &res) {
  2948. if (++hits == 1) {
  2949. res.status = StatusCode::Unauthorized_401;
  2950. for (const auto &challenge : challenges) {
  2951. res.set_header("WWW-Authenticate", challenge);
  2952. }
  2953. } else {
  2954. auto authorization = req.get_header_value("Authorization");
  2955. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2956. EXPECT_NE(std::string::npos,
  2957. authorization.find("realm=\"" + expected_realm + "\""));
  2958. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2959. res.set_content("ok", "text/plain");
  2960. }
  2961. });
  2962. auto port = svr.bind_to_any_port(HOST);
  2963. std::thread t([&]() { svr.listen_after_bind(); });
  2964. auto se = detail::scope_exit([&] {
  2965. svr.stop();
  2966. t.join();
  2967. });
  2968. svr.wait_until_ready();
  2969. Client cli(HOST, port);
  2970. cli.set_digest_auth("hello", "world");
  2971. auto res = cli.Get("/x");
  2972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2973. EXPECT_EQ(2, hits.load());
  2974. }
  2975. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2976. static const char *kDigestChallenge =
  2977. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2978. "algorithm=MD5";
  2979. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2980. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2981. "testrealm");
  2982. }
  2983. // Same challenge list with the schemes in the opposite order, to make sure
  2984. // the fix above didn't just special-case "Basic first".
  2985. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2986. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2987. "testrealm");
  2988. }
  2989. // A comma inside a quoted auth-param value must not be mistaken for the
  2990. // separator between two challenges (or two auth-params).
  2991. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2992. run_digest_challenge_list_test(
  2993. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2994. "algorithm=MD5"},
  2995. "test,realm");
  2996. }
  2997. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2998. // the params and leaves out the fragment.
  2999. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3000. Server svr;
  3001. std::string uri, target;
  3002. svr.Get("/a b", [&](const Request &req, Response &res) {
  3003. auto auth = req.get_header_value("Authorization");
  3004. if (auth.empty()) {
  3005. res.status = StatusCode::Unauthorized_401;
  3006. res.set_header("WWW-Authenticate",
  3007. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3008. return;
  3009. }
  3010. auto b = auth.find("uri=\"") + 5;
  3011. uri = auth.substr(b, auth.find('"', b) - b);
  3012. target = req.target;
  3013. });
  3014. auto port = svr.bind_to_any_port(HOST);
  3015. std::thread t([&]() { svr.listen_after_bind(); });
  3016. auto se = detail::scope_exit([&] {
  3017. svr.stop();
  3018. t.join();
  3019. });
  3020. svr.wait_until_ready();
  3021. Client cli(HOST, port);
  3022. cli.set_digest_auth("hello", "world");
  3023. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3025. EXPECT_EQ("/a%20b?x=1", target);
  3026. EXPECT_EQ(target, uri);
  3027. }
  3028. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3029. // make_digest_authentication_header() dereferences both unconditionally, so
  3030. // a server sending a challenge missing either one must not be treated as
  3031. // usable -- doing so used to crash the client with std::out_of_range.
  3032. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3033. Server svr;
  3034. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3035. res.status = StatusCode::Unauthorized_401;
  3036. res.set_header("WWW-Authenticate", challenge);
  3037. });
  3038. auto port = svr.bind_to_any_port(HOST);
  3039. std::thread t([&]() { svr.listen_after_bind(); });
  3040. auto se = detail::scope_exit([&] {
  3041. svr.stop();
  3042. t.join();
  3043. });
  3044. svr.wait_until_ready();
  3045. Client cli(HOST, port);
  3046. cli.set_digest_auth("hello", "world");
  3047. auto res = cli.Get("/x");
  3048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3049. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3050. }
  3051. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3052. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3053. }
  3054. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3055. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3056. }
  3057. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3058. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3059. }
  3060. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3061. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3062. // when storing the values, so the header builder has to re-escape them (and
  3063. // keep algorithm a bare token); otherwise the value breaks out of its
  3064. // quoted-string and injects extra auth-params into the client's Authorization.
  3065. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3066. std::atomic<int> hits{0};
  3067. std::string authorization;
  3068. Server svr;
  3069. svr.Get("/x", [&](const Request &req, Response &res) {
  3070. if (++hits == 1) {
  3071. res.status = StatusCode::Unauthorized_401;
  3072. // On the wire the quotes embedded in the values are backslash-escaped.
  3073. res.set_header("WWW-Authenticate",
  3074. "Digest realm=\"testrealm\", "
  3075. "nonce=\"n\\\"; injected=\\\"x\", "
  3076. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3077. } else {
  3078. authorization = req.get_header_value("Authorization");
  3079. res.set_content("ok", "text/plain");
  3080. }
  3081. });
  3082. auto port = svr.bind_to_any_port(HOST);
  3083. std::thread t([&]() { svr.listen_after_bind(); });
  3084. auto se = detail::scope_exit([&] {
  3085. svr.stop();
  3086. t.join();
  3087. });
  3088. svr.wait_until_ready();
  3089. Client cli(HOST, port);
  3090. cli.set_digest_auth("hello", "world");
  3091. auto res = cli.Get("/x");
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. EXPECT_EQ(2, hits.load());
  3094. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3095. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3096. // inside its quoted-string rather than starting an "injected" auth-param.
  3097. EXPECT_NE(std::string::npos,
  3098. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3099. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3100. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3101. }
  3102. #endif
  3103. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3104. auto host = "google.com";
  3105. auto another_host = "example.com";
  3106. auto wrong_ip = "0.0.0.0";
  3107. #ifdef CPPHTTPLIB_SSL_ENABLED
  3108. SSLClient cli(host);
  3109. #else
  3110. Client cli(host);
  3111. #endif
  3112. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3113. auto res = cli.Get("/");
  3114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3115. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3116. }
  3117. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3118. auto host = "google.com";
  3119. auto wrong_ip = "0.0.0.0";
  3120. #ifdef CPPHTTPLIB_SSL_ENABLED
  3121. SSLClient cli(host);
  3122. #else
  3123. Client cli(host);
  3124. #endif
  3125. cli.set_hostname_addr_map({{host, wrong_ip}});
  3126. auto res = cli.Get("/");
  3127. ASSERT_TRUE(!res);
  3128. EXPECT_EQ(Error::Connection, res.error());
  3129. }
  3130. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3131. // A mapped value that is not an IP literal must be resolved. "localhost"
  3132. // resolves from the hosts file, so this test needs no external DNS.
  3133. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3134. auto host = "target.invalid";
  3135. Server svr;
  3136. std::string received_host;
  3137. svr.Get("/hi", [&](const Request &req, Response &res) {
  3138. received_host = req.get_header_value("Host");
  3139. res.set_content("Hello World!", "text/plain");
  3140. });
  3141. auto port = svr.bind_to_any_port(HOST);
  3142. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3143. auto se = detail::scope_exit([&] {
  3144. svr.stop();
  3145. thread.join();
  3146. ASSERT_FALSE(svr.is_running());
  3147. });
  3148. svr.wait_until_ready();
  3149. Client cli(host, port);
  3150. cli.set_hostname_addr_map({{host, HOST}});
  3151. auto res = cli.Get("/hi");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. // The mapping only redirects the connection; the identity stays host_.
  3155. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3156. }
  3157. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3158. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3159. auto host = "target.invalid";
  3160. Server svr;
  3161. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3162. res.set_content("Hello World!", "text/plain");
  3163. });
  3164. auto port = svr.bind_to_any_port("127.0.0.1");
  3165. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3166. auto se = detail::scope_exit([&] {
  3167. svr.stop();
  3168. thread.join();
  3169. ASSERT_FALSE(svr.is_running());
  3170. });
  3171. svr.wait_until_ready();
  3172. Client cli(host, port);
  3173. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3174. auto res = cli.Get("/hi");
  3175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3176. EXPECT_EQ(StatusCode::OK_200, res->status);
  3177. }
  3178. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3179. // An empty mapped value must leave host_ as the connection target. Without
  3180. // that guard the empty value would become the host argument, getaddrinfo
  3181. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3182. // loopback - silently connecting somewhere the caller never asked for.
  3183. // The server listens on loopback, so such a fallback would succeed and is
  3184. // therefore observable as a failure of this test.
  3185. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3186. Server svr;
  3187. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3188. res.set_content("Hello World!", "text/plain");
  3189. });
  3190. auto port = svr.bind_to_any_port(HOST);
  3191. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3192. auto se = detail::scope_exit([&] {
  3193. svr.stop();
  3194. thread.join();
  3195. ASSERT_FALSE(svr.is_running());
  3196. });
  3197. svr.wait_until_ready();
  3198. Client cli(blackhole, port);
  3199. cli.set_hostname_addr_map({{blackhole, ""}});
  3200. cli.set_connection_timeout(1);
  3201. auto res = cli.Get("/hi");
  3202. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3203. }
  3204. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3205. auto host = "httpbingo.org";
  3206. auto path = std::string{"/absolute-redirect/3"};
  3207. #ifdef CPPHTTPLIB_SSL_ENABLED
  3208. SSLClient cli(host);
  3209. #else
  3210. Client cli(host);
  3211. #endif
  3212. cli.set_follow_location(true);
  3213. auto res = cli.Get(path);
  3214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3215. EXPECT_EQ(StatusCode::OK_200, res->status);
  3216. }
  3217. TEST(RedirectTest, Redirect_Online) {
  3218. auto host = "httpbingo.org";
  3219. auto path = std::string{"/redirect/3"};
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(host);
  3222. #else
  3223. Client cli(host);
  3224. #endif
  3225. cli.set_follow_location(true);
  3226. auto res = cli.Get(path);
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. }
  3230. TEST(RelativeRedirectTest, Redirect_Online) {
  3231. auto host = "httpbingo.org";
  3232. auto path = std::string{"/relative-redirect/3"};
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. SSLClient cli(host);
  3235. #else
  3236. Client cli(host);
  3237. #endif
  3238. cli.set_follow_location(true);
  3239. auto res = cli.Get(path);
  3240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3241. EXPECT_EQ(StatusCode::OK_200, res->status);
  3242. }
  3243. TEST(TooManyRedirectTest, Redirect_Online) {
  3244. auto host = "httpbingo.org";
  3245. auto path = std::string{"/redirect/21"};
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. SSLClient cli(host);
  3248. #else
  3249. Client cli(host);
  3250. #endif
  3251. cli.set_follow_location(true);
  3252. auto res = cli.Get(path);
  3253. ASSERT_TRUE(!res);
  3254. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3255. }
  3256. #ifdef CPPHTTPLIB_SSL_ENABLED
  3257. TEST(YahooRedirectTest, Redirect_Online) {
  3258. Client cli("yahoo.com");
  3259. auto res = cli.Get("/");
  3260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3261. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3262. cli.set_follow_location(true);
  3263. res = cli.Get("/");
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3267. }
  3268. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3269. #define REDIR_HOST "httpbingo.org"
  3270. #define REDIR_PATH "/redirect-to"
  3271. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3272. SSLClient cli(REDIR_HOST);
  3273. cli.set_follow_location(true);
  3274. auto res =
  3275. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. }
  3279. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3280. SSLClient cli(REDIR_HOST);
  3281. cli.set_follow_location(true);
  3282. Params params;
  3283. params.emplace("url", "http://example.com");
  3284. params.emplace("status_code", "302");
  3285. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. }
  3289. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3290. SSLClient cli(REDIR_HOST);
  3291. cli.set_follow_location(true);
  3292. Params params;
  3293. params.emplace("url", "http://example.com");
  3294. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. }
  3298. TEST(UrlWithSpace, Redirect_Online) {
  3299. SSLClient cli("edge.forgecdn.net");
  3300. cli.set_follow_location(true);
  3301. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3303. EXPECT_EQ(StatusCode::OK_200, res->status);
  3304. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3305. }
  3306. #endif
  3307. #if !defined(_WIN32) && !defined(_WIN64)
  3308. TEST(ReceiveSignals, Signal) {
  3309. auto setupSignalHandlers = []() {
  3310. struct sigaction act;
  3311. sigemptyset(&act.sa_mask);
  3312. act.sa_flags = SA_SIGINFO;
  3313. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3314. switch (sig) {
  3315. case SIGINT:
  3316. default: break;
  3317. }
  3318. };
  3319. ::sigaction(SIGINT, &act, nullptr);
  3320. };
  3321. Server svr;
  3322. int port = 0;
  3323. auto thread = std::thread([&]() {
  3324. setupSignalHandlers();
  3325. port = svr.bind_to_any_port(HOST);
  3326. svr.listen_after_bind();
  3327. });
  3328. auto se = detail::scope_exit([&] {
  3329. svr.stop();
  3330. thread.join();
  3331. ASSERT_FALSE(svr.is_running());
  3332. });
  3333. svr.wait_until_ready();
  3334. ASSERT_TRUE(svr.is_running());
  3335. pthread_kill(thread.native_handle(), SIGINT);
  3336. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3337. ASSERT_TRUE(svr.is_running());
  3338. }
  3339. #endif
  3340. TEST(RedirectToDifferentPort, Redirect) {
  3341. Server svr1;
  3342. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3343. res.set_content("Hello World!", "text/plain");
  3344. });
  3345. int svr1_port = 0;
  3346. auto thread1 = std::thread([&]() {
  3347. svr1_port = svr1.bind_to_any_port(HOST);
  3348. svr1.listen_after_bind();
  3349. });
  3350. Server svr2;
  3351. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3352. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3353. });
  3354. int svr2_port = 0;
  3355. auto thread2 = std::thread([&]() {
  3356. svr2_port = svr2.bind_to_any_port(HOST);
  3357. svr2.listen_after_bind();
  3358. });
  3359. auto se = detail::scope_exit([&] {
  3360. svr2.stop();
  3361. thread2.join();
  3362. svr1.stop();
  3363. thread1.join();
  3364. ASSERT_FALSE(svr2.is_running());
  3365. ASSERT_FALSE(svr1.is_running());
  3366. });
  3367. svr1.wait_until_ready();
  3368. svr2.wait_until_ready();
  3369. Client cli("localhost", svr2_port);
  3370. cli.set_follow_location(true);
  3371. auto res = cli.Get("/2");
  3372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3373. EXPECT_EQ(StatusCode::OK_200, res->status);
  3374. EXPECT_EQ("Hello World!", res->body);
  3375. }
  3376. // GET /redir on one server redirects to /target on another port, so the
  3377. // client follows it with a new client.
  3378. static Result
  3379. GetThroughRedirectToDifferentPort(Server::Handler target,
  3380. const std::function<void(Client &)> &setup,
  3381. const Headers &headers = Headers()) {
  3382. Server target_svr;
  3383. target_svr.Get("/target", target);
  3384. int target_port = 0;
  3385. auto target_thread = std::thread([&]() {
  3386. target_port = target_svr.bind_to_any_port(HOST);
  3387. target_svr.listen_after_bind();
  3388. });
  3389. Server origin_svr;
  3390. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3391. res.set_redirect(
  3392. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3393. });
  3394. int origin_port = 0;
  3395. auto origin_thread = std::thread([&]() {
  3396. origin_port = origin_svr.bind_to_any_port(HOST);
  3397. origin_svr.listen_after_bind();
  3398. });
  3399. auto se = detail::scope_exit([&] {
  3400. origin_svr.stop();
  3401. origin_thread.join();
  3402. target_svr.stop();
  3403. target_thread.join();
  3404. });
  3405. target_svr.wait_until_ready();
  3406. origin_svr.wait_until_ready();
  3407. Client cli("localhost", origin_port);
  3408. cli.set_follow_location(true);
  3409. setup(cli);
  3410. return cli.Get("/redir", headers);
  3411. }
  3412. static void
  3413. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3414. std::string captured_authorization;
  3415. auto result = GetThroughRedirectToDifferentPort(
  3416. [&](const Request &req, Response &res) {
  3417. captured_authorization = req.get_header_value("Authorization");
  3418. res.set_content("OK", "text/plain");
  3419. },
  3420. set_auth);
  3421. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3422. EXPECT_EQ(StatusCode::OK_200, result->status);
  3423. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3424. EXPECT_TRUE(captured_authorization.empty());
  3425. }
  3426. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3427. TestDoNotForwardCredentialsOnRedirect(
  3428. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3429. }
  3430. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3431. TestDoNotForwardCredentialsOnRedirect(
  3432. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3433. }
  3434. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3435. std::string captured_cookie;
  3436. auto result = GetThroughRedirectToDifferentPort(
  3437. [&](const Request &req, Response &res) {
  3438. captured_cookie = req.get_header_value("Cookie");
  3439. res.set_content("OK", "text/plain");
  3440. },
  3441. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3442. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3443. EXPECT_EQ(StatusCode::OK_200, result->status);
  3444. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3445. EXPECT_TRUE(captured_cookie.empty());
  3446. }
  3447. TEST(RedirectToSamePort, ForwardCookie) {
  3448. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3449. // header so that ordinary session flows keep working.
  3450. Server svr;
  3451. std::string captured_cookie;
  3452. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3453. res.set_redirect("/target", 302);
  3454. });
  3455. svr.Get("/target", [&](const Request &req, Response &res) {
  3456. captured_cookie = req.get_header_value("Cookie");
  3457. res.set_content("OK", "text/plain");
  3458. });
  3459. auto port = svr.bind_to_any_port(HOST);
  3460. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3461. auto se = detail::scope_exit([&] {
  3462. svr.stop();
  3463. thread.join();
  3464. ASSERT_FALSE(svr.is_running());
  3465. });
  3466. svr.wait_until_ready();
  3467. Client cli(HOST, port);
  3468. cli.set_follow_location(true);
  3469. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3470. auto res = cli.Get("/redir", headers);
  3471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3472. EXPECT_EQ(StatusCode::OK_200, res->status);
  3473. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3474. }
  3475. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3476. std::string authorization;
  3477. std::string trace_id;
  3478. auto result = GetThroughRedirectToDifferentPort(
  3479. [&](const Request &req, Response &res) {
  3480. authorization = req.get_header_value("Authorization");
  3481. trace_id = req.get_header_value("X-Trace-Id");
  3482. res.set_content("OK", "text/plain");
  3483. },
  3484. [](Client &cli) {
  3485. cli.set_default_headers(
  3486. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3487. });
  3488. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3489. EXPECT_EQ(StatusCode::OK_200, result->status);
  3490. // Like a header given with the request, a default one goes along unless it
  3491. // carries credentials (RFC 9110 15.4).
  3492. EXPECT_TRUE(authorization.empty());
  3493. EXPECT_EQ("42", trace_id);
  3494. }
  3495. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3496. auto result = GetThroughRedirectToDifferentPort(
  3497. [](const Request &, Response &res) {
  3498. res.set_content(std::string(2048, 'x'), "text/plain");
  3499. },
  3500. [](Client &cli) { cli.set_payload_max_length(1024); });
  3501. EXPECT_FALSE(result);
  3502. }
  3503. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3504. auto result = GetThroughRedirectToDifferentPort(
  3505. [](const Request &req, Response &res) {
  3506. // Answer after a second, or once the client gives up.
  3507. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3508. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3509. }
  3510. res.set_content("late", "text/plain");
  3511. },
  3512. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3513. ASSERT_FALSE(result);
  3514. EXPECT_EQ(Error::Read, result.error());
  3515. }
  3516. #ifdef CPPHTTPLIB_SSL_ENABLED
  3517. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3518. auto result = GetThroughRedirectToDifferentPort(
  3519. [](const Request &, Response &res) {
  3520. res.status = StatusCode::Unauthorized_401;
  3521. res.set_header("WWW-Authenticate",
  3522. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3523. },
  3524. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3525. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3526. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3527. }
  3528. #endif
  3529. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3530. Server svr;
  3531. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3532. // Port number that overflows int — should not crash
  3533. res.set_redirect("http://localhost:99999999999999999999/target");
  3534. });
  3535. auto port = svr.bind_to_any_port(HOST);
  3536. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3537. auto se = detail::scope_exit([&] {
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. });
  3542. svr.wait_until_ready();
  3543. Client cli(HOST, port);
  3544. cli.set_follow_location(true);
  3545. auto res = cli.Get("/redir");
  3546. // Should fail gracefully, not crash (no valid response due to bad port)
  3547. EXPECT_FALSE(res);
  3548. }
  3549. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3550. Server svr;
  3551. auto port = svr.bind_to_any_port(HOST);
  3552. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3553. // The server's own port followed by junk must not be followed
  3554. res.set_redirect("http://" + std::string(HOST) + ":" +
  3555. std::to_string(port) + "junk/target");
  3556. });
  3557. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3558. res.set_content("target", "text/plain");
  3559. });
  3560. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3561. auto se = detail::scope_exit([&] {
  3562. svr.stop();
  3563. thread.join();
  3564. ASSERT_FALSE(svr.is_running());
  3565. });
  3566. svr.wait_until_ready();
  3567. Client cli(HOST, port);
  3568. cli.set_follow_location(true);
  3569. auto res = cli.Get("/redir");
  3570. EXPECT_FALSE(res);
  3571. }
  3572. TEST(RedirectFromPageWithContent, Redirect) {
  3573. Server svr;
  3574. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3575. res.set_content("___", "text/plain");
  3576. res.set_redirect("/2");
  3577. });
  3578. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3579. res.set_content("Hello World!", "text/plain");
  3580. });
  3581. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3582. auto se = detail::scope_exit([&] {
  3583. svr.stop();
  3584. th.join();
  3585. ASSERT_FALSE(svr.is_running());
  3586. });
  3587. svr.wait_until_ready();
  3588. {
  3589. Client cli("localhost", PORT);
  3590. cli.set_follow_location(true);
  3591. std::string body;
  3592. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3593. body.append(data, data_length);
  3594. return true;
  3595. });
  3596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3597. EXPECT_EQ(StatusCode::OK_200, res->status);
  3598. EXPECT_EQ("Hello World!", body);
  3599. }
  3600. {
  3601. Client cli("localhost", PORT);
  3602. std::string body;
  3603. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3604. body.append(data, data_length);
  3605. return true;
  3606. });
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ(StatusCode::Found_302, res->status);
  3609. EXPECT_EQ("___", body);
  3610. }
  3611. }
  3612. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3613. Server svr;
  3614. auto port_str = std::to_string(PORT);
  3615. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3616. auto expected_host = "[::1]:" + port_str;
  3617. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3618. res.set_content("___", "text/plain");
  3619. // res.set_redirect("/2");
  3620. res.set_redirect(redirect_url);
  3621. });
  3622. svr.Get("/2", [&](const Request &req, Response &res) {
  3623. auto host_header = req.headers.find("Host");
  3624. ASSERT_TRUE(host_header != req.headers.end());
  3625. EXPECT_EQ(expected_host, host_header->second);
  3626. res.set_content("Hello World!", "text/plain");
  3627. });
  3628. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3629. auto se = detail::scope_exit([&] {
  3630. svr.stop();
  3631. th.join();
  3632. ASSERT_FALSE(svr.is_running());
  3633. });
  3634. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3635. // actually starts anything, so the condition !svr.is_running() will
  3636. // always remain true, and the loop never stops.
  3637. // This basically counts how many milliseconds have passed since the
  3638. // call to svr.listen(), and if after 5 seconds nothing started yet
  3639. // aborts the test.
  3640. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3641. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3642. ASSERT_LT(milliseconds, 5000U);
  3643. }
  3644. {
  3645. Client cli("::1", PORT);
  3646. cli.set_follow_location(true);
  3647. std::string body;
  3648. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3649. body.append(data, data_length);
  3650. return true;
  3651. });
  3652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3653. EXPECT_EQ(StatusCode::OK_200, res->status);
  3654. EXPECT_EQ("Hello World!", body);
  3655. }
  3656. {
  3657. Client cli("::1", PORT);
  3658. std::string body;
  3659. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3660. body.append(data, data_length);
  3661. return true;
  3662. });
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::Found_302, res->status);
  3665. EXPECT_EQ("___", body);
  3666. }
  3667. }
  3668. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3669. Server svr;
  3670. svr.Get("/foo", [](const Request &req, Response &res) {
  3671. auto a = req.params.find("a");
  3672. if (a != req.params.end()) {
  3673. res.set_content((*a).second, "text/plain");
  3674. res.status = StatusCode::OK_200;
  3675. } else {
  3676. res.status = StatusCode::BadRequest_400;
  3677. }
  3678. });
  3679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3680. auto se = detail::scope_exit([&] {
  3681. svr.stop();
  3682. thread.join();
  3683. ASSERT_FALSE(svr.is_running());
  3684. });
  3685. svr.wait_until_ready();
  3686. {
  3687. Client cli(HOST, PORT);
  3688. cli.set_path_encode(false);
  3689. auto res = cli.Get("/foo?a=explicitly+encoded");
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. // This expects it back with a space, as the `+` won't have been
  3693. // url-encoded, and server-side the params get decoded turning `+`
  3694. // into spaces.
  3695. EXPECT_EQ("explicitly encoded", res->body);
  3696. }
  3697. }
  3698. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3699. // When path encoding is disabled the client must transmit the supplied
  3700. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3701. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3702. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3703. // than a space (0x20). Assert on the raw wire target to catch this.
  3704. Server svr;
  3705. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3706. svr.Get("/foo", [&](const Request &req, Response &res) {
  3707. EXPECT_EQ(expected_target, req.target);
  3708. res.status = StatusCode::OK_200;
  3709. });
  3710. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3711. auto se = detail::scope_exit([&] {
  3712. svr.stop();
  3713. thread.join();
  3714. ASSERT_FALSE(svr.is_running());
  3715. });
  3716. svr.wait_until_ready();
  3717. {
  3718. Client cli(HOST, PORT);
  3719. cli.set_path_encode(false);
  3720. auto res = cli.Get(expected_target.c_str());
  3721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3722. EXPECT_EQ(StatusCode::OK_200, res->status);
  3723. }
  3724. }
  3725. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3726. // `open_stream()` used to skip the path encoding that the buffered send
  3727. // path applies, so the same `path` produced different bytes in the request
  3728. // line depending on which API was used. Assert the two agree.
  3729. Server svr;
  3730. std::string target;
  3731. svr.Get(".*", [&](const Request &req, Response &res) {
  3732. target = req.target;
  3733. res.status = StatusCode::OK_200;
  3734. });
  3735. auto port = svr.bind_to_any_port(HOST);
  3736. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3737. auto se = detail::scope_exit([&] {
  3738. svr.stop();
  3739. thread.join();
  3740. ASSERT_FALSE(svr.is_running());
  3741. });
  3742. svr.wait_until_ready();
  3743. struct {
  3744. const char *path;
  3745. const char *expected;
  3746. } cases[] = {
  3747. {"/a b?x=1", "/a%20b?x=1"},
  3748. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3749. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3750. };
  3751. for (const auto &c : cases) {
  3752. Client cli(HOST, port);
  3753. target.clear();
  3754. auto res = cli.Get(c.path);
  3755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3756. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3757. auto buffered_target = target;
  3758. target.clear();
  3759. auto handle = cli.open_stream("GET", c.path);
  3760. EXPECT_TRUE(handle.is_valid())
  3761. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3762. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3763. }
  3764. }
  3765. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3766. // The `set_path_encode(false)` contract — transmit the supplied target
  3767. // verbatim — must hold for the streaming API too.
  3768. Server svr;
  3769. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3770. std::string target;
  3771. svr.Get("/foo", [&](const Request &req, Response &res) {
  3772. target = req.target;
  3773. res.status = StatusCode::OK_200;
  3774. });
  3775. auto port = svr.bind_to_any_port(HOST);
  3776. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3777. auto se = detail::scope_exit([&] {
  3778. svr.stop();
  3779. thread.join();
  3780. ASSERT_FALSE(svr.is_running());
  3781. });
  3782. svr.wait_until_ready();
  3783. {
  3784. Client cli(HOST, port);
  3785. cli.set_path_encode(false);
  3786. auto handle = cli.open_stream("GET", expected_target);
  3787. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3788. EXPECT_EQ(expected_target, target);
  3789. }
  3790. }
  3791. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3792. // With path encoding enabled a CR/LF in the target is percent-encoded
  3793. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3794. // write_request_line still backstops `set_path_encode(false)`, which is
  3795. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3796. Server svr;
  3797. // Captured before routing: the decoded path contains a newline, which a
  3798. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3799. std::string target;
  3800. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3801. target = req.target;
  3802. res.status = StatusCode::OK_200;
  3803. return Server::HandlerResponse::Handled;
  3804. });
  3805. auto port = svr.bind_to_any_port(HOST);
  3806. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3807. auto se = detail::scope_exit([&] {
  3808. svr.stop();
  3809. thread.join();
  3810. ASSERT_FALSE(svr.is_running());
  3811. });
  3812. svr.wait_until_ready();
  3813. {
  3814. Client cli(HOST, port);
  3815. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3816. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3817. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3818. }
  3819. }
  3820. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3821. // Every control character is percent-encoded, not just CR/LF, so the target
  3822. // passes the request-target check in write_request_line.
  3823. Server svr;
  3824. std::string target;
  3825. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3826. target = req.target;
  3827. res.status = StatusCode::OK_200;
  3828. return Server::HandlerResponse::Handled;
  3829. });
  3830. auto port = svr.bind_to_any_port(HOST);
  3831. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3832. auto se = detail::scope_exit([&] {
  3833. svr.stop();
  3834. thread.join();
  3835. ASSERT_FALSE(svr.is_running());
  3836. });
  3837. svr.wait_until_ready();
  3838. {
  3839. Client cli(HOST, port);
  3840. auto res = cli.Get("/a\tb\x1b\x7f");
  3841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3842. EXPECT_EQ("/a%09b%1B%7F", target);
  3843. }
  3844. }
  3845. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3846. // Nothing may reach the wire: a raw CR/LF target would split the request
  3847. // line and inject headers.
  3848. Server svr;
  3849. // Pre-routing so that "not called" means nothing reached the server at all,
  3850. // rather than merely failing to match a handler pattern.
  3851. auto handler_called = false;
  3852. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3853. handler_called = true;
  3854. res.status = StatusCode::OK_200;
  3855. return Server::HandlerResponse::Handled;
  3856. });
  3857. auto port = svr.bind_to_any_port(HOST);
  3858. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3859. auto se = detail::scope_exit([&] {
  3860. svr.stop();
  3861. thread.join();
  3862. ASSERT_FALSE(svr.is_running());
  3863. });
  3864. svr.wait_until_ready();
  3865. {
  3866. Client cli(HOST, port);
  3867. cli.set_path_encode(false);
  3868. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3869. EXPECT_FALSE(handle.is_valid());
  3870. EXPECT_EQ(Error::Write, handle.error);
  3871. EXPECT_FALSE(handler_called);
  3872. }
  3873. }
  3874. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3875. // Which of the two branches runs is decided by whether the query component
  3876. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3877. // an empty query and must still fall back to building one from
  3878. // `req.params`, while a non-empty query must win over `req.params`.
  3879. Server svr;
  3880. std::string target;
  3881. svr.Get("/foo", [&](const Request &req, Response &res) {
  3882. target = req.target;
  3883. res.status = StatusCode::OK_200;
  3884. });
  3885. auto port = svr.bind_to_any_port(HOST);
  3886. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3887. auto se = detail::scope_exit([&] {
  3888. svr.stop();
  3889. thread.join();
  3890. ASSERT_FALSE(svr.is_running());
  3891. });
  3892. svr.wait_until_ready();
  3893. {
  3894. // Trailing `?` -> empty query component -> `req.params` is used.
  3895. Client cli(HOST, port);
  3896. Request req;
  3897. req.method = "GET";
  3898. req.path = "/foo?";
  3899. req.params.emplace("a", "1");
  3900. target.clear();
  3901. auto res = cli.send(req);
  3902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3903. EXPECT_EQ("/foo?a=1", target);
  3904. }
  3905. {
  3906. // Non-empty query in `req.path` -> `req.params` is not appended.
  3907. Client cli(HOST, port);
  3908. Request req;
  3909. req.method = "GET";
  3910. req.path = "/foo?b=2";
  3911. req.params.emplace("a", "1");
  3912. target.clear();
  3913. auto res = cli.send(req);
  3914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3915. EXPECT_EQ("/foo?b=2", target);
  3916. }
  3917. }
  3918. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3919. Server svr;
  3920. svr.Get("/", [](const Request &req, Response &) {
  3921. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3922. });
  3923. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3924. auto se = detail::scope_exit([&] {
  3925. svr.stop();
  3926. thread.join();
  3927. ASSERT_FALSE(svr.is_running());
  3928. });
  3929. svr.wait_until_ready();
  3930. {
  3931. Client cli(HOST, PORT);
  3932. cli.set_path_encode(false);
  3933. auto res = cli.Get("/?something=%0A");
  3934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3935. EXPECT_EQ(StatusCode::OK_200, res->status);
  3936. }
  3937. }
  3938. TEST(BindServerTest, BindDualStack) {
  3939. Server svr;
  3940. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3941. res.set_content("Hello World!", "text/plain");
  3942. });
  3943. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3944. auto se = detail::scope_exit([&] {
  3945. svr.stop();
  3946. thread.join();
  3947. ASSERT_FALSE(svr.is_running());
  3948. });
  3949. svr.wait_until_ready();
  3950. {
  3951. Client cli("127.0.0.1", PORT);
  3952. auto res = cli.Get("/1");
  3953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. {
  3958. Client cli("::1", PORT);
  3959. auto res = cli.Get("/1");
  3960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3961. EXPECT_EQ(StatusCode::OK_200, res->status);
  3962. EXPECT_EQ("Hello World!", res->body);
  3963. }
  3964. }
  3965. TEST(BindServerTest, BindAndListenSeparately) {
  3966. Server svr;
  3967. int port = svr.bind_to_any_port("0.0.0.0");
  3968. ASSERT_TRUE(svr.is_valid());
  3969. ASSERT_TRUE(port > 0);
  3970. svr.stop();
  3971. }
  3972. // Reports whether anything is still listening on a loopback port. A plain
  3973. // connect() is used instead of a Client request because a socket left bound by
  3974. // mistake accepts the connection into its backlog and never answers, which
  3975. // would hang the test instead of failing it.
  3976. static bool is_loopback_port_accepting(int port) {
  3977. sockaddr_in addr{};
  3978. addr.sin_family = AF_INET;
  3979. addr.sin_port = htons(static_cast<uint16_t>(port));
  3980. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3981. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3982. EXPECT_NE(sock, INVALID_SOCKET);
  3983. if (sock == INVALID_SOCKET) { return false; }
  3984. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3985. static_cast<socklen_t>(sizeof(addr)));
  3986. detail::close_socket(sock);
  3987. return ret == 0;
  3988. }
  3989. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3990. Server svr;
  3991. auto port = svr.bind_to_any_port("127.0.0.1");
  3992. ASSERT_TRUE(port > 0);
  3993. svr.stop();
  3994. // bind_to_any_port() already called listen(2), so until stop() closed the
  3995. // descriptor the port kept accepting connections into the backlog. ASSERT
  3996. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3997. // below blocks forever in the accept loop.
  3998. ASSERT_FALSE(is_loopback_port_accepting(port));
  3999. // Nothing is left to accept on, so listen_after_bind() must report failure
  4000. // instead of returning success without ever serving.
  4001. EXPECT_FALSE(svr.listen_after_bind());
  4002. // The failed listen marks the server decommissioned, so a waiter returns
  4003. // instead of spinning forever.
  4004. svr.wait_until_ready();
  4005. }
  4006. #ifdef CPPHTTPLIB_SSL_ENABLED
  4007. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4009. CLIENT_CA_CERT_DIR);
  4010. int port = svr.bind_to_any_port("0.0.0.0");
  4011. ASSERT_TRUE(svr.is_valid());
  4012. ASSERT_TRUE(port > 0);
  4013. svr.stop();
  4014. }
  4015. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4016. // or a rejected CustomRoute() registration would not stop the server binding.
  4017. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4019. CLIENT_CA_CERT_DIR);
  4020. ASSERT_TRUE(svr.is_valid());
  4021. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4022. EXPECT_FALSE(svr.is_valid());
  4023. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4024. }
  4025. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4026. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4027. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4028. int port = svr.bind_to_any_port("0.0.0.0");
  4029. ASSERT_TRUE(svr.is_valid());
  4030. ASSERT_TRUE(port > 0);
  4031. svr.stop();
  4032. }
  4033. TEST(BindServerTest, UpdateCertsPem) {
  4034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4035. int port = svr.bind_to_any_port("0.0.0.0");
  4036. ASSERT_TRUE(svr.is_valid());
  4037. ASSERT_TRUE(port > 0);
  4038. // Read PEM files
  4039. std::string cert_pem, key_pem, ca_pem;
  4040. read_file(SERVER_CERT_FILE, cert_pem);
  4041. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4042. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4043. // Update server certificates using PEM API
  4044. ASSERT_TRUE(
  4045. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4046. ASSERT_TRUE(svr.is_valid());
  4047. svr.stop();
  4048. }
  4049. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4050. // Start server with client CA (enables client auth)
  4051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4052. ASSERT_TRUE(svr.is_valid());
  4053. bool handler_called = false;
  4054. svr.Get("/test", [&](const Request &req, Response &res) {
  4055. handler_called = true;
  4056. // Verify client certificate is present
  4057. auto cert = req.peer_cert();
  4058. EXPECT_TRUE(static_cast<bool>(cert));
  4059. res.set_content("ok", "text/plain");
  4060. });
  4061. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4062. auto se = detail::scope_exit([&] {
  4063. svr.stop();
  4064. t.join();
  4065. ASSERT_FALSE(svr.is_running());
  4066. });
  4067. svr.wait_until_ready();
  4068. // Read PEM files
  4069. std::string cert_pem, key_pem, ca_pem;
  4070. read_file(SERVER_CERT_FILE, cert_pem);
  4071. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4072. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4073. // Update server certificates and client CA using PEM API while server running
  4074. ASSERT_TRUE(
  4075. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4076. // Connect with client certificate
  4077. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4078. cli.enable_server_certificate_verification(false);
  4079. cli.set_connection_timeout(30);
  4080. auto res = cli.Get("/test");
  4081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4082. ASSERT_EQ(StatusCode::OK_200, res->status);
  4083. ASSERT_TRUE(handler_called);
  4084. EXPECT_EQ("ok", res->body);
  4085. }
  4086. // Puts a CA that did not sign the client's certificate in the old one's place.
  4087. static bool replace_client_ca(SSLServer &svr) {
  4088. std::string cert_pem, key_pem, ca_pem;
  4089. read_file(SERVER_CERT_FILE, cert_pem);
  4090. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4091. read_file(SERVER_CERT2_FILE, ca_pem);
  4092. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4093. ca_pem.c_str());
  4094. }
  4095. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4097. ASSERT_TRUE(svr.is_valid());
  4098. svr.Get("/test", [](const Request &, Response &res) {
  4099. res.set_content("ok", "text/plain");
  4100. });
  4101. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4102. auto se = detail::scope_exit([&] {
  4103. svr.stop();
  4104. t.join();
  4105. ASSERT_FALSE(svr.is_running());
  4106. });
  4107. svr.wait_until_ready();
  4108. auto get = [] {
  4109. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4110. cli.enable_server_certificate_verification(false);
  4111. return cli.Get("/test");
  4112. };
  4113. ASSERT_TRUE(get());
  4114. ASSERT_TRUE(replace_client_ca(svr));
  4115. EXPECT_FALSE(get());
  4116. }
  4117. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4118. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4119. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4120. ASSERT_TRUE(svr.is_valid());
  4121. tls::set_verify_callback(svr.tls_context(),
  4122. [](const tls::VerifyContext &) -> bool {
  4123. throw std::runtime_error("verify");
  4124. });
  4125. svr.Get("/test", [](const Request &, Response &res) {
  4126. res.set_content("ok", "text/plain");
  4127. });
  4128. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4129. auto se = detail::scope_exit([&] {
  4130. svr.stop();
  4131. t.join();
  4132. ASSERT_FALSE(svr.is_running());
  4133. });
  4134. svr.wait_until_ready();
  4135. auto get = [] {
  4136. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4137. cli.enable_server_certificate_verification(false);
  4138. return cli.Get("/test");
  4139. };
  4140. EXPECT_FALSE(get());
  4141. // The handshake is over, so an update does not wait for it.
  4142. std::string cert_pem, key_pem;
  4143. read_file(SERVER_CERT_FILE, cert_pem);
  4144. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4145. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4146. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4147. return v.preverify_ok;
  4148. });
  4149. auto res = get();
  4150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4151. EXPECT_EQ("ok", res->body);
  4152. }
  4153. #endif
  4154. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4155. // Sends each request over a new connection with a client certificate,
  4156. // resuming the session of the one before when there is one.
  4157. class ResumingClient {
  4158. public:
  4159. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4160. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4161. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4162. SSL_FILETYPE_PEM);
  4163. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4164. // callback, not through SSL_get1_session().
  4165. SSL_CTX_set_app_data(ctx_, this);
  4166. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4167. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4168. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4169. auto self = static_cast<ResumingClient *>(
  4170. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4171. SSL_SESSION_free(self->session_);
  4172. self->session_ = session;
  4173. return 1; // Keeps the reference
  4174. });
  4175. }
  4176. ~ResumingClient() {
  4177. SSL_SESSION_free(session_);
  4178. SSL_CTX_free(ctx_);
  4179. }
  4180. // Tells whether the request was answered.
  4181. bool get() {
  4182. auto error = Error::Success;
  4183. auto sock = detail::create_client_socket(
  4184. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4185. /*connection_timeout_sec=*/5, 0,
  4186. /*read_timeout_sec=*/5, 0,
  4187. /*write_timeout_sec=*/5, 0, std::string(), error);
  4188. if (sock == INVALID_SOCKET) { return false; }
  4189. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4190. auto ssl = SSL_new(ctx_);
  4191. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4192. SSL_set_fd(ssl, static_cast<int>(sock));
  4193. if (session_) { SSL_set_session(ssl, session_); }
  4194. if (SSL_connect(ssl) != 1) { return false; }
  4195. reused_ = SSL_session_reused(ssl) == 1;
  4196. // Reading the response also takes in a TLS 1.3 session ticket.
  4197. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4198. "Connection: close\r\n\r\n";
  4199. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4200. std::string res;
  4201. char buf[256];
  4202. int n;
  4203. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4204. res.append(buf, static_cast<size_t>(n));
  4205. }
  4206. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4207. SSL_shutdown(ssl);
  4208. return res.find("200 OK") != std::string::npos;
  4209. }
  4210. // Whether the last connection resumed a session
  4211. bool reused() const { return reused_; }
  4212. private:
  4213. SSL_CTX *ctx_;
  4214. SSL_SESSION *session_ = nullptr;
  4215. bool reused_ = false;
  4216. };
  4217. // A client that resumes its session gets through, but not once the client CA
  4218. // has changed, as a resumed session does not show the certificate again.
  4219. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4221. ASSERT_TRUE(svr.is_valid());
  4222. svr.Get("/test", [](const Request &, Response &res) {
  4223. res.set_content("ok", "text/plain");
  4224. });
  4225. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4226. auto se = detail::scope_exit([&] {
  4227. svr.stop();
  4228. t.join();
  4229. ASSERT_FALSE(svr.is_running());
  4230. });
  4231. svr.wait_until_ready();
  4232. ResumingClient cli;
  4233. ASSERT_TRUE(cli.get());
  4234. ASSERT_TRUE(cli.get());
  4235. EXPECT_TRUE(cli.reused());
  4236. ASSERT_TRUE(replace_client_ca(svr));
  4237. EXPECT_FALSE(cli.get());
  4238. }
  4239. // A resumed session does not show the certificate again, so the server does
  4240. // not resume one with a verify callback to run on it.
  4241. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4242. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4243. ASSERT_TRUE(svr.is_valid());
  4244. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4245. return v.preverify_ok;
  4246. });
  4247. svr.Get("/test", [](const Request &, Response &res) {
  4248. res.set_content("ok", "text/plain");
  4249. });
  4250. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4251. auto se = detail::scope_exit([&] {
  4252. svr.stop();
  4253. t.join();
  4254. ASSERT_FALSE(svr.is_running());
  4255. });
  4256. svr.wait_until_ready();
  4257. ResumingClient cli;
  4258. ASSERT_TRUE(cli.get());
  4259. ASSERT_TRUE(cli.get());
  4260. EXPECT_FALSE(cli.reused());
  4261. }
  4262. #endif
  4263. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4264. // wolfSSL shares its session cache between contexts, so a resumed session
  4265. // could carry a client certificate checked against another server's CA, or
  4266. // against a client CA since replaced.
  4267. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4269. ASSERT_TRUE(svr.is_valid());
  4270. // Trusts a CA that did not sign the client's certificate.
  4271. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4272. ASSERT_TRUE(other.is_valid());
  4273. for (auto s : {&svr, &other}) {
  4274. s->Get("/test", [](const Request &, Response &res) {
  4275. res.set_content("ok", "text/plain");
  4276. });
  4277. }
  4278. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4279. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4280. auto se = detail::scope_exit([&] {
  4281. other.stop();
  4282. svr.stop();
  4283. t2.join();
  4284. t.join();
  4285. });
  4286. svr.wait_until_ready();
  4287. other.wait_until_ready();
  4288. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4289. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4290. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4291. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4292. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4293. ASSERT_EQ(WOLFSSL_SUCCESS,
  4294. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4295. WOLFSSL_FILETYPE_PEM));
  4296. WOLFSSL_SESSION *session = nullptr;
  4297. auto session_se = detail::scope_exit([&] {
  4298. if (session) { wolfSSL_SESSION_free(session); }
  4299. });
  4300. // A request over a new connection, resuming `session` when there is one and
  4301. // keeping the connection's own in its place. Tells whether it was answered.
  4302. auto get = [&](int port) {
  4303. auto error = Error::Success;
  4304. auto sock = detail::create_client_socket(
  4305. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4306. /*connection_timeout_sec=*/5, 0,
  4307. /*read_timeout_sec=*/5, 0,
  4308. /*write_timeout_sec=*/5, 0, std::string(), error);
  4309. if (sock == INVALID_SOCKET) { return false; }
  4310. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4311. auto ssl = wolfSSL_new(ctx);
  4312. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4313. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4314. if (session) { wolfSSL_set_session(ssl, session); }
  4315. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4316. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4317. "Connection: close\r\n\r\n";
  4318. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4319. std::string res;
  4320. char buf[256];
  4321. int n;
  4322. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4323. res.append(buf, static_cast<size_t>(n));
  4324. }
  4325. wolfSSL_shutdown(ssl);
  4326. if (session) { wolfSSL_SESSION_free(session); }
  4327. session = wolfSSL_get1_session(ssl);
  4328. return res.find("200 OK") != std::string::npos;
  4329. };
  4330. ASSERT_TRUE(get(PORT));
  4331. EXPECT_FALSE(get(PORT + 1));
  4332. ASSERT_TRUE(get(PORT));
  4333. ASSERT_TRUE(replace_client_ca(svr));
  4334. EXPECT_FALSE(get(PORT));
  4335. }
  4336. #endif
  4337. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4339. ASSERT_TRUE(svr.is_valid());
  4340. svr.Get("/test", [](const Request &, Response &res) {
  4341. res.set_content("ok", "text/plain");
  4342. });
  4343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4344. auto se = detail::scope_exit([&] {
  4345. svr.stop();
  4346. t.join();
  4347. ASSERT_FALSE(svr.is_running());
  4348. });
  4349. svr.wait_until_ready();
  4350. // A connection that sends no ClientHello keeps its handshake in progress,
  4351. // once the server has had a moment to start it.
  4352. auto error = Error::Success;
  4353. auto sock = detail::create_client_socket(
  4354. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4355. /*connection_timeout_sec=*/5, 0,
  4356. /*read_timeout_sec=*/5, 0,
  4357. /*write_timeout_sec=*/5, 0, std::string(), error);
  4358. ASSERT_NE(INVALID_SOCKET, sock);
  4359. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4360. std::string cert_pem, key_pem;
  4361. read_file(SERVER_CERT_FILE, cert_pem);
  4362. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4363. auto update = std::async(std::launch::async, [&]() {
  4364. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4365. });
  4366. EXPECT_EQ(std::future_status::timeout,
  4367. update.wait_for(std::chrono::milliseconds(200)));
  4368. detail::close_socket(sock);
  4369. EXPECT_TRUE(update.get());
  4370. SSLClient cli(HOST, PORT);
  4371. cli.enable_server_certificate_verification(false);
  4372. auto res = cli.Get("/test");
  4373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4374. EXPECT_EQ(StatusCode::OK_200, res->status);
  4375. }
  4376. #endif
  4377. TEST(ErrorHandlerTest, ContentLength) {
  4378. Server svr;
  4379. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4380. res.status = StatusCode::OK_200;
  4381. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4382. "text/html"); // <= Content-Length still 13
  4383. });
  4384. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4385. res.set_content("Hello World!\n", "text/plain");
  4386. res.status = 524;
  4387. });
  4388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4389. auto se = detail::scope_exit([&] {
  4390. svr.stop();
  4391. thread.join();
  4392. ASSERT_FALSE(svr.is_running());
  4393. });
  4394. svr.wait_until_ready();
  4395. {
  4396. Client cli(HOST, PORT);
  4397. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4399. EXPECT_EQ(StatusCode::OK_200, res->status);
  4400. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4401. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4402. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4403. }
  4404. }
  4405. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4406. TEST(ExceptionTest, WithoutExceptionHandler) {
  4407. Server svr;
  4408. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4409. throw std::runtime_error("exception...");
  4410. });
  4411. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4412. throw std::runtime_error("exception\r\n...");
  4413. });
  4414. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4415. auto se = detail::scope_exit([&] {
  4416. svr.stop();
  4417. listen_thread.join();
  4418. ASSERT_FALSE(svr.is_running());
  4419. });
  4420. svr.wait_until_ready();
  4421. Client cli("localhost", PORT);
  4422. {
  4423. auto res = cli.Get("/exception");
  4424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4425. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4426. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4427. }
  4428. {
  4429. auto res = cli.Get("/unknown");
  4430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4431. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4432. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4433. }
  4434. }
  4435. TEST(ExceptionTest, WithExceptionHandler) {
  4436. Server svr;
  4437. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4438. std::exception_ptr ep) {
  4439. EXPECT_FALSE(ep == nullptr);
  4440. try {
  4441. std::rethrow_exception(ep);
  4442. } catch (std::exception &e) {
  4443. EXPECT_EQ("abc", std::string(e.what()));
  4444. } catch (...) {}
  4445. res.status = StatusCode::InternalServerError_500;
  4446. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4447. "text/html"); // <= Content-Length still 13 at this point
  4448. });
  4449. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4450. res.set_content("Hello World!\n", "text/plain");
  4451. throw std::runtime_error("abc");
  4452. });
  4453. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4454. auto se = detail::scope_exit([&] {
  4455. svr.stop();
  4456. thread.join();
  4457. ASSERT_FALSE(svr.is_running());
  4458. });
  4459. svr.wait_until_ready();
  4460. for (size_t i = 0; i < 10; i++) {
  4461. Client cli(HOST, PORT);
  4462. for (size_t j = 0; j < 100; j++) {
  4463. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4465. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4466. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4467. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4468. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4469. }
  4470. cli.set_keep_alive(true);
  4471. for (size_t j = 0; j < 100; j++) {
  4472. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4474. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4475. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4476. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4477. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4478. }
  4479. }
  4480. }
  4481. TEST(ExceptionTest, AndErrorHandler) {
  4482. Server svr;
  4483. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4484. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4485. });
  4486. svr.set_exception_handler(
  4487. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4488. EXPECT_FALSE(ep == nullptr);
  4489. try {
  4490. std::rethrow_exception(ep);
  4491. } catch (std::exception &e) {
  4492. res.set_content(e.what(), "text/html");
  4493. } catch (...) {}
  4494. res.status = StatusCode::InternalServerError_500;
  4495. });
  4496. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4497. throw std::runtime_error("EXCEPTION");
  4498. });
  4499. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4500. res.set_content("ERROR", "text/html");
  4501. res.status = StatusCode::InternalServerError_500;
  4502. });
  4503. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4504. auto se = detail::scope_exit([&] {
  4505. svr.stop();
  4506. thread.join();
  4507. ASSERT_FALSE(svr.is_running());
  4508. });
  4509. svr.wait_until_ready();
  4510. Client cli(HOST, PORT);
  4511. {
  4512. auto res = cli.Get("/exception");
  4513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4514. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4515. EXPECT_EQ("EXCEPTION", res->body);
  4516. }
  4517. {
  4518. auto res = cli.Get("/error");
  4519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4520. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4521. EXPECT_EQ("ERROR", res->body);
  4522. }
  4523. {
  4524. auto res = cli.Get("/invalid");
  4525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4527. EXPECT_EQ("NOT_FOUND", res->body);
  4528. }
  4529. }
  4530. #endif
  4531. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4532. // process_request() wraps only routing() in a try/catch, so an exception from
  4533. // any other user callback used to unwind into the task queue - which does not
  4534. // catch - and terminate the process. Each test below runs the server on a
  4535. // single worker thread: a guard that catches the exception but still loses the
  4536. // thread would otherwise be hidden by a spare worker serving the follow-up
  4537. // request. Note that a regression here aborts the whole test binary rather
  4538. // than failing one test.
  4539. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4540. Server svr;
  4541. svr.new_task_queue = [] { return new ThreadPool(1); };
  4542. std::atomic<int> reported{0};
  4543. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4544. if (err == Error::UserCallbackException) { reported++; }
  4545. });
  4546. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4547. res.set_content_provider(
  4548. 1024, "text/plain",
  4549. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4550. sink.write("hello", 5);
  4551. throw std::runtime_error("from the content provider");
  4552. });
  4553. });
  4554. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4555. res.set_content("ok", "text/plain");
  4556. });
  4557. auto port = svr.bind_to_any_port(HOST);
  4558. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4559. auto se = detail::scope_exit([&] {
  4560. svr.stop();
  4561. listen_thread.join();
  4562. ASSERT_FALSE(svr.is_running());
  4563. });
  4564. svr.wait_until_ready();
  4565. {
  4566. Client cli(HOST, port);
  4567. cli.set_read_timeout(5, 0);
  4568. EXPECT_FALSE(cli.Get("/throw"));
  4569. }
  4570. EXPECT_TRUE(svr.is_running());
  4571. EXPECT_EQ(1, reported.load());
  4572. // A request on a fresh connection is still served.
  4573. {
  4574. Client cli(HOST, port);
  4575. auto res = cli.Get("/ok");
  4576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4577. EXPECT_EQ(StatusCode::OK_200, res->status);
  4578. EXPECT_EQ("ok", res->body);
  4579. }
  4580. }
  4581. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4582. Server svr;
  4583. svr.new_task_queue = [] { return new ThreadPool(1); };
  4584. std::atomic<bool> should_throw{true};
  4585. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4586. res.set_content("hi", "text/plain");
  4587. });
  4588. svr.set_post_routing_handler(
  4589. [&](const Request & /*req*/, Response & /*res*/) {
  4590. if (should_throw) {
  4591. throw std::runtime_error("from the post-routing handler");
  4592. }
  4593. });
  4594. auto port = svr.bind_to_any_port(HOST);
  4595. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4596. auto se = detail::scope_exit([&] {
  4597. svr.stop();
  4598. listen_thread.join();
  4599. ASSERT_FALSE(svr.is_running());
  4600. });
  4601. svr.wait_until_ready();
  4602. {
  4603. Client cli(HOST, port);
  4604. cli.set_read_timeout(5, 0);
  4605. EXPECT_FALSE(cli.Get("/hi"));
  4606. }
  4607. EXPECT_TRUE(svr.is_running());
  4608. should_throw = false;
  4609. {
  4610. Client cli(HOST, port);
  4611. auto res = cli.Get("/hi");
  4612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("hi", res->body);
  4615. }
  4616. }
  4617. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4618. // The guard reports the caught exception through the error logger, which is
  4619. // a user callback too. A logger that throws has to be contained as well, or
  4620. // the process would terminate from inside the catch.
  4621. Server svr;
  4622. svr.new_task_queue = [] { return new ThreadPool(1); };
  4623. std::atomic<int> reported{0};
  4624. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4625. if (err == Error::UserCallbackException) {
  4626. reported++;
  4627. throw std::runtime_error("from the error logger");
  4628. }
  4629. });
  4630. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4631. res.set_content_provider(
  4632. 1024, "text/plain",
  4633. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4634. sink.write("hello", 5);
  4635. throw std::runtime_error("from the content provider");
  4636. });
  4637. });
  4638. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4639. res.set_content("ok", "text/plain");
  4640. });
  4641. auto port = svr.bind_to_any_port(HOST);
  4642. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4643. auto se = detail::scope_exit([&] {
  4644. svr.stop();
  4645. listen_thread.join();
  4646. ASSERT_FALSE(svr.is_running());
  4647. });
  4648. svr.wait_until_ready();
  4649. {
  4650. Client cli(HOST, port);
  4651. cli.set_read_timeout(5, 0);
  4652. EXPECT_FALSE(cli.Get("/throw"));
  4653. }
  4654. EXPECT_TRUE(svr.is_running());
  4655. EXPECT_EQ(1, reported.load());
  4656. {
  4657. Client cli(HOST, port);
  4658. auto res = cli.Get("/ok");
  4659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4660. EXPECT_EQ(StatusCode::OK_200, res->status);
  4661. EXPECT_EQ("ok", res->body);
  4662. }
  4663. }
  4664. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4665. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4666. // so the exception unwinds through the ws::WebSocket object on its way to
  4667. // the guard. None of the HTTP cases above cross that.
  4668. Server svr;
  4669. svr.new_task_queue = [] { return new ThreadPool(1); };
  4670. std::atomic<int> reported{0};
  4671. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4672. if (err == Error::UserCallbackException) { reported++; }
  4673. });
  4674. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4675. throw std::runtime_error("from the WebSocket handler");
  4676. });
  4677. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4678. res.set_content("ok", "text/plain");
  4679. });
  4680. auto port = svr.bind_to_any_port(HOST);
  4681. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4682. auto se = detail::scope_exit([&] {
  4683. svr.stop();
  4684. listen_thread.join();
  4685. ASSERT_FALSE(svr.is_running());
  4686. });
  4687. svr.wait_until_ready();
  4688. {
  4689. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4690. "/ws");
  4691. auto res = client.connect();
  4692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4693. // The server dropped the connection instead of dying.
  4694. std::string msg;
  4695. EXPECT_FALSE(client.read(msg));
  4696. client.close();
  4697. }
  4698. EXPECT_TRUE(svr.is_running());
  4699. EXPECT_EQ(1, reported.load());
  4700. {
  4701. Client cli(HOST, port);
  4702. auto res = cli.Get("/ok");
  4703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4704. EXPECT_EQ(StatusCode::OK_200, res->status);
  4705. EXPECT_EQ("ok", res->body);
  4706. }
  4707. }
  4708. #ifdef CPPHTTPLIB_SSL_ENABLED
  4709. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4710. // SSLServer::process_and_close_socket() is a separate overload with its own
  4711. // guard, so it is exercised on its own.
  4712. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4713. ASSERT_TRUE(svr.is_valid());
  4714. svr.new_task_queue = [] { return new ThreadPool(1); };
  4715. std::atomic<int> reported{0};
  4716. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4717. if (err == Error::UserCallbackException) { reported++; }
  4718. });
  4719. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4720. res.set_content_provider(
  4721. 1024, "text/plain",
  4722. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4723. sink.write("hello", 5);
  4724. throw std::runtime_error("from the content provider");
  4725. });
  4726. });
  4727. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4728. res.set_content("ok", "text/plain");
  4729. });
  4730. auto port = svr.bind_to_any_port(HOST);
  4731. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4732. auto se = detail::scope_exit([&] {
  4733. svr.stop();
  4734. listen_thread.join();
  4735. ASSERT_FALSE(svr.is_running());
  4736. });
  4737. svr.wait_until_ready();
  4738. {
  4739. SSLClient cli(HOST, port);
  4740. cli.enable_server_certificate_verification(false);
  4741. cli.set_read_timeout(5, 0);
  4742. EXPECT_FALSE(cli.Get("/throw"));
  4743. }
  4744. EXPECT_TRUE(svr.is_running());
  4745. EXPECT_EQ(1, reported.load());
  4746. {
  4747. SSLClient cli(HOST, port);
  4748. cli.enable_server_certificate_verification(false);
  4749. auto res = cli.Get("/ok");
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::OK_200, res->status);
  4752. EXPECT_EQ("ok", res->body);
  4753. }
  4754. }
  4755. #endif
  4756. #endif
  4757. TEST(NoContentTest, ContentLength) {
  4758. Server svr;
  4759. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4760. res.status = StatusCode::NoContent_204;
  4761. });
  4762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4763. auto se = detail::scope_exit([&] {
  4764. svr.stop();
  4765. thread.join();
  4766. ASSERT_FALSE(svr.is_running());
  4767. });
  4768. svr.wait_until_ready();
  4769. {
  4770. Client cli(HOST, PORT);
  4771. auto res = cli.Get("/hi");
  4772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4773. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4774. // RFC 9110 8.6: none in a 204 response
  4775. EXPECT_FALSE(res->has_header("Content-Length"));
  4776. }
  4777. }
  4778. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4779. Server svr;
  4780. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4781. res.set_header("Content-Length", "5");
  4782. res.set_content("hello world", "text/plain");
  4783. });
  4784. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4785. // A body that reads as the last chunk, were it taken as chunked
  4786. res.set_header("Transfer-Encoding", "chunked");
  4787. res.set_content("0\r\n\r\n", "text/plain");
  4788. });
  4789. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4790. res.set_header("Content-Length", "2");
  4791. res.set_content_provider(5, "text/plain",
  4792. [](size_t offset, size_t length, DataSink &sink) {
  4793. sink.write(&"hello"[offset], length);
  4794. return true;
  4795. });
  4796. });
  4797. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4798. res.set_header("Content-Length", "1234");
  4799. });
  4800. thread t = thread([&] { svr.listen(HOST, PORT); });
  4801. auto se = detail::scope_exit([&] {
  4802. svr.stop();
  4803. t.join();
  4804. ASSERT_FALSE(svr.is_running());
  4805. });
  4806. svr.wait_until_ready();
  4807. Client cli(HOST, PORT);
  4808. cli.set_read_timeout(1, 0);
  4809. auto expect_body = [&](const Result &res, const std::string &body) {
  4810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4811. EXPECT_EQ(body, res->body);
  4812. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4813. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4814. };
  4815. Headers identity{{"Accept-Encoding", ""}};
  4816. expect_body(cli.Get("/body", identity), "hello world");
  4817. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4818. expect_body(cli.Get("/body",
  4819. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4820. "he");
  4821. expect_body(cli.Get("/provider", identity), "hello");
  4822. expect_body(cli.Get("/empty", identity), "");
  4823. // A HEAD response may give the length of the body a GET would get.
  4824. auto res = cli.Head("/empty");
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4827. }
  4828. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4829. Server svr;
  4830. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4831. res.set_content("short", "text/plain");
  4832. });
  4833. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4834. res.body += " with a footer";
  4835. res.set_header("Transfer-Encoding", "chunked");
  4836. });
  4837. thread t = thread([&] { svr.listen(HOST, PORT); });
  4838. auto se = detail::scope_exit([&] {
  4839. svr.stop();
  4840. t.join();
  4841. ASSERT_FALSE(svr.is_running());
  4842. });
  4843. svr.wait_until_ready();
  4844. Client cli(HOST, PORT);
  4845. cli.set_read_timeout(1, 0);
  4846. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4848. EXPECT_EQ("short with a footer", res->body);
  4849. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4850. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4851. }
  4852. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4853. Server svr;
  4854. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4855. res.set_header("Content-Length", "3");
  4856. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4857. sink.write("abc", 3);
  4858. sink.done();
  4859. return true;
  4860. });
  4861. });
  4862. thread t = thread([&] { svr.listen(HOST, PORT); });
  4863. auto se = detail::scope_exit([&] {
  4864. svr.stop();
  4865. t.join();
  4866. ASSERT_FALSE(svr.is_running());
  4867. });
  4868. svr.wait_until_ready();
  4869. Client cli(HOST, PORT);
  4870. cli.set_keep_alive(true);
  4871. auto res = cli.Get("/");
  4872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4873. EXPECT_EQ("abc", res->body);
  4874. EXPECT_FALSE(res->has_header("Content-Length"));
  4875. EXPECT_EQ("close", res->get_header_value("Connection"));
  4876. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4877. // No body to delimit
  4878. auto head = cli.Head("/");
  4879. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4880. EXPECT_FALSE(head->has_header("Connection"));
  4881. }
  4882. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4883. #ifdef CPPHTTPLIB_SSL_ENABLED
  4884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4885. ASSERT_TRUE(svr.is_valid());
  4886. #else
  4887. Server svr;
  4888. #endif
  4889. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4890. if (req.path == "/routing_handler") {
  4891. res.set_header("PRE_ROUTING", "on");
  4892. res.set_content("Routing Handler", "text/plain");
  4893. return httplib::Server::HandlerResponse::Handled;
  4894. }
  4895. return httplib::Server::HandlerResponse::Unhandled;
  4896. });
  4897. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4898. res.set_content("Error", "text/html");
  4899. });
  4900. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4901. if (req.path == "/routing_handler") {
  4902. res.set_header("POST_ROUTING", "on");
  4903. }
  4904. });
  4905. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4906. res.set_content("Hello World!\n", "text/plain");
  4907. });
  4908. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4909. auto se = detail::scope_exit([&] {
  4910. svr.stop();
  4911. thread.join();
  4912. ASSERT_FALSE(svr.is_running());
  4913. });
  4914. svr.wait_until_ready();
  4915. {
  4916. #ifdef CPPHTTPLIB_SSL_ENABLED
  4917. SSLClient cli(HOST, PORT);
  4918. cli.enable_server_certificate_verification(false);
  4919. #else
  4920. Client cli(HOST, PORT);
  4921. #endif
  4922. auto res = cli.Get("/routing_handler");
  4923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4924. EXPECT_EQ(StatusCode::OK_200, res->status);
  4925. EXPECT_EQ("Routing Handler", res->body);
  4926. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4927. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4928. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4929. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4930. }
  4931. {
  4932. #ifdef CPPHTTPLIB_SSL_ENABLED
  4933. SSLClient cli(HOST, PORT);
  4934. cli.enable_server_certificate_verification(false);
  4935. #else
  4936. Client cli(HOST, PORT);
  4937. #endif
  4938. auto res = cli.Get("/hi");
  4939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4940. EXPECT_EQ(StatusCode::OK_200, res->status);
  4941. EXPECT_EQ("Hello World!\n", res->body);
  4942. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4943. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4944. }
  4945. {
  4946. #ifdef CPPHTTPLIB_SSL_ENABLED
  4947. SSLClient cli(HOST, PORT);
  4948. cli.enable_server_certificate_verification(false);
  4949. #else
  4950. Client cli(HOST, PORT);
  4951. #endif
  4952. auto res = cli.Get("/aaa");
  4953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4954. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4955. EXPECT_EQ("Error", res->body);
  4956. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4957. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4958. }
  4959. }
  4960. TEST(RequestHandlerTest, PreRequestHandler) {
  4961. auto route_path = "/user/:user";
  4962. Server svr;
  4963. svr.Get("/hi", [](const Request &, Response &res) {
  4964. res.set_content("hi", "text/plain");
  4965. });
  4966. svr.Get(route_path, [](const Request &req, Response &res) {
  4967. res.set_content(req.path_params.at("user"), "text/plain");
  4968. });
  4969. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4970. if (req.matched_route == route_path) {
  4971. auto user = req.path_params.at("user");
  4972. if (user != "john") {
  4973. res.status = StatusCode::Forbidden_403;
  4974. res.set_content("error", "text/html");
  4975. return Server::HandlerResponse::Handled;
  4976. }
  4977. }
  4978. return Server::HandlerResponse::Unhandled;
  4979. });
  4980. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4981. auto se = detail::scope_exit([&] {
  4982. svr.stop();
  4983. thread.join();
  4984. ASSERT_FALSE(svr.is_running());
  4985. });
  4986. svr.wait_until_ready();
  4987. Client cli(HOST, PORT);
  4988. {
  4989. auto res = cli.Get("/hi");
  4990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4991. EXPECT_EQ(StatusCode::OK_200, res->status);
  4992. EXPECT_EQ("hi", res->body);
  4993. }
  4994. {
  4995. auto res = cli.Get("/user/john");
  4996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4997. EXPECT_EQ(StatusCode::OK_200, res->status);
  4998. EXPECT_EQ("john", res->body);
  4999. }
  5000. {
  5001. auto res = cli.Get("/user/invalid-user");
  5002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5003. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5004. EXPECT_EQ("error", res->body);
  5005. }
  5006. }
  5007. // The pre-request handler must run before the request body is read, so a
  5008. // rejected request never forces the server to buffer a (potentially large)
  5009. // body. Here the posted body is larger than the payload limit: if the body
  5010. // were read first the server would answer 413, but because the pre-request
  5011. // handler runs first it answers 403 and the body is never read.
  5012. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5013. Server svr;
  5014. svr.set_payload_max_length(8);
  5015. auto handler_ran = false;
  5016. svr.Post("/reject", [&](const Request &req, Response &res) {
  5017. handler_ran = true;
  5018. res.set_content(req.body, "text/plain");
  5019. });
  5020. svr.Post("/accept", [](const Request &req, Response &res) {
  5021. res.set_content(req.body, "text/plain");
  5022. });
  5023. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5024. if (req.matched_route == "/reject") {
  5025. res.status = StatusCode::Forbidden_403;
  5026. res.set_content("denied", "text/plain");
  5027. return Server::HandlerResponse::Handled;
  5028. }
  5029. return Server::HandlerResponse::Unhandled;
  5030. });
  5031. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5032. auto se = detail::scope_exit([&] {
  5033. svr.stop();
  5034. thread.join();
  5035. ASSERT_FALSE(svr.is_running());
  5036. });
  5037. svr.wait_until_ready();
  5038. Client cli(HOST, PORT);
  5039. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5040. // rejects with 403 before the body is read, so 413 is never reached.
  5041. {
  5042. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5044. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5045. EXPECT_EQ("denied", res->body);
  5046. EXPECT_FALSE(handler_ran);
  5047. }
  5048. // An approved route still reads the body and enforces the payload limit.
  5049. {
  5050. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5052. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5053. }
  5054. }
  5055. TEST(UserDataTest, BasicOperations) {
  5056. httplib::UserData ud;
  5057. // Initially empty
  5058. EXPECT_FALSE(ud.has("key"));
  5059. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5060. // set and get
  5061. ud.set("key", 42);
  5062. EXPECT_TRUE(ud.has("key"));
  5063. auto *p = ud.get<int>("key");
  5064. ASSERT_NE(nullptr, p);
  5065. EXPECT_EQ(42, *p);
  5066. // Type mismatch → nullptr
  5067. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5068. // Overwrite with different type
  5069. ud.set("key", std::string("hello"));
  5070. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5071. auto *s = ud.get<std::string>("key");
  5072. ASSERT_NE(nullptr, s);
  5073. EXPECT_EQ("hello", *s);
  5074. // erase
  5075. ud.erase("key");
  5076. EXPECT_FALSE(ud.has("key"));
  5077. // clear
  5078. ud.set("a", 1);
  5079. ud.set("b", 2);
  5080. ud.clear();
  5081. EXPECT_FALSE(ud.has("a"));
  5082. EXPECT_FALSE(ud.has("b"));
  5083. }
  5084. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5085. struct AuthCtx {
  5086. std::string user_id;
  5087. };
  5088. Server svr;
  5089. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5090. res.user_data.set("auth", AuthCtx{"alice"});
  5091. return Server::HandlerResponse::Unhandled;
  5092. });
  5093. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5094. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5095. ASSERT_NE(nullptr, ctx);
  5096. res.set_content("Hello " + ctx->user_id, "text/plain");
  5097. });
  5098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5099. auto se = detail::scope_exit([&] {
  5100. svr.stop();
  5101. thread.join();
  5102. ASSERT_FALSE(svr.is_running());
  5103. });
  5104. svr.wait_until_ready();
  5105. Client cli(HOST, PORT);
  5106. auto res = cli.Get("/me");
  5107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5108. EXPECT_EQ(StatusCode::OK_200, res->status);
  5109. EXPECT_EQ("Hello alice", res->body);
  5110. }
  5111. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5112. struct RoleCtx {
  5113. std::string role;
  5114. };
  5115. Server svr;
  5116. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5117. res.user_data.set("role", RoleCtx{"admin"});
  5118. return Server::HandlerResponse::Unhandled;
  5119. });
  5120. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5121. auto *ctx = res.user_data.get<RoleCtx>("role");
  5122. ASSERT_NE(nullptr, ctx);
  5123. res.set_content(ctx->role, "text/plain");
  5124. });
  5125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5126. auto se = detail::scope_exit([&] {
  5127. svr.stop();
  5128. thread.join();
  5129. ASSERT_FALSE(svr.is_running());
  5130. });
  5131. svr.wait_until_ready();
  5132. Client cli(HOST, PORT);
  5133. auto res = cli.Get("/role");
  5134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5135. EXPECT_EQ(StatusCode::OK_200, res->status);
  5136. EXPECT_EQ("admin", res->body);
  5137. }
  5138. TEST(InvalidFormatTest, StatusCode) {
  5139. Server svr;
  5140. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5141. res.set_content("Hello World!\n", "text/plain");
  5142. res.status = 9999; // Status should be a three-digit code...
  5143. });
  5144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5145. auto se = detail::scope_exit([&] {
  5146. svr.stop();
  5147. thread.join();
  5148. ASSERT_FALSE(svr.is_running());
  5149. });
  5150. svr.wait_until_ready();
  5151. {
  5152. Client cli(HOST, PORT);
  5153. auto res = cli.Get("/hi");
  5154. ASSERT_FALSE(res);
  5155. }
  5156. }
  5157. TEST(URLFragmentTest, WithFragment) {
  5158. Server svr;
  5159. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5160. EXPECT_TRUE(req.target == "/hi");
  5161. });
  5162. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5163. auto se = detail::scope_exit([&] {
  5164. svr.stop();
  5165. thread.join();
  5166. ASSERT_FALSE(svr.is_running());
  5167. });
  5168. svr.wait_until_ready();
  5169. {
  5170. Client cli(HOST, PORT);
  5171. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5172. EXPECT_TRUE(res);
  5173. EXPECT_EQ(StatusCode::OK_200, res->status);
  5174. res = cli.Get("/hi%23key1=val1=key2=val2");
  5175. EXPECT_TRUE(res);
  5176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5177. }
  5178. }
  5179. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5180. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5181. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5182. Server svr;
  5183. std::vector<std::string> targets;
  5184. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5185. targets.push_back(req.target);
  5186. });
  5187. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5188. auto se = detail::scope_exit([&] {
  5189. svr.stop();
  5190. thread.join();
  5191. ASSERT_FALSE(svr.is_running());
  5192. });
  5193. svr.wait_until_ready();
  5194. Client cli(HOST, PORT);
  5195. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5196. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5197. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5198. // A '?' after the '#' belongs to the fragment, not to the query.
  5199. Request req;
  5200. req.method = "GET";
  5201. req.path = "/hi#f?x=1";
  5202. req.params.emplace("a", "1");
  5203. Response res;
  5204. auto error = Error::Success;
  5205. EXPECT_TRUE(cli.send(req, res, error));
  5206. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5207. "/hi?a=1"}),
  5208. targets);
  5209. }
  5210. TEST(HeaderWriter, SetHeaderWriter) {
  5211. Server svr;
  5212. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5213. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5214. return detail::write_headers(strm, hdrs);
  5215. });
  5216. svr.Get("/hi", [](const Request &req, Response &res) {
  5217. auto it = req.headers.find("CustomClientHeader");
  5218. EXPECT_TRUE(it != req.headers.end());
  5219. EXPECT_EQ(it->second, "CustomClientValue");
  5220. res.set_content("Hello World!\n", "text/plain");
  5221. });
  5222. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5223. auto se = detail::scope_exit([&] {
  5224. svr.stop();
  5225. thread.join();
  5226. ASSERT_FALSE(svr.is_running());
  5227. });
  5228. svr.wait_until_ready();
  5229. {
  5230. Client cli(HOST, PORT);
  5231. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5232. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5233. return detail::write_headers(strm, hdrs);
  5234. });
  5235. auto res = cli.Get("/hi");
  5236. EXPECT_TRUE(res);
  5237. EXPECT_EQ(StatusCode::OK_200, res->status);
  5238. auto it = res->headers.find("CustomServerHeader");
  5239. EXPECT_TRUE(it != res->headers.end());
  5240. EXPECT_EQ(it->second, "CustomServerValue");
  5241. }
  5242. }
  5243. class ServerTest : public ::testing::Test {
  5244. protected:
  5245. ServerTest()
  5246. : cli_(HOST, PORT)
  5247. #ifdef CPPHTTPLIB_SSL_ENABLED
  5248. ,
  5249. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5250. #endif
  5251. {
  5252. #ifdef CPPHTTPLIB_SSL_ENABLED
  5253. cli_.enable_server_certificate_verification(false);
  5254. #endif
  5255. // Allow LARGE_DATA (100MB) responses
  5256. cli_.set_payload_max_length(200 * 1024 * 1024);
  5257. }
  5258. virtual void SetUp() {
  5259. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5260. svr_.set_payload_max_length(200 * 1024 * 1024);
  5261. svr_.set_mount_point("/", "./www");
  5262. svr_.set_mount_point("/mount", "./www2");
  5263. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5264. svr_.Get("/hi",
  5265. [&](const Request & /*req*/, Response &res) {
  5266. res.set_content("Hello World!", "text/plain");
  5267. })
  5268. .Get("/file_content",
  5269. [&](const Request & /*req*/, Response &res) {
  5270. res.set_file_content("./www/dir/test.html");
  5271. })
  5272. .Get("/file_content_with_content_type",
  5273. [&](const Request & /*req*/, Response &res) {
  5274. res.set_file_content("./www/file", "text/plain");
  5275. })
  5276. .Get("/invalid_file_content",
  5277. [&](const Request & /*req*/, Response &res) {
  5278. res.set_file_content("./www/dir/invalid_file_path");
  5279. })
  5280. .Get("/http_response_splitting",
  5281. [&](const Request & /*req*/, Response &res) {
  5282. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5283. EXPECT_EQ(0U, res.headers.size());
  5284. EXPECT_FALSE(res.has_header("a"));
  5285. res.set_header("a", "1\nSet-Cookie: a=1");
  5286. EXPECT_EQ(0U, res.headers.size());
  5287. EXPECT_FALSE(res.has_header("a"));
  5288. res.set_header("a", "1\rSet-Cookie: a=1");
  5289. EXPECT_EQ(0U, res.headers.size());
  5290. EXPECT_FALSE(res.has_header("a"));
  5291. res.set_header("a\r\nb", "0");
  5292. EXPECT_EQ(0U, res.headers.size());
  5293. EXPECT_FALSE(res.has_header("a"));
  5294. res.set_header("a\rb", "0");
  5295. EXPECT_EQ(0U, res.headers.size());
  5296. EXPECT_FALSE(res.has_header("a"));
  5297. res.set_header("a\nb", "0");
  5298. EXPECT_EQ(0U, res.headers.size());
  5299. EXPECT_FALSE(res.has_header("a"));
  5300. res.set_redirect("1\r\nSet-Cookie: a=1");
  5301. EXPECT_EQ(0U, res.headers.size());
  5302. EXPECT_FALSE(res.has_header("Location"));
  5303. })
  5304. .Get("/slow",
  5305. [&](const Request & /*req*/, Response &res) {
  5306. std::this_thread::sleep_for(std::chrono::seconds(4));
  5307. res.set_content("slow", "text/plain");
  5308. })
  5309. #if 0
  5310. .Post("/slowpost",
  5311. [&](const Request & /*req*/, Response &res) {
  5312. std::this_thread::sleep_for(std::chrono::seconds(2));
  5313. res.set_content("slow", "text/plain");
  5314. })
  5315. #endif
  5316. .Get("/remote_addr",
  5317. [&](const Request &req, Response &res) {
  5318. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5319. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5320. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5321. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5322. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5323. #endif
  5324. res.set_content(req.remote_addr, "text/plain");
  5325. })
  5326. .Get("/local_addr",
  5327. [&](const Request &req, Response &res) {
  5328. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5329. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5330. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5331. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5332. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5333. #endif
  5334. auto local_addr = req.local_addr;
  5335. auto local_port = std::to_string(req.local_port);
  5336. res.set_content(local_addr.append(":").append(local_port),
  5337. "text/plain");
  5338. })
  5339. .Get("/endwith%",
  5340. [&](const Request & /*req*/, Response &res) {
  5341. res.set_content("Hello World!", "text/plain");
  5342. })
  5343. .Get("/a\\+\\+b",
  5344. [&](const Request &req, Response &res) {
  5345. ASSERT_TRUE(req.has_param("a +b"));
  5346. auto val = req.get_param_value("a +b");
  5347. res.set_content(val, "text/plain");
  5348. })
  5349. .Get("/", [&](const Request & /*req*/,
  5350. Response &res) { res.set_redirect("/hi"); })
  5351. .Post("/1",
  5352. [](const Request & /*req*/, Response &res) {
  5353. res.set_redirect("/2", StatusCode::SeeOther_303);
  5354. })
  5355. .Get("/2",
  5356. [](const Request & /*req*/, Response &res) {
  5357. res.set_content("redirected.", "text/plain");
  5358. res.status = StatusCode::OK_200;
  5359. })
  5360. .Post("/person",
  5361. [&](const Request &req, Response &res) {
  5362. if (req.has_param("name") && req.has_param("note")) {
  5363. persons_[req.get_param_value("name")] =
  5364. req.get_param_value("note");
  5365. } else {
  5366. res.status = StatusCode::BadRequest_400;
  5367. }
  5368. })
  5369. .Put("/person",
  5370. [&](const Request &req, Response &res) {
  5371. if (req.has_param("name") && req.has_param("note")) {
  5372. persons_[req.get_param_value("name")] =
  5373. req.get_param_value("note");
  5374. } else {
  5375. res.status = StatusCode::BadRequest_400;
  5376. }
  5377. })
  5378. .Get("/person/(.*)",
  5379. [&](const Request &req, Response &res) {
  5380. string name = req.matches[1];
  5381. if (persons_.find(name) != persons_.end()) {
  5382. auto note = persons_[name];
  5383. res.set_content(note, "text/plain");
  5384. } else {
  5385. res.status = StatusCode::NotFound_404;
  5386. }
  5387. })
  5388. .Delete("/person",
  5389. [&](const Request &req, Response &res) {
  5390. if (req.has_param("name")) {
  5391. string name = req.get_param_value("name");
  5392. if (persons_.find(name) != persons_.end()) {
  5393. persons_.erase(name);
  5394. res.set_content("DELETED", "text/plain");
  5395. } else {
  5396. res.status = StatusCode::NotFound_404;
  5397. }
  5398. } else {
  5399. res.status = StatusCode::BadRequest_400;
  5400. }
  5401. })
  5402. .Post("/x-www-form-urlencoded-json",
  5403. [&](const Request &req, Response &res) {
  5404. auto json = req.get_param_value("json");
  5405. ASSERT_EQ(JSON_DATA, json);
  5406. res.set_content(json, "appliation/json");
  5407. res.status = StatusCode::OK_200;
  5408. })
  5409. .Get("/streamed-chunked",
  5410. [&](const Request & /*req*/, Response &res) {
  5411. res.set_chunked_content_provider(
  5412. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5413. sink.os << "123";
  5414. sink.os << "456";
  5415. sink.os << "789";
  5416. sink.done();
  5417. return true;
  5418. });
  5419. })
  5420. .Get("/streamed-chunked-with-prohibited-trailer",
  5421. [&](const Request & /*req*/, Response &res) {
  5422. auto i = new int(0);
  5423. // Declare both a prohibited trailer (Content-Length) and an
  5424. // allowed one
  5425. res.set_header("Trailer", "Content-Length, X-Allowed");
  5426. res.set_chunked_content_provider(
  5427. "text/plain",
  5428. [i](size_t /*offset*/, DataSink &sink) {
  5429. switch (*i) {
  5430. case 0: sink.os << "123"; break;
  5431. case 1: sink.os << "456"; break;
  5432. case 2: sink.os << "789"; break;
  5433. case 3: {
  5434. sink.done_with_trailer(
  5435. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5436. } break;
  5437. }
  5438. (*i)++;
  5439. return true;
  5440. },
  5441. [i](bool success) {
  5442. EXPECT_TRUE(success);
  5443. delete i;
  5444. });
  5445. })
  5446. .Get("/streamed-chunked2",
  5447. [&](const Request & /*req*/, Response &res) {
  5448. auto i = new int(0);
  5449. res.set_chunked_content_provider(
  5450. "text/plain",
  5451. [i](size_t /*offset*/, DataSink &sink) {
  5452. switch (*i) {
  5453. case 0: sink.os << "123"; break;
  5454. case 1: sink.os << "456"; break;
  5455. case 2: sink.os << "789"; break;
  5456. case 3: sink.done(); break;
  5457. }
  5458. (*i)++;
  5459. return true;
  5460. },
  5461. [i](bool success) {
  5462. EXPECT_TRUE(success);
  5463. delete i;
  5464. });
  5465. })
  5466. .Get("/streamed-chunked-with-trailer",
  5467. [&](const Request & /*req*/, Response &res) {
  5468. auto i = new int(0);
  5469. res.set_header("Trailer", "Dummy1, Dummy2");
  5470. res.set_chunked_content_provider(
  5471. "text/plain",
  5472. [i](size_t /*offset*/, DataSink &sink) {
  5473. switch (*i) {
  5474. case 0: sink.os << "123"; break;
  5475. case 1: sink.os << "456"; break;
  5476. case 2: sink.os << "789"; break;
  5477. case 3: {
  5478. sink.done_with_trailer(
  5479. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5480. } break;
  5481. }
  5482. (*i)++;
  5483. return true;
  5484. },
  5485. [i](bool success) {
  5486. EXPECT_TRUE(success);
  5487. delete i;
  5488. });
  5489. })
  5490. .Get("/streamed",
  5491. [&](const Request & /*req*/, Response &res) {
  5492. res.set_content_provider(
  5493. 6, "text/plain",
  5494. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5495. sink.os << (offset < 3 ? "a" : "b");
  5496. return true;
  5497. });
  5498. })
  5499. .Get("/streamed-without-length",
  5500. [&](const Request & /*req*/, Response &res) {
  5501. auto data = new std::string("abcdefg");
  5502. res.set_content_provider(
  5503. "text/plain",
  5504. [data](size_t offset, DataSink &sink) {
  5505. if (offset < data->size()) {
  5506. sink.os << data->substr(offset);
  5507. }
  5508. sink.done();
  5509. return true;
  5510. },
  5511. [data](bool success) {
  5512. EXPECT_TRUE(success);
  5513. delete data;
  5514. });
  5515. })
  5516. .Get("/streamed-with-range",
  5517. [&](const Request &req, Response &res) {
  5518. auto data = new std::string("abcdefg");
  5519. // An explicit status keeps the server from picking the 206 it
  5520. // would otherwise choose for a ranged request, so the response
  5521. // is not a partial representation.
  5522. auto status = req.get_param_value("status");
  5523. if (status == "200") {
  5524. res.status = StatusCode::OK_200;
  5525. } else if (status == "403") {
  5526. res.status = StatusCode::Forbidden_403;
  5527. }
  5528. res.set_content_provider(
  5529. data->size(), "text/plain",
  5530. [data](size_t offset, size_t length, DataSink &sink) {
  5531. size_t DATA_CHUNK_SIZE = 4;
  5532. const auto &d = *data;
  5533. auto out_len =
  5534. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5535. auto ret =
  5536. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5537. EXPECT_TRUE(ret);
  5538. return true;
  5539. },
  5540. [data, &req](bool success) {
  5541. EXPECT_EQ(success, !req.has_param("error"));
  5542. delete data;
  5543. });
  5544. })
  5545. .Get("/streamed-cancel",
  5546. [&](const Request & /*req*/, Response &res) {
  5547. res.set_content_provider(
  5548. size_t(-1), "text/plain",
  5549. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5550. sink.os << "data_chunk";
  5551. return true;
  5552. });
  5553. })
  5554. .Get("/regex-with-delimiter",
  5555. [&](const Request &req, Response & /*res*/) {
  5556. ASSERT_TRUE(req.has_param("key"));
  5557. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5558. })
  5559. .Get("/with-range",
  5560. [&](const Request & /*req*/, Response &res) {
  5561. res.set_content("abcdefg", "text/plain");
  5562. })
  5563. .Get("/test-start-time",
  5564. [&](const Request &req, Response & /*res*/) {
  5565. EXPECT_NE(req.start_time_,
  5566. std::chrono::steady_clock::time_point::min());
  5567. })
  5568. .Get("/with-range-customized-response",
  5569. [&](const Request & /*req*/, Response &res) {
  5570. res.status = StatusCode::BadRequest_400;
  5571. res.set_content(JSON_DATA, "application/json");
  5572. })
  5573. .Post("/chunked",
  5574. [&](const Request &req, Response & /*res*/) {
  5575. EXPECT_EQ(req.body, "dechunked post body");
  5576. })
  5577. .Post("/large-chunked",
  5578. [&](const Request &req, Response & /*res*/) {
  5579. std::string expected(6 * 30 * 1024u, 'a');
  5580. EXPECT_EQ(req.body, expected);
  5581. })
  5582. .Post("/multipart",
  5583. [&](const Request &req, Response & /*res*/) {
  5584. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5585. req.form.get_field_count("text2") +
  5586. req.form.get_field_count("file3") +
  5587. req.form.get_field_count("file4"));
  5588. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5589. req.form.get_file_count("file2"));
  5590. ASSERT_TRUE(!req.form.has_file("???"));
  5591. ASSERT_TRUE(!req.form.has_field("???"));
  5592. ASSERT_TRUE(req.body.empty());
  5593. {
  5594. const auto &text = req.form.get_field("text1");
  5595. EXPECT_EQ("text default", text);
  5596. }
  5597. {
  5598. const auto &text = req.form.get_field("text2");
  5599. EXPECT_EQ("aωb", text);
  5600. }
  5601. {
  5602. const auto &file = req.form.get_file("file1");
  5603. EXPECT_EQ("hello.txt", file.filename);
  5604. EXPECT_EQ("text/plain", file.content_type);
  5605. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5606. }
  5607. {
  5608. const auto &file = req.form.get_file("file2");
  5609. EXPECT_EQ("world.json", file.filename);
  5610. EXPECT_EQ("application/json", file.content_type);
  5611. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5612. }
  5613. {
  5614. const auto &text = req.form.get_field("file3");
  5615. EXPECT_EQ(0u, text.size());
  5616. }
  5617. {
  5618. const auto &text = req.form.get_field("file4");
  5619. EXPECT_EQ(0u, text.size());
  5620. }
  5621. })
  5622. .Post("/multipart/multi_file_values",
  5623. [&](const Request &req, Response & /*res*/) {
  5624. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5625. req.form.get_field_count("multi_text1"));
  5626. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5627. ASSERT_TRUE(!req.form.has_file("???"));
  5628. ASSERT_TRUE(!req.form.has_field("???"));
  5629. ASSERT_TRUE(req.body.empty());
  5630. {
  5631. const auto &text = req.form.get_field("text");
  5632. EXPECT_EQ("default text", text);
  5633. }
  5634. {
  5635. const auto &text1_values = req.form.get_fields("multi_text1");
  5636. EXPECT_EQ(2u, text1_values.size());
  5637. EXPECT_EQ("aaaaa", text1_values[0]);
  5638. EXPECT_EQ("bbbbb", text1_values[1]);
  5639. }
  5640. {
  5641. const auto &file1_values = req.form.get_files("multi_file1");
  5642. EXPECT_EQ(2u, file1_values.size());
  5643. auto file1 = file1_values[0];
  5644. EXPECT_EQ(file1.filename, "hello.txt");
  5645. EXPECT_EQ(file1.content_type, "text/plain");
  5646. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5647. auto file2 = file1_values[1];
  5648. EXPECT_EQ(file2.filename, "world.json");
  5649. EXPECT_EQ(file2.content_type, "application/json");
  5650. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5651. }
  5652. })
  5653. .Post("/empty",
  5654. [&](const Request &req, Response &res) {
  5655. EXPECT_EQ(req.body, "");
  5656. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5657. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5658. res.set_content("empty", "text/plain");
  5659. })
  5660. .Post("/empty-no-content-type",
  5661. [&](const Request &req, Response &res) {
  5662. EXPECT_EQ(req.body, "");
  5663. EXPECT_FALSE(req.has_header("Content-Type"));
  5664. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5665. res.set_content("empty-no-content-type", "text/plain");
  5666. })
  5667. .Post("/path-only",
  5668. [&](const Request &req, Response &res) {
  5669. EXPECT_EQ(req.body, "");
  5670. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5671. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5672. res.set_content("path-only", "text/plain");
  5673. })
  5674. .Post("/path-headers-only",
  5675. [&](const Request &req, Response &res) {
  5676. EXPECT_EQ(req.body, "");
  5677. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5678. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5679. EXPECT_EQ("world", req.get_header_value("hello"));
  5680. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5681. res.set_content("path-headers-only", "text/plain");
  5682. })
  5683. .Post("/post-large",
  5684. [&](const Request &req, Response &res) {
  5685. EXPECT_EQ(req.body, LARGE_DATA);
  5686. res.set_content(req.body, "text/plain");
  5687. })
  5688. .Post("/post-loopback",
  5689. [&](const Request &, Response &res,
  5690. ContentReader const &content_reader) {
  5691. std::string body;
  5692. content_reader([&](const char *data, size_t data_length) {
  5693. body.append(data, data_length);
  5694. return true;
  5695. });
  5696. res.set_content(body, "text/plain");
  5697. })
  5698. .Put("/put-loopback",
  5699. [&](const Request &, Response &res,
  5700. ContentReader const &content_reader) {
  5701. std::string body;
  5702. content_reader([&](const char *data, size_t data_length) {
  5703. body.append(data, data_length);
  5704. return true;
  5705. });
  5706. res.set_content(body, "text/plain");
  5707. })
  5708. .Patch("/patch-loopback",
  5709. [&](const Request &, Response &res,
  5710. ContentReader const &content_reader) {
  5711. std::string body;
  5712. content_reader([&](const char *data, size_t data_length) {
  5713. body.append(data, data_length);
  5714. return true;
  5715. });
  5716. res.set_content(body, "text/plain");
  5717. })
  5718. .Put("/empty-no-content-type",
  5719. [&](const Request &req, Response &res) {
  5720. EXPECT_EQ(req.body, "");
  5721. EXPECT_FALSE(req.has_header("Content-Type"));
  5722. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5723. res.set_content("empty-no-content-type", "text/plain");
  5724. })
  5725. .Put("/put",
  5726. [&](const Request &req, Response &res) {
  5727. EXPECT_EQ(req.body, "PUT");
  5728. res.set_content(req.body, "text/plain");
  5729. })
  5730. .Put("/put-large",
  5731. [&](const Request &req, Response &res) {
  5732. EXPECT_EQ(req.body, LARGE_DATA);
  5733. res.set_content(req.body, "text/plain");
  5734. })
  5735. .Patch("/patch",
  5736. [&](const Request &req, Response &res) {
  5737. EXPECT_EQ(req.body, "PATCH");
  5738. res.set_content(req.body, "text/plain");
  5739. })
  5740. .Delete("/delete",
  5741. [&](const Request & /*req*/, Response &res) {
  5742. res.set_content("DELETE", "text/plain");
  5743. })
  5744. .Delete("/delete-body",
  5745. [&](const Request &req, Response &res) {
  5746. EXPECT_EQ(req.body, "content");
  5747. res.set_content(req.body, "text/plain");
  5748. })
  5749. .Options(R"(\*)",
  5750. [&](const Request & /*req*/, Response &res) {
  5751. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5752. })
  5753. .CustomRoute("PROPFIND", "/dav/:id",
  5754. [&](const Request &req, Response &res) {
  5755. res.set_header("x-body-size",
  5756. std::to_string(req.body.size()));
  5757. res.set_header("x-matched-route", req.matched_route);
  5758. res.set_header("x-dav-id", req.path_params.at("id"));
  5759. res.status = StatusCode::MultiStatus_207;
  5760. res.set_content(req.body, "application/xml");
  5761. })
  5762. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5763. [&](const Request &req, Response &res) {
  5764. res.set_header("x-dav-match", req.matches[1]);
  5765. res.status = StatusCode::MultiStatus_207;
  5766. })
  5767. .CustomRoute("MKCOL", "/dav-mkcol",
  5768. [&](const Request &req, Response &res) {
  5769. EXPECT_TRUE(req.body.empty());
  5770. res.status = StatusCode::Created_201;
  5771. })
  5772. .CustomRoute(
  5773. "REPORT", "/dav-report",
  5774. [&](const Request & /*req*/, Response &res,
  5775. const ContentReader &content_reader) {
  5776. std::string body;
  5777. content_reader([&](const char *data, size_t data_length) {
  5778. body.append(data, data_length);
  5779. return true;
  5780. });
  5781. res.set_header("x-body-size", std::to_string(body.size()));
  5782. res.status = StatusCode::MultiStatus_207;
  5783. res.set_content(body, "application/xml");
  5784. })
  5785. .Get("/request-target",
  5786. [&](const Request &req, Response & /*res*/) {
  5787. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5788. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5789. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5790. })
  5791. .Get("/long-query-value",
  5792. [&](const Request &req, Response & /*res*/) {
  5793. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5794. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5795. })
  5796. .Get("/too-long-query-value",
  5797. [&](const Request &req, Response & /*res*/) {
  5798. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5799. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5800. })
  5801. .Get("/array-param",
  5802. [&](const Request &req, Response & /*res*/) {
  5803. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5804. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5805. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5806. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5807. })
  5808. .Get("/array-param-values",
  5809. [&](const Request &req, Response & /*res*/) {
  5810. auto values = req.get_param_values("array");
  5811. EXPECT_EQ(3u, values.size());
  5812. EXPECT_EQ("value1", values[0]);
  5813. EXPECT_EQ("value2", values[1]);
  5814. EXPECT_EQ("value3", values[2]);
  5815. auto empty = req.get_param_values("nonexistent");
  5816. EXPECT_TRUE(empty.empty());
  5817. })
  5818. .Post("/validate-no-multiple-headers",
  5819. [&](const Request &req, Response & /*res*/) {
  5820. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5821. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5822. })
  5823. .Post("/content_receiver",
  5824. [&](const Request &req, Response &res,
  5825. const ContentReader &content_reader) {
  5826. if (req.is_multipart_form_data()) {
  5827. std::vector<FormData> items;
  5828. content_reader(
  5829. [&](const FormData &file) {
  5830. items.push_back(file);
  5831. return true;
  5832. },
  5833. [&](const char *data, size_t data_length) {
  5834. items.back().content.append(data, data_length);
  5835. return true;
  5836. });
  5837. EXPECT_EQ(5u, items.size());
  5838. {
  5839. const auto &file = get_file_value(items, "text1");
  5840. EXPECT_TRUE(file.filename.empty());
  5841. EXPECT_EQ("text default", file.content);
  5842. }
  5843. {
  5844. const auto &file = get_file_value(items, "text2");
  5845. EXPECT_TRUE(file.filename.empty());
  5846. EXPECT_EQ("aωb", file.content);
  5847. }
  5848. {
  5849. const auto &file = get_file_value(items, "file1");
  5850. EXPECT_EQ("hello.txt", file.filename);
  5851. EXPECT_EQ("text/plain", file.content_type);
  5852. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5853. }
  5854. {
  5855. const auto &file = get_file_value(items, "file2");
  5856. EXPECT_EQ("world.json", file.filename);
  5857. EXPECT_EQ("application/json", file.content_type);
  5858. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5859. }
  5860. {
  5861. const auto &file = get_file_value(items, "file3");
  5862. EXPECT_TRUE(file.filename.empty());
  5863. EXPECT_EQ("application/octet-stream", file.content_type);
  5864. EXPECT_EQ(0u, file.content.size());
  5865. }
  5866. } else {
  5867. std::string body;
  5868. content_reader([&](const char *data, size_t data_length) {
  5869. EXPECT_EQ(7U, data_length);
  5870. body.append(data, data_length);
  5871. return true;
  5872. });
  5873. EXPECT_EQ(body, "content");
  5874. res.set_content(body, "text/plain");
  5875. }
  5876. })
  5877. .Put("/content_receiver",
  5878. [&](const Request & /*req*/, Response &res,
  5879. const ContentReader &content_reader) {
  5880. std::string body;
  5881. content_reader([&](const char *data, size_t data_length) {
  5882. body.append(data, data_length);
  5883. return true;
  5884. });
  5885. EXPECT_EQ(body, "content");
  5886. res.set_content(body, "text/plain");
  5887. })
  5888. .Patch("/content_receiver",
  5889. [&](const Request & /*req*/, Response &res,
  5890. const ContentReader &content_reader) {
  5891. std::string body;
  5892. content_reader([&](const char *data, size_t data_length) {
  5893. body.append(data, data_length);
  5894. return true;
  5895. });
  5896. EXPECT_EQ(body, "content");
  5897. res.set_content(body, "text/plain");
  5898. })
  5899. .Post("/query-string-and-body",
  5900. [&](const Request &req, Response & /*res*/) {
  5901. ASSERT_TRUE(req.has_param("key"));
  5902. EXPECT_EQ(req.get_param_value("key"), "value");
  5903. EXPECT_EQ(req.body, "content");
  5904. })
  5905. .Get("/last-request",
  5906. [&](const Request &req, Response & /*res*/) {
  5907. EXPECT_EQ("close", req.get_header_value("Connection"));
  5908. })
  5909. .Get(R"(/redirect/(\d+))",
  5910. [&](const Request &req, Response &res) {
  5911. auto num = std::stoi(req.matches[1]) + 1;
  5912. std::string url = "/redirect/" + std::to_string(num);
  5913. res.set_redirect(url);
  5914. })
  5915. .Post("/binary",
  5916. [&](const Request &req, Response &res) {
  5917. EXPECT_EQ(4U, req.body.size());
  5918. EXPECT_EQ("application/octet-stream",
  5919. req.get_header_value("Content-Type"));
  5920. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5921. res.set_content(req.body, "application/octet-stream");
  5922. })
  5923. .Put("/binary",
  5924. [&](const Request &req, Response &res) {
  5925. EXPECT_EQ(4U, req.body.size());
  5926. EXPECT_EQ("application/octet-stream",
  5927. req.get_header_value("Content-Type"));
  5928. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5929. res.set_content(req.body, "application/octet-stream");
  5930. })
  5931. .Patch("/binary",
  5932. [&](const Request &req, Response &res) {
  5933. EXPECT_EQ(4U, req.body.size());
  5934. EXPECT_EQ("application/octet-stream",
  5935. req.get_header_value("Content-Type"));
  5936. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5937. res.set_content(req.body, "application/octet-stream");
  5938. })
  5939. .Delete("/binary",
  5940. [&](const Request &req, Response &res) {
  5941. EXPECT_EQ(4U, req.body.size());
  5942. EXPECT_EQ("application/octet-stream",
  5943. req.get_header_value("Content-Type"));
  5944. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5945. res.set_content(req.body, "application/octet-stream");
  5946. })
  5947. .Get("/issue1772",
  5948. [&](const Request & /*req*/, Response &res) {
  5949. res.status = 401;
  5950. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5951. })
  5952. .Delete("/issue609",
  5953. [](const httplib::Request &, httplib::Response &res,
  5954. const httplib::ContentReader &) {
  5955. res.set_content("ok", "text/plain");
  5956. })
  5957. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5958. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5959. .Get("/compress",
  5960. [&](const Request & /*req*/, Response &res) {
  5961. res.set_content(
  5962. "12345678901234567890123456789012345678901234567890123456789"
  5963. "01234567890123456789012345678901234567890",
  5964. "text/plain");
  5965. })
  5966. .Get("/compress-with-charset",
  5967. [&](const Request & /*req*/, Response &res) {
  5968. res.set_content(
  5969. "12345678901234567890123456789012345678901234567890123456789"
  5970. "01234567890123456789012345678901234567890",
  5971. "application/json; charset=utf-8");
  5972. })
  5973. .Get("/nocompress",
  5974. [&](const Request & /*req*/, Response &res) {
  5975. res.set_content(
  5976. "12345678901234567890123456789012345678901234567890123456789"
  5977. "01234567890123456789012345678901234567890",
  5978. "application/octet-stream");
  5979. })
  5980. .Post("/compress-multipart",
  5981. [&](const Request &req, Response & /*res*/) {
  5982. EXPECT_EQ(2u, req.form.fields.size());
  5983. ASSERT_TRUE(!req.form.has_field("???"));
  5984. {
  5985. const auto &text = req.form.get_field("key1");
  5986. EXPECT_EQ("test", text);
  5987. }
  5988. {
  5989. const auto &text = req.form.get_field("key2");
  5990. EXPECT_EQ("--abcdefg123", text);
  5991. }
  5992. })
  5993. #endif
  5994. ;
  5995. persons_["john"] = "programmer";
  5996. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5997. svr_.wait_until_ready();
  5998. }
  5999. virtual void TearDown() {
  6000. svr_.stop();
  6001. if (!request_threads_.empty()) {
  6002. std::this_thread::sleep_for(std::chrono::seconds(1));
  6003. for (auto &t : request_threads_) {
  6004. t.join();
  6005. }
  6006. }
  6007. t_.join();
  6008. }
  6009. map<string, string> persons_;
  6010. #ifdef CPPHTTPLIB_SSL_ENABLED
  6011. SSLClient cli_;
  6012. SSLServer svr_;
  6013. #else
  6014. Client cli_;
  6015. Server svr_;
  6016. #endif
  6017. thread t_;
  6018. std::vector<thread> request_threads_;
  6019. };
  6020. TEST_F(ServerTest, GetMethod200) {
  6021. auto res = cli_.Get("/hi");
  6022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6023. EXPECT_EQ("HTTP/1.1", res->version);
  6024. EXPECT_EQ(StatusCode::OK_200, res->status);
  6025. EXPECT_EQ("OK", res->reason);
  6026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6027. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6028. EXPECT_EQ("Hello World!", res->body);
  6029. }
  6030. TEST_F(ServerTest, GetEmptyFile) {
  6031. auto res = cli_.Get("/empty_file");
  6032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6033. EXPECT_EQ(StatusCode::OK_200, res->status);
  6034. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6035. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6036. EXPECT_EQ("", res->body);
  6037. }
  6038. TEST_F(ServerTest, GetFileContent) {
  6039. auto res = cli_.Get("/file_content");
  6040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6041. EXPECT_EQ(StatusCode::OK_200, res->status);
  6042. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6043. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6044. EXPECT_EQ("test.html", res->body);
  6045. }
  6046. TEST_F(ServerTest, GetFileContentWithRange) {
  6047. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6050. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6051. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6052. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6053. EXPECT_EQ("est", res->body);
  6054. }
  6055. TEST_F(ServerTest, GetFileContentWithContentType) {
  6056. auto res = cli_.Get("/file_content_with_content_type");
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. EXPECT_EQ(StatusCode::OK_200, res->status);
  6059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6060. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6061. EXPECT_EQ("file\n", res->body);
  6062. }
  6063. TEST_F(ServerTest, GetInvalidFileContent) {
  6064. auto res = cli_.Get("/invalid_file_content");
  6065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6066. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6067. }
  6068. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6069. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. EXPECT_EQ("HTTP/1.1", res->version);
  6072. EXPECT_EQ(StatusCode::OK_200, res->status);
  6073. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6074. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6075. EXPECT_EQ("Hello World!", res->body);
  6076. }
  6077. TEST_F(ServerTest, GetMethod302) {
  6078. auto res = cli_.Get("/");
  6079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6080. EXPECT_EQ(StatusCode::Found_302, res->status);
  6081. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6082. }
  6083. TEST_F(ServerTest, GetMethod302Redirect) {
  6084. cli_.set_follow_location(true);
  6085. auto res = cli_.Get("/");
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::OK_200, res->status);
  6088. EXPECT_EQ("Hello World!", res->body);
  6089. EXPECT_EQ("/hi", res->location);
  6090. }
  6091. TEST_F(ServerTest, GetMethod404) {
  6092. auto res = cli_.Get("/invalid");
  6093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6094. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6095. }
  6096. TEST_F(ServerTest, HeadMethod200) {
  6097. auto res = cli_.Head("/hi");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6101. EXPECT_TRUE(res->body.empty());
  6102. }
  6103. TEST_F(ServerTest, HeadMethod200Static) {
  6104. auto res = cli_.Head("/mount/dir/index.html");
  6105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6108. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6109. EXPECT_TRUE(res->body.empty());
  6110. }
  6111. TEST_F(ServerTest, HeadMethod404) {
  6112. auto res = cli_.Head("/invalid");
  6113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6114. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6115. EXPECT_TRUE(res->body.empty());
  6116. }
  6117. TEST_F(ServerTest, GetMethodPersonJohn) {
  6118. auto res = cli_.Get("/person/john");
  6119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6120. EXPECT_EQ(StatusCode::OK_200, res->status);
  6121. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6122. EXPECT_EQ("programmer", res->body);
  6123. }
  6124. TEST_F(ServerTest, PostMethod1) {
  6125. auto res = cli_.Get("/person/john1");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6128. res = cli_.Post("/person", "name=john1&note=coder",
  6129. "application/x-www-form-urlencoded");
  6130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6131. ASSERT_EQ(StatusCode::OK_200, res->status);
  6132. res = cli_.Get("/person/john1");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. ASSERT_EQ(StatusCode::OK_200, res->status);
  6135. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6136. ASSERT_EQ("coder", res->body);
  6137. }
  6138. TEST_F(ServerTest, PostMethod2) {
  6139. auto res = cli_.Get("/person/john2");
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6142. Params params;
  6143. params.emplace("name", "john2");
  6144. params.emplace("note", "coder");
  6145. res = cli_.Post("/person", params);
  6146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6147. ASSERT_EQ(StatusCode::OK_200, res->status);
  6148. res = cli_.Get("/person/john2");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. ASSERT_EQ(StatusCode::OK_200, res->status);
  6151. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6152. ASSERT_EQ("coder", res->body);
  6153. }
  6154. TEST_F(ServerTest, PutMethod3) {
  6155. auto res = cli_.Get("/person/john3");
  6156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6157. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6158. Params params;
  6159. params.emplace("name", "john3");
  6160. params.emplace("note", "coder");
  6161. res = cli_.Put("/person", params);
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. ASSERT_EQ(StatusCode::OK_200, res->status);
  6164. res = cli_.Get("/person/john3");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. ASSERT_EQ(StatusCode::OK_200, res->status);
  6167. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6168. ASSERT_EQ("coder", res->body);
  6169. }
  6170. TEST_F(ServerTest, DeleteMethod1) {
  6171. auto res = cli_.Get("/person/john4");
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6174. Params params;
  6175. params.emplace("name", "john4");
  6176. params.emplace("note", "coder");
  6177. res = cli_.Post("/person", params);
  6178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6179. ASSERT_EQ(StatusCode::OK_200, res->status);
  6180. res = cli_.Get("/person/john4");
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. ASSERT_EQ(StatusCode::OK_200, res->status);
  6183. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6184. ASSERT_EQ("coder", res->body);
  6185. Params delete_params;
  6186. delete_params.emplace("name", "john4");
  6187. res = cli_.Delete("/person", delete_params);
  6188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6189. ASSERT_EQ(StatusCode::OK_200, res->status);
  6190. ASSERT_EQ("DELETED", res->body);
  6191. res = cli_.Get("/person/john4");
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6194. }
  6195. TEST_F(ServerTest, DeleteMethod2) {
  6196. auto res = cli_.Get("/person/john5");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6199. Params params;
  6200. params.emplace("name", "john5");
  6201. params.emplace("note", "developer");
  6202. res = cli_.Post("/person", params);
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. ASSERT_EQ(StatusCode::OK_200, res->status);
  6205. res = cli_.Get("/person/john5");
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. ASSERT_EQ(StatusCode::OK_200, res->status);
  6208. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6209. ASSERT_EQ("developer", res->body);
  6210. Params delete_params;
  6211. delete_params.emplace("name", "john5");
  6212. Headers headers;
  6213. headers.emplace("Custom-Header", "test-value");
  6214. res = cli_.Delete("/person", headers, delete_params);
  6215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6216. ASSERT_EQ(StatusCode::OK_200, res->status);
  6217. ASSERT_EQ("DELETED", res->body);
  6218. res = cli_.Get("/person/john5");
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6221. }
  6222. TEST_F(ServerTest, DeleteMethod3) {
  6223. auto res = cli_.Get("/person/john6");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6226. Params params;
  6227. params.emplace("name", "john6");
  6228. params.emplace("note", "tester");
  6229. res = cli_.Post("/person", params);
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. ASSERT_EQ(StatusCode::OK_200, res->status);
  6232. res = cli_.Get("/person/john6");
  6233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6234. ASSERT_EQ(StatusCode::OK_200, res->status);
  6235. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6236. ASSERT_EQ("tester", res->body);
  6237. Params delete_params;
  6238. delete_params.emplace("name", "john6");
  6239. Headers headers;
  6240. headers.emplace("Custom-Header", "test-value");
  6241. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. ASSERT_EQ(StatusCode::OK_200, res->status);
  6244. ASSERT_EQ("DELETED", res->body);
  6245. res = cli_.Get("/person/john6");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6248. }
  6249. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6250. Params params;
  6251. params.emplace("json", JSON_DATA);
  6252. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6254. ASSERT_EQ(StatusCode::OK_200, res->status);
  6255. ASSERT_EQ(JSON_DATA, res->body);
  6256. }
  6257. TEST_F(ServerTest, PostEmptyContent) {
  6258. auto res = cli_.Post("/empty", "", "text/plain");
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. ASSERT_EQ(StatusCode::OK_200, res->status);
  6261. ASSERT_EQ("empty", res->body);
  6262. }
  6263. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6264. auto res = cli_.Post("/empty-no-content-type");
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. ASSERT_EQ(StatusCode::OK_200, res->status);
  6267. ASSERT_EQ("empty-no-content-type", res->body);
  6268. }
  6269. TEST_F(ServerTest, PostPathOnly) {
  6270. auto res = cli_.Post("/path-only");
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. ASSERT_EQ(StatusCode::OK_200, res->status);
  6273. ASSERT_EQ("path-only", res->body);
  6274. }
  6275. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6276. auto res = cli_.Post("/path-headers-only",
  6277. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. ASSERT_EQ(StatusCode::OK_200, res->status);
  6280. ASSERT_EQ("path-headers-only", res->body);
  6281. }
  6282. TEST_F(ServerTest, PostLarge) {
  6283. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. ASSERT_EQ(StatusCode::OK_200, res->status);
  6286. EXPECT_EQ(LARGE_DATA, res->body);
  6287. }
  6288. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6289. auto res = cli_.Put("/empty-no-content-type");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. ASSERT_EQ(StatusCode::OK_200, res->status);
  6292. ASSERT_EQ("empty-no-content-type", res->body);
  6293. }
  6294. TEST_F(ServerTest, GetMethodDir) {
  6295. auto res = cli_.Get("/dir/");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. EXPECT_EQ(StatusCode::OK_200, res->status);
  6298. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6299. auto body = R"(<html>
  6300. <head>
  6301. </head>
  6302. <body>
  6303. <a href="/dir/test.html">Test</a>
  6304. <a href="/hi">hi</a>
  6305. </body>
  6306. </html>
  6307. )";
  6308. EXPECT_EQ(body, res->body);
  6309. }
  6310. TEST_F(ServerTest, GetMethodDirTest) {
  6311. auto res = cli_.Get("/dir/test.html");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6315. EXPECT_EQ("test.html", res->body);
  6316. }
  6317. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6318. auto res = cli_.Get("/dir/../dir/test.html");
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6321. }
  6322. TEST_F(ServerTest, GetMethodInvalidPath) {
  6323. auto res = cli_.Get("/dir/../test.html");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6326. }
  6327. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6328. auto res = cli_.Get("/../www/dir/test.html");
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6331. }
  6332. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6333. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6336. }
  6337. TEST_F(ServerTest, GetMethodDirMountTest) {
  6338. auto res = cli_.Get("/mount/dir/test.html");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::OK_200, res->status);
  6341. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6342. EXPECT_EQ("test.html", res->body);
  6343. }
  6344. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6345. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6347. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6348. }
  6349. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6350. auto res = cli_.Get("/mount/dir/../test.html");
  6351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6353. }
  6354. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6355. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6358. }
  6359. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6360. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6362. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6363. }
  6364. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6365. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6368. }
  6369. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6370. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6373. }
  6374. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6375. auto res = cli_.Get("/mount/dir");
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6378. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6379. }
  6380. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6381. auto res = cli_.Get("//dir");
  6382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6383. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6384. EXPECT_FALSE(res->has_header("Location"));
  6385. }
  6386. TEST_F(ServerTest, PostMethod303) {
  6387. auto res = cli_.Post("/1", "body", "text/plain");
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6390. EXPECT_EQ("/2", res->get_header_value("Location"));
  6391. }
  6392. TEST_F(ServerTest, PostMethod303Redirect) {
  6393. cli_.set_follow_location(true);
  6394. auto res = cli_.Post("/1", "body", "text/plain");
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. EXPECT_EQ(StatusCode::OK_200, res->status);
  6397. EXPECT_EQ("redirected.", res->body);
  6398. EXPECT_EQ("/2", res->location);
  6399. }
  6400. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6401. auto res = cli_.Get("/dir/test.abcde");
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::OK_200, res->status);
  6404. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6405. EXPECT_EQ("abcde", res->body);
  6406. }
  6407. TEST_F(ServerTest, StaticFileRange) {
  6408. auto res =
  6409. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6412. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6413. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6414. EXPECT_EQ(true, res->has_header("Content-Range"));
  6415. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6416. EXPECT_EQ(std::string("cd"), res->body);
  6417. }
  6418. TEST_F(ServerTest, StaticFileRanges) {
  6419. auto res = cli_.Get("/dir/test.abcde",
  6420. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6423. EXPECT_TRUE(
  6424. res->get_header_value("Content-Type")
  6425. .find(
  6426. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6427. 0);
  6428. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6429. }
  6430. TEST_F(ServerTest, StaticFileRangeHead) {
  6431. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6433. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6434. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6435. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6436. EXPECT_EQ(true, res->has_header("Content-Range"));
  6437. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6438. }
  6439. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6440. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6443. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6444. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6445. EXPECT_EQ(true, res->has_header("Content-Range"));
  6446. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6447. res->get_header_value("Content-Range"));
  6448. EXPECT_EQ("LAST\n", res->body);
  6449. }
  6450. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6451. auto res =
  6452. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6456. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6457. EXPECT_EQ(true, res->has_header("Content-Range"));
  6458. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6459. }
  6460. TEST_F(ServerTest, StaticFileBigFile) {
  6461. auto res = cli_.Get("/dir/1MB.txt");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::OK_200, res->status);
  6464. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6465. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6466. }
  6467. TEST_F(ServerTest, InvalidBaseDirMount) {
  6468. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6469. }
  6470. TEST_F(ServerTest, Binary) {
  6471. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6472. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6473. "application/octet-stream");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. ASSERT_EQ(StatusCode::OK_200, res->status);
  6476. ASSERT_EQ(4U, res->body.size());
  6477. res = cli_.Put("/binary", binary.data(), binary.size(),
  6478. "application/octet-stream");
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. ASSERT_EQ(StatusCode::OK_200, res->status);
  6481. ASSERT_EQ(4U, res->body.size());
  6482. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6483. "application/octet-stream");
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. ASSERT_EQ(StatusCode::OK_200, res->status);
  6486. ASSERT_EQ(4U, res->body.size());
  6487. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6488. "application/octet-stream");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. ASSERT_EQ(StatusCode::OK_200, res->status);
  6491. ASSERT_EQ(4U, res->body.size());
  6492. }
  6493. TEST_F(ServerTest, BinaryString) {
  6494. auto binary = std::string("\x00\x01\x02\x03", 4);
  6495. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6497. ASSERT_EQ(StatusCode::OK_200, res->status);
  6498. ASSERT_EQ(4U, res->body.size());
  6499. res = cli_.Put("/binary", binary, "application/octet-stream");
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. ASSERT_EQ(StatusCode::OK_200, res->status);
  6502. ASSERT_EQ(4U, res->body.size());
  6503. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. ASSERT_EQ(StatusCode::OK_200, res->status);
  6506. ASSERT_EQ(4U, res->body.size());
  6507. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. ASSERT_EQ(StatusCode::OK_200, res->status);
  6510. ASSERT_EQ(4U, res->body.size());
  6511. }
  6512. TEST_F(ServerTest, EmptyRequest) {
  6513. auto res = cli_.Get("");
  6514. ASSERT_TRUE(!res);
  6515. EXPECT_EQ(Error::Connection, res.error());
  6516. }
  6517. TEST_F(ServerTest, LongRequest) {
  6518. std::string request;
  6519. for (size_t i = 0; i < 545; i++) {
  6520. request += "/TooLongRequest";
  6521. }
  6522. request += "OK";
  6523. auto res = cli_.Get(request.c_str());
  6524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6526. }
  6527. TEST_F(ServerTest, TooLongRequest) {
  6528. std::string request;
  6529. for (size_t i = 0; i < 546; i++) {
  6530. request += "/TooLongRequest";
  6531. }
  6532. request += "_NG";
  6533. auto start = std::chrono::high_resolution_clock::now();
  6534. cli_.set_keep_alive(true);
  6535. auto res = cli_.Get(request.c_str());
  6536. auto end = std::chrono::high_resolution_clock::now();
  6537. auto elapsed =
  6538. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6539. .count();
  6540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6541. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6542. EXPECT_LE(elapsed, 1000);
  6543. EXPECT_EQ("close", res->get_header_value("Connection"));
  6544. EXPECT_FALSE(cli_.is_socket_open());
  6545. }
  6546. TEST_F(ServerTest, AlmostTooLongRequest) {
  6547. // test for #2046 - URI length check shouldn't include other content on req
  6548. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6549. // leading /, space, HTTP/1.1)
  6550. std::string request =
  6551. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6552. auto res = cli_.Get(request.c_str());
  6553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6554. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6555. }
  6556. TEST_F(ServerTest, LongHeader) {
  6557. Request req;
  6558. req.method = "GET";
  6559. req.path = "/hi";
  6560. std::string host_and_port;
  6561. host_and_port += HOST;
  6562. host_and_port += ":";
  6563. host_and_port += std::to_string(PORT);
  6564. req.headers.emplace("Host", host_and_port.c_str());
  6565. req.headers.emplace("Accept", "*/*");
  6566. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6567. req.headers.emplace(
  6568. "Header-Name",
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6594. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6595. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6596. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6597. "@@@@@@@@@@@@@@@@");
  6598. auto res = std::make_shared<Response>();
  6599. auto error = Error::Success;
  6600. auto ret = cli_.send(req, *res, error);
  6601. ASSERT_TRUE(ret);
  6602. EXPECT_EQ(StatusCode::OK_200, res->status);
  6603. }
  6604. TEST_F(ServerTest, LongQueryValue) {
  6605. auto start = std::chrono::high_resolution_clock::now();
  6606. cli_.set_keep_alive(true);
  6607. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6608. auto end = std::chrono::high_resolution_clock::now();
  6609. auto elapsed =
  6610. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6611. .count();
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6614. EXPECT_LE(elapsed, 1000);
  6615. EXPECT_EQ("close", res->get_header_value("Connection"));
  6616. EXPECT_FALSE(cli_.is_socket_open());
  6617. }
  6618. TEST_F(ServerTest, TooLongQueryValue) {
  6619. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6620. ASSERT_FALSE(res);
  6621. EXPECT_EQ(Error::Read, res.error());
  6622. }
  6623. TEST_F(ServerTest, TooLongHeader) {
  6624. Request req;
  6625. req.method = "GET";
  6626. req.path = "/hi";
  6627. std::string host_and_port;
  6628. host_and_port += HOST;
  6629. host_and_port += ":";
  6630. host_and_port += std::to_string(PORT);
  6631. req.headers.emplace("Host", host_and_port.c_str());
  6632. req.headers.emplace("Accept", "*/*");
  6633. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6634. req.headers.emplace(
  6635. "Header-Name",
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6664. "@@@@@@@@@@@@@@@@@");
  6665. auto res = std::make_shared<Response>();
  6666. auto error = Error::Success;
  6667. auto ret = cli_.send(req, *res, error);
  6668. ASSERT_TRUE(ret);
  6669. EXPECT_EQ(StatusCode::OK_200, res->status);
  6670. }
  6671. TEST_F(ServerTest, HeaderCountAtLimit) {
  6672. // Test with headers just under the 100 limit
  6673. httplib::Headers headers;
  6674. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6675. // This should keep us just under the 100 header limit
  6676. for (int i = 0; i < 95; i++) {
  6677. std::string name = "X-Test-Header-" + std::to_string(i);
  6678. std::string value = "value" + std::to_string(i);
  6679. headers.emplace(name, value);
  6680. }
  6681. // This should work fine as we're under the limit
  6682. auto res = cli_.Get("/hi", headers);
  6683. EXPECT_TRUE(res);
  6684. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6685. }
  6686. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6687. // Test with many headers to exceed the 100 limit
  6688. httplib::Headers headers;
  6689. // Add 150 headers to definitely exceed the 100 limit
  6690. for (int i = 0; i < 150; i++) {
  6691. std::string name = "X-Test-Header-" + std::to_string(i);
  6692. std::string value = "value" + std::to_string(i);
  6693. headers.emplace(name, value);
  6694. }
  6695. // This should fail due to exceeding header count limit
  6696. cli_.set_keep_alive(true);
  6697. auto res = cli_.Get("/hi", headers);
  6698. // The server should respond with 400 Bad Request
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6701. EXPECT_EQ("close", res->get_header_value("Connection"));
  6702. EXPECT_FALSE(cli_.is_socket_open());
  6703. }
  6704. TEST_F(ServerTest, PercentEncoding) {
  6705. auto res = cli_.Get("/e%6edwith%");
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ(StatusCode::OK_200, res->status);
  6708. }
  6709. TEST_F(ServerTest, PercentEncodingUnicode) {
  6710. auto res = cli_.Get("/e%u006edwith%");
  6711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6712. EXPECT_EQ(StatusCode::OK_200, res->status);
  6713. }
  6714. TEST_F(ServerTest, InvalidPercentEncoding) {
  6715. auto res = cli_.Get("/%endwith%");
  6716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6717. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6718. }
  6719. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6720. auto res = cli_.Get("/%uendwith%");
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6723. }
  6724. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6725. auto res = cli_.Get("/hello?aaa=bbb%");
  6726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6727. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6728. }
  6729. TEST_F(ServerTest, PlusSignEncoding) {
  6730. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ(StatusCode::OK_200, res->status);
  6733. EXPECT_EQ("a +b", res->body);
  6734. }
  6735. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6736. // This test simulates a potential DoS attack using many headers
  6737. // to verify our security fix prevents memory exhaustion
  6738. httplib::Headers attack_headers;
  6739. // Attempt to add many headers like an attacker would (200 headers to far
  6740. // exceed limit)
  6741. for (int i = 0; i < 200; i++) {
  6742. std::string name = "X-Attack-Header-" + std::to_string(i);
  6743. std::string value = "attack_payload_" + std::to_string(i);
  6744. attack_headers.emplace(name, value);
  6745. }
  6746. // Try to POST with excessive headers
  6747. cli_.set_keep_alive(true);
  6748. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6749. // Should either fail or return 400 Bad Request due to security limit
  6750. if (res) {
  6751. // If we get a response, it should be 400 Bad Request
  6752. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6753. EXPECT_EQ("close", res->get_header_value("Connection"));
  6754. }
  6755. EXPECT_FALSE(cli_.is_socket_open());
  6756. }
  6757. TEST_F(ServerTest, MultipartFormData) {
  6758. UploadFormDataItems items = {
  6759. {"text1", "text default", "", ""},
  6760. {"text2", "aωb", "", ""},
  6761. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6762. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6763. {"file3", "", "", "application/octet-stream"},
  6764. {"file4", "", "", " application/json tmp-string "}};
  6765. auto res = cli_.Post("/multipart", items);
  6766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6767. EXPECT_EQ(StatusCode::OK_200, res->status);
  6768. }
  6769. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6770. UploadFormDataItems items = {
  6771. {"text", "default text", "", ""},
  6772. {"multi_text1", "aaaaa", "", ""},
  6773. {"multi_text1", "bbbbb", "", ""},
  6774. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6775. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6776. "application/json"},
  6777. };
  6778. auto res = cli_.Post("/multipart/multi_file_values", items);
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. }
  6782. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6783. auto res = cli_.Get("/hi");
  6784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6785. EXPECT_EQ(StatusCode::OK_200, res->status);
  6786. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6787. EXPECT_EQ("Hello World!", res->body);
  6788. }
  6789. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6790. Request req;
  6791. req.method = "POST";
  6792. req.path = "/chunked";
  6793. std::string host_and_port;
  6794. host_and_port += HOST;
  6795. host_and_port += ":";
  6796. host_and_port += std::to_string(PORT);
  6797. req.headers.emplace("Host", host_and_port.c_str());
  6798. req.headers.emplace("Accept", "*/*");
  6799. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6800. req.headers.emplace("Content-Type", "text/plain");
  6801. req.headers.emplace("Content-Length", "0");
  6802. req.headers.emplace(
  6803. "Transfer-Encoding",
  6804. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6805. // Client does not chunk, so make a chunked body manually.
  6806. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6807. auto res = std::make_shared<Response>();
  6808. auto error = Error::Success;
  6809. auto ret = cli_.send(req, *res, error);
  6810. ASSERT_TRUE(ret);
  6811. EXPECT_EQ(StatusCode::OK_200, res->status);
  6812. }
  6813. template <typename ClientT>
  6814. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6815. int expected_status) {
  6816. Request req;
  6817. req.method = "POST";
  6818. req.path = "/chunked";
  6819. std::string host_and_port;
  6820. host_and_port += HOST;
  6821. host_and_port += ":";
  6822. host_and_port += std::to_string(PORT);
  6823. req.headers.emplace("Host", host_and_port.c_str());
  6824. req.headers.emplace("Content-Length", "0");
  6825. req.headers.emplace("Transfer-Encoding", "chunked");
  6826. req.body = body;
  6827. auto res = std::make_shared<Response>();
  6828. auto error = Error::Success;
  6829. ASSERT_TRUE(cli.send(req, *res, error));
  6830. EXPECT_EQ(expected_status, res->status);
  6831. }
  6832. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6833. // rather than treat them as valid lengths.
  6834. template <typename ClientT>
  6835. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6836. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6837. }
  6838. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6839. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6840. }
  6841. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6842. expect_chunked_body_rejected(
  6843. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6844. }
  6845. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6846. // chunk-size line carries no CR, LF or other control character ahead of its
  6847. // terminator. Such a line must be refused rather than read as extension text.
  6848. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6849. expect_chunked_body_rejected(
  6850. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6851. }
  6852. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6853. expect_chunked_body_rejected(
  6854. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6855. }
  6856. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6857. expect_chunked_body_rejected(
  6858. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6859. }
  6860. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6861. // The literal stays split: a hex escape consumes every hex digit that
  6862. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6863. expect_chunked_body_rejected(
  6864. cli_, "4;a\x01"
  6865. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6866. }
  6867. // The bytes around chunk data are no payload, so they cannot ride on the
  6868. // payload limit
  6869. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6870. // Small enough that the whole request is sent before the server turns it
  6871. // down, yet past the limit by the last chunks
  6872. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  6873. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  6874. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  6875. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6876. SCOPED_TRACE(size_line.substr(0, 2));
  6877. std::string body;
  6878. for (auto c : std::string("dechunked post body")) {
  6879. body += size_line + "\r\n" + c + "\r\n";
  6880. }
  6881. body += "0\r\n\r\n";
  6882. expect_chunked_body_rejected(cli_, body.c_str());
  6883. }
  6884. }
  6885. TEST_F(ServerTest, AcceptsChunkExtension) {
  6886. expect_chunked_body_status(cli_,
  6887. "4;name=value\r\ndech\r\n"
  6888. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6889. "0;last\r\n\r\n",
  6890. StatusCode::OK_200);
  6891. }
  6892. TEST_F(ServerTest, GetStreamed2) {
  6893. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6895. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6896. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6897. EXPECT_EQ(true, res->has_header("Content-Range"));
  6898. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6899. EXPECT_EQ(std::string("ab"), res->body);
  6900. }
  6901. TEST_F(ServerTest, GetStreamed) {
  6902. auto res = cli_.Get("/streamed");
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_EQ(StatusCode::OK_200, res->status);
  6905. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6906. EXPECT_EQ(std::string("aaabbb"), res->body);
  6907. }
  6908. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6909. auto res = cli_.Get("/streamed-without-length",
  6910. Headers{make_range_header({{0, -1}})});
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ(StatusCode::OK_200, res->status);
  6913. EXPECT_EQ(false, res->has_header("Content-Length"));
  6914. EXPECT_EQ(false, res->has_header("Content-Range"));
  6915. EXPECT_EQ(std::string("abcdefg"), res->body);
  6916. }
  6917. TEST_F(ServerTest, GetStreamedWithRange1) {
  6918. auto res =
  6919. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6922. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6923. EXPECT_EQ(true, res->has_header("Content-Range"));
  6924. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6925. EXPECT_EQ(std::string("def"), res->body);
  6926. }
  6927. TEST_F(ServerTest, GetStreamedWithRange2) {
  6928. auto res =
  6929. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6932. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6933. EXPECT_EQ(true, res->has_header("Content-Range"));
  6934. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6935. EXPECT_EQ(std::string("bcdefg"), res->body);
  6936. }
  6937. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6938. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6941. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6942. EXPECT_EQ(true, res->has_header("Content-Range"));
  6943. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6944. EXPECT_EQ(std::string("efg"), res->body);
  6945. }
  6946. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6947. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6948. // the entire representation.
  6949. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6950. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6953. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6954. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6955. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6956. }
  6957. }
  6958. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6959. auto res =
  6960. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6963. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6964. EXPECT_EQ(false, res->has_header("Content-Range"));
  6965. EXPECT_EQ(0U, res->body.size());
  6966. }
  6967. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6968. // Only a 206 is served as a partial representation. Under any other status
  6969. // `apply_ranges()` reported the full content length, so the body must match
  6970. // that header, and the content provider must never be asked for an offset
  6971. // outside the representation.
  6972. auto check = [&](int status, const char *range) {
  6973. auto path =
  6974. std::string("/streamed-with-range?status=") + std::to_string(status);
  6975. auto ctx = path + " Range: " + range;
  6976. auto res = cli_.Get(path, Headers{{"Range", range}});
  6977. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6978. EXPECT_EQ(status, res->status) << ctx;
  6979. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6980. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6981. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6982. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6983. };
  6984. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6985. check(403, "bytes=3-5");
  6986. // The offset is far past the representation.
  6987. check(403, "bytes=100000-100200");
  6988. // `first_pos` is still -1 here, and the bounds asserts in
  6989. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6990. check(403, "bytes=-3");
  6991. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6992. // multipart branch would have written one that is empty.
  6993. check(403, "bytes=1-2, 4-5");
  6994. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6995. // covers the whole representation.
  6996. check(200, "bytes=3-5");
  6997. check(200, "bytes=1-2, 4-5");
  6998. }
  6999. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7000. auto res =
  7001. cli_.Get("/streamed-with-range",
  7002. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7003. "92233720368547758079223372036854775807"}});
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7006. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7007. EXPECT_EQ(false, res->has_header("Content-Range"));
  7008. EXPECT_EQ(0U, res->body.size());
  7009. }
  7010. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7011. auto res = cli_.Get(
  7012. "/with-range",
  7013. Headers{{"Range",
  7014. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7015. {"Accept-Encoding", ""}});
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7018. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7019. EXPECT_EQ(true, res->has_header("Content-Range"));
  7020. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7021. EXPECT_EQ(std::string("abcdefg"), res->body);
  7022. }
  7023. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7024. auto res = cli_.Get("/with-range", Headers{
  7025. {"Range", "bytes=0-"},
  7026. {"Accept-Encoding", ""},
  7027. });
  7028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7029. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7030. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7031. EXPECT_EQ(true, res->has_header("Content-Range"));
  7032. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7033. EXPECT_EQ(std::string("abcdefg"), res->body);
  7034. }
  7035. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7036. auto res = cli_.Get("/streamed-with-range",
  7037. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7040. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7041. EXPECT_EQ(false, res->has_header("Content-Range"));
  7042. EXPECT_EQ(267U, res->body.size());
  7043. // Check that both range contents are present
  7044. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7045. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7046. // Check that Content-Range headers are present for both ranges
  7047. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7048. std::string::npos);
  7049. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7050. std::string::npos);
  7051. }
  7052. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7053. Ranges ranges;
  7054. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7055. ranges.emplace_back(0, -1);
  7056. }
  7057. auto res = cli_.Get("/streamed-with-range?error",
  7058. Headers{{make_range_header(ranges)}});
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7061. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7062. EXPECT_EQ(false, res->has_header("Content-Range"));
  7063. EXPECT_EQ(0U, res->body.size());
  7064. }
  7065. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7066. auto res = cli_.Get("/streamed-with-range",
  7067. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7069. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7070. EXPECT_EQ(5U, res->body.size());
  7071. // Check that overlapping ranges are coalesced into a single range
  7072. EXPECT_EQ("bcdef", res->body);
  7073. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7074. // Should be single range, not multipart
  7075. EXPECT_TRUE(res->has_header("Content-Range"));
  7076. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7077. }
  7078. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7079. auto res = cli_.Get("/streamed-with-range",
  7080. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7083. EXPECT_EQ(268U, res->body.size());
  7084. // Check that both range contents are present
  7085. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7086. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7087. // Check that Content-Range headers are present for both ranges
  7088. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7089. std::string::npos);
  7090. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7091. std::string::npos);
  7092. }
  7093. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7094. auto res = cli_.Get("/streamed-with-range",
  7095. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7098. EXPECT_EQ(269U, res->body.size());
  7099. // Check that both duplicate range contents are present
  7100. size_t first_abc = res->body.find("abc\r\n");
  7101. EXPECT_TRUE(first_abc != std::string::npos);
  7102. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7103. EXPECT_TRUE(second_abc != std::string::npos);
  7104. // Check that Content-Range headers are present for both ranges
  7105. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7106. EXPECT_TRUE(first_range != std::string::npos);
  7107. size_t second_range =
  7108. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7109. EXPECT_TRUE(second_range != std::string::npos);
  7110. }
  7111. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7112. auto res =
  7113. cli_.Get("/streamed-with-range?error",
  7114. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7117. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7118. EXPECT_EQ(false, res->has_header("Content-Range"));
  7119. EXPECT_EQ(0U, res->body.size());
  7120. }
  7121. TEST_F(ServerTest, GetStreamedEndless) {
  7122. uint64_t offset = 0;
  7123. auto res = cli_.Get("/streamed-cancel",
  7124. [&](const char * /*data*/, uint64_t data_length) {
  7125. if (offset < 100) {
  7126. offset += data_length;
  7127. return true;
  7128. }
  7129. return false;
  7130. });
  7131. ASSERT_TRUE(!res);
  7132. EXPECT_EQ(Error::Canceled, res.error());
  7133. }
  7134. TEST_F(ServerTest, ClientStop) {
  7135. std::atomic_size_t count{4};
  7136. std::vector<std::thread> threads;
  7137. for (auto i = count.load(); i != 0; --i) {
  7138. threads.emplace_back([&]() {
  7139. auto res = cli_.Get("/streamed-cancel",
  7140. [&](const char *, uint64_t) { return true; });
  7141. --count;
  7142. ASSERT_TRUE(!res);
  7143. EXPECT_TRUE(res.error() == Error::Canceled ||
  7144. res.error() == Error::Read || res.error() == Error::Write);
  7145. });
  7146. }
  7147. std::this_thread::sleep_for(std::chrono::seconds(2));
  7148. while (count != 0) {
  7149. cli_.stop();
  7150. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7151. }
  7152. for (auto &t : threads) {
  7153. t.join();
  7154. }
  7155. }
  7156. TEST_F(ServerTest, GetWithRange1) {
  7157. auto res = cli_.Get("/with-range", Headers{
  7158. make_range_header({{3, 5}}),
  7159. {"Accept-Encoding", ""},
  7160. });
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7163. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7164. EXPECT_EQ(true, res->has_header("Content-Range"));
  7165. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7166. EXPECT_EQ(std::string("def"), res->body);
  7167. }
  7168. TEST_F(ServerTest, GetWithRange2) {
  7169. auto res = cli_.Get("/with-range", Headers{
  7170. make_range_header({{1, -1}}),
  7171. {"Accept-Encoding", ""},
  7172. });
  7173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7175. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7176. EXPECT_EQ(true, res->has_header("Content-Range"));
  7177. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7178. EXPECT_EQ(std::string("bcdefg"), res->body);
  7179. }
  7180. TEST_F(ServerTest, GetWithRange3) {
  7181. auto res = cli_.Get("/with-range", Headers{
  7182. make_range_header({{0, 0}}),
  7183. {"Accept-Encoding", ""},
  7184. });
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7187. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(true, res->has_header("Content-Range"));
  7189. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7190. EXPECT_EQ(std::string("a"), res->body);
  7191. }
  7192. TEST_F(ServerTest, GetWithRange4) {
  7193. auto res = cli_.Get("/with-range", Headers{
  7194. make_range_header({{-1, 2}}),
  7195. {"Accept-Encoding", ""},
  7196. });
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7199. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7200. EXPECT_EQ(true, res->has_header("Content-Range"));
  7201. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7202. EXPECT_EQ(std::string("fg"), res->body);
  7203. }
  7204. TEST_F(ServerTest, GetWithRange5) {
  7205. auto res = cli_.Get("/with-range", Headers{
  7206. make_range_header({{0, 5}}),
  7207. {"Accept-Encoding", ""},
  7208. });
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7211. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7212. EXPECT_EQ(true, res->has_header("Content-Range"));
  7213. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7214. EXPECT_EQ(std::string("abcdef"), res->body);
  7215. }
  7216. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7217. auto res =
  7218. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7220. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7221. }
  7222. TEST_F(ServerTest, GetWithRangeMultipart) {
  7223. auto res =
  7224. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7227. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7228. EXPECT_EQ(false, res->has_header("Content-Range"));
  7229. EXPECT_EQ(267U, res->body.size());
  7230. }
  7231. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7232. auto res = cli_.Get("/with-range",
  7233. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7236. }
  7237. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7238. auto res = cli_.Get("/with-range-customized-response",
  7239. Headers{{make_range_header({{1, 2}})}});
  7240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7241. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7242. EXPECT_EQ(true, res->has_header("Content-Length"));
  7243. EXPECT_EQ(false, res->has_header("Content-Range"));
  7244. EXPECT_EQ(JSON_DATA, res->body);
  7245. }
  7246. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7247. auto res = cli_.Get("/with-range-customized-response",
  7248. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7251. EXPECT_EQ(true, res->has_header("Content-Length"));
  7252. EXPECT_EQ(false, res->has_header("Content-Range"));
  7253. EXPECT_EQ(JSON_DATA, res->body);
  7254. }
  7255. TEST_F(ServerTest, Issue1772) {
  7256. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7259. }
  7260. TEST_F(ServerTest, Issue609) {
  7261. auto res = cli_.Delete("/issue609");
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::OK_200, res->status);
  7264. EXPECT_EQ(std::string("ok"), res->body);
  7265. }
  7266. TEST_F(ServerTest, GetStreamedChunked) {
  7267. auto res = cli_.Get("/streamed-chunked");
  7268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7269. EXPECT_EQ(StatusCode::OK_200, res->status);
  7270. EXPECT_EQ(std::string("123456789"), res->body);
  7271. }
  7272. TEST_F(ServerTest, GetStreamedChunked2) {
  7273. auto res = cli_.Get("/streamed-chunked2");
  7274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7275. EXPECT_EQ(StatusCode::OK_200, res->status);
  7276. EXPECT_EQ(std::string("123456789"), res->body);
  7277. }
  7278. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7279. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ(StatusCode::OK_200, res->status);
  7282. EXPECT_EQ(std::string("123456789"), res->body);
  7283. EXPECT_TRUE(res->has_header("Trailer"));
  7284. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7285. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7286. // Trailers are now stored separately from headers (security fix)
  7287. EXPECT_EQ(2U, res->trailers.size());
  7288. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7289. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7290. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7291. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7292. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7293. // Verify trailers are NOT in headers (security verification)
  7294. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7295. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7296. }
  7297. TEST_F(ServerTest, LargeChunkedPost) {
  7298. Request req;
  7299. req.method = "POST";
  7300. req.path = "/large-chunked";
  7301. std::string host_and_port;
  7302. host_and_port += HOST;
  7303. host_and_port += ":";
  7304. host_and_port += std::to_string(PORT);
  7305. req.headers.emplace("Host", host_and_port.c_str());
  7306. req.headers.emplace("Accept", "*/*");
  7307. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7308. req.headers.emplace("Content-Type", "text/plain");
  7309. req.headers.emplace("Content-Length", "0");
  7310. req.headers.emplace("Transfer-Encoding", "chunked");
  7311. std::string long_string(30 * 1024u, 'a');
  7312. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7313. // Attempt to make a large enough post to exceed OS buffers, to test that
  7314. // the server handles short reads if the full chunk data isn't available.
  7315. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7316. auto res = std::make_shared<Response>();
  7317. auto error = Error::Success;
  7318. auto ret = cli_.send(req, *res, error);
  7319. ASSERT_TRUE(ret);
  7320. EXPECT_EQ(StatusCode::OK_200, res->status);
  7321. }
  7322. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7323. auto res = cli_.Get("/remote_addr");
  7324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7325. EXPECT_EQ(StatusCode::OK_200, res->status);
  7326. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7327. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7328. }
  7329. TEST_F(ServerTest, GetMethodLocalAddr) {
  7330. auto res = cli_.Get("/local_addr");
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::OK_200, res->status);
  7333. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7334. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7335. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7336. }
  7337. TEST_F(ServerTest, HTTPResponseSplitting) {
  7338. auto res = cli_.Get("/http_response_splitting");
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ(StatusCode::OK_200, res->status);
  7341. }
  7342. TEST_F(ServerTest, SlowRequest) {
  7343. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7344. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7345. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7346. }
  7347. #if 0
  7348. TEST_F(ServerTest, SlowPost) {
  7349. char buffer[64 * 1024];
  7350. memset(buffer, 0x42, sizeof(buffer));
  7351. auto res = cli_.Post(
  7352. "/slowpost", 64 * 1024 * 1024,
  7353. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7354. auto ret = sink.write(buffer, sizeof(buffer));
  7355. EXPECT_TRUE(ret);
  7356. return true;
  7357. },
  7358. "text/plain");
  7359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7360. EXPECT_EQ(StatusCode::OK_200, res->status);
  7361. }
  7362. TEST_F(ServerTest, SlowPostFail) {
  7363. char buffer[64 * 1024];
  7364. memset(buffer, 0x42, sizeof(buffer));
  7365. cli_.set_write_timeout(std::chrono::seconds(0));
  7366. auto res = cli_.Post(
  7367. "/slowpost", 64 * 1024 * 1024,
  7368. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7369. sink.write(buffer, sizeof(buffer));
  7370. return true;
  7371. },
  7372. "text/plain");
  7373. ASSERT_TRUE(!res);
  7374. EXPECT_EQ(Error::Write, res.error());
  7375. }
  7376. #endif
  7377. TEST_F(ServerTest, Put) {
  7378. auto res = cli_.Put("/put", "PUT", "text/plain");
  7379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7380. EXPECT_EQ(StatusCode::OK_200, res->status);
  7381. EXPECT_EQ("PUT", res->body);
  7382. }
  7383. TEST_F(ServerTest, PutWithContentProvider) {
  7384. auto res = cli_.Put(
  7385. "/put", 3,
  7386. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7387. sink.os << "PUT";
  7388. return true;
  7389. },
  7390. "text/plain");
  7391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7392. EXPECT_EQ(StatusCode::OK_200, res->status);
  7393. EXPECT_EQ("PUT", res->body);
  7394. }
  7395. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7396. auto res = cli_.Post(
  7397. "/post", 42,
  7398. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7399. return false;
  7400. },
  7401. "text/plain");
  7402. ASSERT_TRUE(!res);
  7403. EXPECT_EQ(Error::Canceled, res.error());
  7404. }
  7405. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7406. auto res = cli_.Put(
  7407. "/put",
  7408. [](size_t /*offset*/, DataSink &sink) {
  7409. sink.os << "PUT";
  7410. sink.done();
  7411. return true;
  7412. },
  7413. "text/plain");
  7414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7415. EXPECT_EQ(StatusCode::OK_200, res->status);
  7416. EXPECT_EQ("PUT", res->body);
  7417. }
  7418. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7419. auto res = cli_.Post(
  7420. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7421. "text/plain");
  7422. ASSERT_TRUE(!res);
  7423. EXPECT_EQ(Error::Canceled, res.error());
  7424. }
  7425. TEST_F(ServerTest, PostLoopBack) {
  7426. std::string body;
  7427. auto res = cli_.Post(
  7428. "/post-loopback", 9,
  7429. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7430. EXPECT_EQ(9u, length);
  7431. sink.write("123", 3);
  7432. sink.write("456", 3);
  7433. sink.write("789", 3);
  7434. return true;
  7435. },
  7436. "text/plain",
  7437. [&body](const char *data, size_t data_length) {
  7438. body.append(data, data_length);
  7439. return true;
  7440. });
  7441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7442. EXPECT_EQ(StatusCode::OK_200, res->status);
  7443. EXPECT_EQ("123456789", body);
  7444. }
  7445. TEST_F(ServerTest, PutLoopBack) {
  7446. std::string body;
  7447. auto res = cli_.Put(
  7448. "/put-loopback", 9,
  7449. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7450. EXPECT_EQ(9u, length);
  7451. sink.write("123", 3);
  7452. sink.write("456", 3);
  7453. sink.write("789", 3);
  7454. return true;
  7455. },
  7456. "text/plain",
  7457. [&body](const char *data, size_t data_length) {
  7458. body.append(data, data_length);
  7459. return true;
  7460. });
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. EXPECT_EQ("123456789", body);
  7464. }
  7465. TEST_F(ServerTest, PatchLoopBack) {
  7466. std::string body;
  7467. auto res = cli_.Patch(
  7468. "/patch-loopback", 9,
  7469. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7470. EXPECT_EQ(9u, length);
  7471. sink.write("123", 3);
  7472. sink.write("456", 3);
  7473. sink.write("789", 3);
  7474. return true;
  7475. },
  7476. "text/plain",
  7477. [&body](const char *data, size_t data_length) {
  7478. body.append(data, data_length);
  7479. return true;
  7480. });
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. EXPECT_EQ("123456789", body);
  7484. }
  7485. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7486. std::string body;
  7487. auto res = cli_.Post(
  7488. "/post-loopback",
  7489. [](size_t /*offset*/, DataSink &sink) {
  7490. sink.write("123", 3);
  7491. sink.write("456", 3);
  7492. sink.write("789", 3);
  7493. sink.done();
  7494. return true;
  7495. },
  7496. "text/plain",
  7497. [&body](const char *data, size_t data_length) {
  7498. body.append(data, data_length);
  7499. return true;
  7500. });
  7501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7502. EXPECT_EQ(StatusCode::OK_200, res->status);
  7503. EXPECT_EQ("123456789", body);
  7504. }
  7505. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7506. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7507. cli_.set_compress(true);
  7508. auto res = cli_.Put(
  7509. "/put", 3,
  7510. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7511. sink.os << "PUT";
  7512. return true;
  7513. },
  7514. "text/plain");
  7515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. EXPECT_EQ("PUT", res->body);
  7518. }
  7519. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7520. cli_.set_compress(true);
  7521. auto res = cli_.Post(
  7522. "/post", 42,
  7523. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7524. return false;
  7525. },
  7526. "text/plain");
  7527. ASSERT_TRUE(!res);
  7528. EXPECT_EQ(Error::Canceled, res.error());
  7529. }
  7530. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7531. cli_.set_compress(true);
  7532. auto res = cli_.Put(
  7533. "/put",
  7534. [](size_t /*offset*/, DataSink &sink) {
  7535. sink.os << "PUT";
  7536. sink.done();
  7537. return true;
  7538. },
  7539. "text/plain");
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::OK_200, res->status);
  7542. EXPECT_EQ("PUT", res->body);
  7543. }
  7544. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7545. cli_.set_compress(true);
  7546. auto res = cli_.Post(
  7547. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7548. "text/plain");
  7549. ASSERT_TRUE(!res);
  7550. EXPECT_EQ(Error::Canceled, res.error());
  7551. }
  7552. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7553. cli_.set_compress(true);
  7554. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. EXPECT_EQ(StatusCode::OK_200, res->status);
  7557. EXPECT_EQ(LARGE_DATA, res->body);
  7558. }
  7559. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7560. #ifdef CPPHTTPLIB_SSL_ENABLED
  7561. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7562. Client cli(s.c_str());
  7563. cli.enable_server_certificate_verification(false);
  7564. #else
  7565. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7566. Client cli(s.c_str());
  7567. #endif
  7568. cli.set_compress(true);
  7569. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7571. EXPECT_EQ(StatusCode::OK_200, res->status);
  7572. EXPECT_EQ(LARGE_DATA, res->body);
  7573. // The compressed size should be less than a 10th of the original. May vary
  7574. // depending on the zlib library.
  7575. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7576. static_cast<uint64_t>(10 * 1024 * 1024));
  7577. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7578. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7579. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7580. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7581. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7582. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7583. #endif
  7584. }
  7585. TEST_F(ServerTest, PutContentWithDeflate) {
  7586. cli_.set_compress(false);
  7587. Headers headers;
  7588. headers.emplace("Content-Encoding", "deflate");
  7589. // PUT in deflate format:
  7590. auto res = cli_.Put("/put", headers,
  7591. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7593. EXPECT_EQ(StatusCode::OK_200, res->status);
  7594. EXPECT_EQ("PUT", res->body);
  7595. }
  7596. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7597. Headers headers;
  7598. headers.emplace("Accept-Encoding", "gzip, deflate");
  7599. auto res = cli_.Get("/streamed-chunked", headers);
  7600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7601. EXPECT_EQ(StatusCode::OK_200, res->status);
  7602. EXPECT_EQ(std::string("123456789"), res->body);
  7603. }
  7604. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7605. Headers headers;
  7606. headers.emplace("Accept-Encoding", "gzip, deflate");
  7607. auto res = cli_.Get("/streamed-chunked2", headers);
  7608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7609. EXPECT_EQ(StatusCode::OK_200, res->status);
  7610. EXPECT_EQ(std::string("123456789"), res->body);
  7611. }
  7612. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7613. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. }
  7617. TEST(GzipDecompressor, ChunkedDecompression) {
  7618. std::string data;
  7619. for (size_t i = 0; i < 32 * 1024; ++i) {
  7620. data.push_back(static_cast<char>('a' + i % 26));
  7621. }
  7622. std::string compressed_data;
  7623. {
  7624. httplib::detail::gzip_compressor compressor;
  7625. bool result = compressor.compress(
  7626. data.data(), data.size(),
  7627. /*last=*/true,
  7628. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7629. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7630. compressed_data_size);
  7631. return true;
  7632. });
  7633. ASSERT_TRUE(result);
  7634. }
  7635. std::string decompressed_data;
  7636. {
  7637. httplib::detail::gzip_decompressor decompressor;
  7638. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7639. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7640. size_t chunk_size = 130;
  7641. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7642. chunk_begin += chunk_size) {
  7643. size_t current_chunk_size =
  7644. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7645. bool result = decompressor.decompress(
  7646. compressed_data.data() + chunk_begin, current_chunk_size,
  7647. [&](const char *decompressed_data_chunk,
  7648. size_t decompressed_data_chunk_size) {
  7649. decompressed_data.insert(decompressed_data.size(),
  7650. decompressed_data_chunk,
  7651. decompressed_data_chunk_size);
  7652. return true;
  7653. });
  7654. ASSERT_TRUE(result);
  7655. }
  7656. }
  7657. ASSERT_EQ(data, decompressed_data);
  7658. }
  7659. TEST(GzipDecompressor, DeflateDecompression) {
  7660. std::string original_text = "Raw deflate without gzip";
  7661. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7662. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7663. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7664. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7665. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7666. std::string decompressed_data;
  7667. {
  7668. httplib::detail::gzip_decompressor decompressor;
  7669. bool result = decompressor.decompress(
  7670. compressed_data.data(), compressed_data.size(),
  7671. [&](const char *decompressed_data_chunk,
  7672. size_t decompressed_data_chunk_size) {
  7673. decompressed_data.insert(decompressed_data.size(),
  7674. decompressed_data_chunk,
  7675. decompressed_data_chunk_size);
  7676. return true;
  7677. });
  7678. ASSERT_TRUE(result);
  7679. }
  7680. ASSERT_EQ(original_text, decompressed_data);
  7681. }
  7682. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7683. std::string original_text = "Raw deflate without gzip";
  7684. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7685. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7686. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7687. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7688. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7689. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7690. std::string decompressed_data;
  7691. {
  7692. httplib::detail::gzip_decompressor decompressor;
  7693. bool result = decompressor.decompress(
  7694. compressed_data.data(), compressed_data.size(),
  7695. [&](const char *decompressed_data_chunk,
  7696. size_t decompressed_data_chunk_size) {
  7697. decompressed_data.insert(decompressed_data.size(),
  7698. decompressed_data_chunk,
  7699. decompressed_data_chunk_size);
  7700. return true;
  7701. });
  7702. ASSERT_TRUE(result);
  7703. }
  7704. ASSERT_EQ(original_text, decompressed_data);
  7705. }
  7706. #endif
  7707. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7708. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7709. Headers headers;
  7710. headers.emplace("Accept-Encoding", "br");
  7711. auto res = cli_.Get("/streamed-chunked", headers);
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. EXPECT_EQ(std::string("123456789"), res->body);
  7715. }
  7716. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7717. Headers headers;
  7718. headers.emplace("Accept-Encoding", "br");
  7719. auto res = cli_.Get("/streamed-chunked2", headers);
  7720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7721. EXPECT_EQ(StatusCode::OK_200, res->status);
  7722. EXPECT_EQ(std::string("123456789"), res->body);
  7723. }
  7724. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7725. cli_.set_compress(true);
  7726. auto res = cli_.Put(
  7727. "/put", 3,
  7728. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7729. sink.os << "PUT";
  7730. return true;
  7731. },
  7732. "text/plain");
  7733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7734. EXPECT_EQ(StatusCode::OK_200, res->status);
  7735. EXPECT_EQ("PUT", res->body);
  7736. }
  7737. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7738. cli_.set_compress(true);
  7739. auto res = cli_.Put(
  7740. "/put",
  7741. [](size_t /*offset*/, DataSink &sink) {
  7742. sink.os << "PUT";
  7743. sink.done();
  7744. return true;
  7745. },
  7746. "text/plain");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. EXPECT_EQ("PUT", res->body);
  7750. }
  7751. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7752. cli_.set_compress(true);
  7753. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7755. EXPECT_EQ(StatusCode::OK_200, res->status);
  7756. EXPECT_EQ(LARGE_DATA, res->body);
  7757. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7758. }
  7759. #endif
  7760. TEST_F(ServerTest, Patch) {
  7761. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7763. EXPECT_EQ(StatusCode::OK_200, res->status);
  7764. EXPECT_EQ("PATCH", res->body);
  7765. }
  7766. TEST_F(ServerTest, Delete) {
  7767. auto res = cli_.Delete("/delete");
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. EXPECT_EQ("DELETE", res->body);
  7771. }
  7772. TEST_F(ServerTest, DeleteContentReceiver) {
  7773. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7775. EXPECT_EQ(StatusCode::OK_200, res->status);
  7776. EXPECT_EQ("content", res->body);
  7777. }
  7778. TEST_F(ServerTest, Options) {
  7779. auto res = cli_.Options("*");
  7780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7781. EXPECT_EQ(StatusCode::OK_200, res->status);
  7782. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7783. EXPECT_TRUE(res->body.empty());
  7784. }
  7785. TEST_F(ServerTest, URL) {
  7786. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7788. EXPECT_EQ(StatusCode::OK_200, res->status);
  7789. }
  7790. TEST_F(ServerTest, ArrayParam) {
  7791. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7793. EXPECT_EQ(StatusCode::OK_200, res->status);
  7794. }
  7795. TEST_F(ServerTest, ArrayParamValues) {
  7796. auto res =
  7797. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7799. EXPECT_EQ(StatusCode::OK_200, res->status);
  7800. }
  7801. TEST_F(ServerTest, NoMultipleHeaders) {
  7802. Headers headers = {{"Content-Length", "5"}};
  7803. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7804. "text/plain");
  7805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7806. EXPECT_EQ(StatusCode::OK_200, res->status);
  7807. }
  7808. TEST_F(ServerTest, PostContentReceiver) {
  7809. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7811. ASSERT_EQ(StatusCode::OK_200, res->status);
  7812. ASSERT_EQ("content", res->body);
  7813. }
  7814. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7815. UploadFormDataItems items = {
  7816. {"text1", "text default", "", ""},
  7817. {"text2", "aωb", "", ""},
  7818. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7819. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7820. {"file3", "", "", "application/octet-stream"},
  7821. };
  7822. auto res = cli_.Post("/content_receiver", items);
  7823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7824. EXPECT_EQ(StatusCode::OK_200, res->status);
  7825. }
  7826. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7827. UploadFormDataItems items = {
  7828. {"text1", "text default", "", ""},
  7829. {"text2", "aωb", "", ""},
  7830. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7831. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7832. {"file3", "", "", "application/octet-stream"},
  7833. };
  7834. auto boundary = std::string("+++++");
  7835. std::string body;
  7836. for (const auto &item : items) {
  7837. body += "--" + boundary + "\r\n";
  7838. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7839. if (!item.filename.empty()) {
  7840. body += "; filename=\"" + item.filename + "\"";
  7841. }
  7842. body += "\r\n";
  7843. if (!item.content_type.empty()) {
  7844. body += "Content-Type: " + item.content_type + "\r\n";
  7845. }
  7846. body += "\r\n";
  7847. body += item.content + "\r\n";
  7848. }
  7849. body += "--" + boundary + "--\r\n";
  7850. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7851. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7853. EXPECT_EQ(StatusCode::OK_200, res->status);
  7854. }
  7855. TEST(MultipartFormDataTest, FieldEscaping) {
  7856. Server svr;
  7857. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7858. const ContentReader &content_reader) {
  7859. ASSERT_TRUE(req.is_multipart_form_data());
  7860. std::vector<FormData> received;
  7861. content_reader(
  7862. [&](const FormData &file) {
  7863. received.push_back(file);
  7864. return true;
  7865. },
  7866. [&](const char *data, size_t data_length) {
  7867. received.back().content.append(data, data_length);
  7868. return true;
  7869. });
  7870. // '"', CR and LF in names and filenames are escaped following the
  7871. // WHATWG HTML standard, so each part still parses as a single part
  7872. // with no injected headers. Content types get CR/LF escaped too,
  7873. // while '"' (legal there, e.g. quoted charset) is preserved.
  7874. ASSERT_EQ(4U, received.size());
  7875. EXPECT_EQ("na%22me", received[0].name);
  7876. EXPECT_EQ("quoted name", received[0].content);
  7877. EXPECT_EQ("file", received[1].name);
  7878. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7879. received[1].filename);
  7880. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7881. EXPECT_EQ("injected", received[1].content);
  7882. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7883. EXPECT_EQ("my%22file.txt", received[2].filename);
  7884. EXPECT_EQ("cr lf name", received[2].content);
  7885. EXPECT_EQ("typed", received[3].name);
  7886. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7887. received[3].content_type);
  7888. EXPECT_EQ("typed content", received[3].content);
  7889. });
  7890. auto port = svr.bind_to_any_port("localhost");
  7891. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7892. auto se = detail::scope_exit([&] {
  7893. svr.stop();
  7894. t.join();
  7895. ASSERT_FALSE(svr.is_running());
  7896. });
  7897. svr.wait_until_ready();
  7898. Client cli("localhost", port);
  7899. UploadFormDataItems items = {
  7900. {"na\"me", "quoted name", "", ""},
  7901. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7902. "application/octet-stream"},
  7903. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7904. {"typed", "typed content", "",
  7905. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7906. };
  7907. auto res = cli.Post("/post", items);
  7908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7909. EXPECT_EQ(StatusCode::OK_200, res->status);
  7910. }
  7911. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7912. const UploadFormDataItems items = {
  7913. {"name1", "Content 1", "", ""},
  7914. {"name2", "Content 2", "file2.txt", "text/plain"},
  7915. };
  7916. Server svr;
  7917. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7918. const ContentReader &content_reader) {
  7919. ASSERT_TRUE(req.is_multipart_form_data());
  7920. std::vector<FormData> received;
  7921. content_reader(
  7922. [&](const FormData &file) {
  7923. received.push_back(file);
  7924. return true;
  7925. },
  7926. [&](const char *data, size_t data_length) {
  7927. received.back().content.append(data, data_length);
  7928. return true;
  7929. });
  7930. ASSERT_EQ(2U, received.size());
  7931. EXPECT_EQ("name1", received[0].name);
  7932. EXPECT_EQ("Content 1", received[0].content);
  7933. EXPECT_EQ("name2", received[1].name);
  7934. EXPECT_EQ("Content 2", received[1].content);
  7935. EXPECT_EQ("file2.txt", received[1].filename);
  7936. EXPECT_EQ("text/plain", received[1].content_type);
  7937. });
  7938. auto port = svr.bind_to_any_port("localhost");
  7939. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7940. auto se = detail::scope_exit([&] {
  7941. svr.stop();
  7942. t.join();
  7943. ASSERT_FALSE(svr.is_running());
  7944. });
  7945. svr.wait_until_ready();
  7946. Client cli("localhost", port);
  7947. // Whole-body serialization with a generated boundary
  7948. {
  7949. MultipartFormDataWriter writer;
  7950. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7951. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7952. writer.content_type());
  7953. auto body = writer.serialize(items);
  7954. EXPECT_EQ(body.size(), writer.content_length(items));
  7955. auto res = cli.Post("/post", body, writer.content_type());
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. }
  7959. // Per-part framing with a custom boundary via a content provider
  7960. {
  7961. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7962. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7963. MultipartFormDataWriter writer("custom-boundary_123");
  7964. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7965. std::string body;
  7966. for (const auto &item : items) {
  7967. body += writer.item_begin(item);
  7968. body += item.content;
  7969. body += MultipartFormDataWriter::item_end();
  7970. }
  7971. body += writer.finish();
  7972. EXPECT_EQ(body.size(), writer.content_length(items));
  7973. auto res = cli.Post(
  7974. "/post", body.size(),
  7975. [&](size_t offset, size_t length, DataSink &sink) {
  7976. sink.write(body.data() + offset, length);
  7977. return true;
  7978. },
  7979. writer.content_type());
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ(StatusCode::OK_200, res->status);
  7982. }
  7983. }
  7984. TEST_F(ServerTest, PostContentReceiverGzip) {
  7985. cli_.set_compress(true);
  7986. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7988. ASSERT_EQ(StatusCode::OK_200, res->status);
  7989. ASSERT_EQ("content", res->body);
  7990. }
  7991. TEST_F(ServerTest, PutContentReceiver) {
  7992. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7994. ASSERT_EQ(StatusCode::OK_200, res->status);
  7995. ASSERT_EQ("content", res->body);
  7996. }
  7997. TEST_F(ServerTest, PatchContentReceiver) {
  7998. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8000. ASSERT_EQ(StatusCode::OK_200, res->status);
  8001. ASSERT_EQ("content", res->body);
  8002. }
  8003. template <typename ClientType>
  8004. void TestWithHeadersAndContentReceiver(
  8005. ClientType &cli,
  8006. std::function<Result(ClientType &, const std::string &, const Headers &,
  8007. const std::string &, const std::string &,
  8008. ContentReceiver, DownloadProgress)>
  8009. request_func) {
  8010. Headers headers;
  8011. headers.emplace("X-Custom-Header", "test-value");
  8012. std::string received_body;
  8013. auto res = request_func(
  8014. cli, "/content_receiver", headers, "content", "application/json",
  8015. [&](const char *data, size_t data_length) {
  8016. received_body.append(data, data_length);
  8017. return true;
  8018. },
  8019. nullptr);
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_EQ(StatusCode::OK_200, res->status);
  8022. EXPECT_EQ("content", received_body);
  8023. }
  8024. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8025. #ifdef CPPHTTPLIB_SSL_ENABLED
  8026. using ClientT = SSLClient;
  8027. #else
  8028. using ClientT = Client;
  8029. #endif
  8030. TestWithHeadersAndContentReceiver<ClientT>(
  8031. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8032. const std::string &body, const std::string &content_type,
  8033. ContentReceiver receiver, DownloadProgress progress) {
  8034. return cli.Post(path, headers, body, content_type, receiver, progress);
  8035. });
  8036. }
  8037. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8038. #ifdef CPPHTTPLIB_SSL_ENABLED
  8039. using ClientT = SSLClient;
  8040. #else
  8041. using ClientT = Client;
  8042. #endif
  8043. TestWithHeadersAndContentReceiver<ClientT>(
  8044. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8045. const std::string &body, const std::string &content_type,
  8046. ContentReceiver receiver, DownloadProgress progress) {
  8047. return cli.Put(path, headers, body, content_type, receiver, progress);
  8048. });
  8049. }
  8050. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8051. #ifdef CPPHTTPLIB_SSL_ENABLED
  8052. using ClientT = SSLClient;
  8053. #else
  8054. using ClientT = Client;
  8055. #endif
  8056. TestWithHeadersAndContentReceiver<ClientT>(
  8057. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8058. const std::string &body, const std::string &content_type,
  8059. ContentReceiver receiver, DownloadProgress progress) {
  8060. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8061. });
  8062. }
  8063. template <typename ClientType>
  8064. void TestWithHeadersAndContentReceiverWithProgress(
  8065. ClientType &cli,
  8066. std::function<Result(ClientType &, const std::string &, const Headers &,
  8067. const std::string &, const std::string &,
  8068. ContentReceiver, DownloadProgress)>
  8069. request_func) {
  8070. Headers headers;
  8071. headers.emplace("X-Test-Header", "progress-test");
  8072. std::string received_body;
  8073. auto progress_called = false;
  8074. auto res = request_func(
  8075. cli, "/content_receiver", headers, "content", "text/plain",
  8076. [&](const char *data, size_t data_length) {
  8077. received_body.append(data, data_length);
  8078. return true;
  8079. },
  8080. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8081. progress_called = true;
  8082. return true;
  8083. });
  8084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8085. EXPECT_EQ(StatusCode::OK_200, res->status);
  8086. EXPECT_EQ("content", received_body);
  8087. EXPECT_TRUE(progress_called);
  8088. }
  8089. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8090. #ifdef CPPHTTPLIB_SSL_ENABLED
  8091. using ClientT = SSLClient;
  8092. #else
  8093. using ClientT = Client;
  8094. #endif
  8095. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8096. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8097. const std::string &body, const std::string &content_type,
  8098. ContentReceiver receiver, DownloadProgress progress) {
  8099. return cli.Post(path, headers, body, content_type, receiver, progress);
  8100. });
  8101. }
  8102. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8103. #ifdef CPPHTTPLIB_SSL_ENABLED
  8104. using ClientT = SSLClient;
  8105. #else
  8106. using ClientT = Client;
  8107. #endif
  8108. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8109. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8110. const std::string &body, const std::string &content_type,
  8111. ContentReceiver receiver, DownloadProgress progress) {
  8112. return cli.Put(path, headers, body, content_type, receiver, progress);
  8113. });
  8114. }
  8115. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8116. #ifdef CPPHTTPLIB_SSL_ENABLED
  8117. using ClientT = SSLClient;
  8118. #else
  8119. using ClientT = Client;
  8120. #endif
  8121. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8122. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8123. const std::string &body, const std::string &content_type,
  8124. ContentReceiver receiver, DownloadProgress progress) {
  8125. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8126. });
  8127. }
  8128. template <typename ClientType>
  8129. void TestWithHeadersAndContentReceiverError(
  8130. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8131. const Headers &, const std::string &,
  8132. const std::string &, ContentReceiver)>
  8133. request_func) {
  8134. Headers headers;
  8135. headers.emplace("X-Error-Test", "true");
  8136. std::string received_body;
  8137. auto receiver_failed = false;
  8138. auto res =
  8139. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8140. [&](const char *data, size_t data_length) {
  8141. received_body.append(data, data_length);
  8142. receiver_failed = true;
  8143. return false;
  8144. });
  8145. ASSERT_FALSE(res);
  8146. EXPECT_TRUE(receiver_failed);
  8147. }
  8148. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8149. #ifdef CPPHTTPLIB_SSL_ENABLED
  8150. using ClientT = SSLClient;
  8151. #else
  8152. using ClientT = Client;
  8153. #endif
  8154. TestWithHeadersAndContentReceiverError<ClientT>(
  8155. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8156. const std::string &body, const std::string &content_type,
  8157. ContentReceiver receiver) {
  8158. return cli.Post(path, headers, body, content_type, receiver);
  8159. });
  8160. }
  8161. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8162. #ifdef CPPHTTPLIB_SSL_ENABLED
  8163. using ClientT = SSLClient;
  8164. #else
  8165. using ClientT = Client;
  8166. #endif
  8167. TestWithHeadersAndContentReceiverError<ClientT>(
  8168. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8169. const std::string &body, const std::string &content_type,
  8170. ContentReceiver receiver) {
  8171. return cli.Put(path, headers, body, content_type, receiver);
  8172. });
  8173. }
  8174. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8175. #ifdef CPPHTTPLIB_SSL_ENABLED
  8176. using ClientT = SSLClient;
  8177. #else
  8178. using ClientT = Client;
  8179. #endif
  8180. TestWithHeadersAndContentReceiverError<ClientT>(
  8181. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8182. const std::string &body, const std::string &content_type,
  8183. ContentReceiver receiver) {
  8184. return cli.Patch(path, headers, body, content_type, receiver);
  8185. });
  8186. }
  8187. TEST_F(ServerTest, PostQueryStringAndBody) {
  8188. auto res =
  8189. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8191. ASSERT_EQ(StatusCode::OK_200, res->status);
  8192. }
  8193. TEST_F(ServerTest, HTTP2Magic) {
  8194. Request req;
  8195. req.method = "PRI";
  8196. req.path = "*";
  8197. req.body = "SM";
  8198. auto res = std::make_shared<Response>();
  8199. auto error = Error::Success;
  8200. auto ret = cli_.send(req, *res, error);
  8201. ASSERT_TRUE(ret);
  8202. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8203. }
  8204. TEST_F(ServerTest, KeepAlive) {
  8205. auto res = cli_.Get("/hi");
  8206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8207. EXPECT_EQ(StatusCode::OK_200, res->status);
  8208. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8209. EXPECT_EQ("Hello World!", res->body);
  8210. res = cli_.Get("/hi");
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8214. EXPECT_EQ("Hello World!", res->body);
  8215. res = cli_.Get("/hi");
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::OK_200, res->status);
  8218. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8219. EXPECT_EQ("Hello World!", res->body);
  8220. res = cli_.Get("/not-exist");
  8221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8223. res = cli_.Post("/empty", "", "text/plain");
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ(StatusCode::OK_200, res->status);
  8226. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8227. EXPECT_EQ("empty", res->body);
  8228. EXPECT_EQ("close", res->get_header_value("Connection"));
  8229. res = cli_.Post(
  8230. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8231. "text/plain");
  8232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8233. EXPECT_EQ(StatusCode::OK_200, res->status);
  8234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8235. EXPECT_EQ("empty", res->body);
  8236. cli_.set_keep_alive(false);
  8237. res = cli_.Get("/last-request");
  8238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8239. EXPECT_EQ(StatusCode::OK_200, res->status);
  8240. EXPECT_EQ("close", res->get_header_value("Connection"));
  8241. }
  8242. TEST_F(ServerTest, TooManyRedirect) {
  8243. cli_.set_follow_location(true);
  8244. auto res = cli_.Get("/redirect/0");
  8245. ASSERT_TRUE(!res);
  8246. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8247. }
  8248. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8249. Request req;
  8250. req.method = "FOOBAR";
  8251. req.path = "/hi";
  8252. cli_.set_keep_alive(true);
  8253. auto res = cli_.send(req);
  8254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8255. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8256. EXPECT_EQ("close", res->get_header_value("Connection"));
  8257. EXPECT_FALSE(cli_.is_socket_open());
  8258. }
  8259. TEST_F(ServerTest, CustomRouteReadsBody) {
  8260. const std::string xml =
  8261. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8262. Request req;
  8263. req.method = "PROPFIND";
  8264. req.path = "/dav/dir";
  8265. req.set_header("Depth", "1");
  8266. req.body = xml;
  8267. auto res = cli_.send(req);
  8268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8269. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8270. EXPECT_EQ(xml, res->body);
  8271. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8272. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8273. }
  8274. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8275. Request req;
  8276. req.method = "PROPFIND";
  8277. req.path = "/dav/42";
  8278. auto res = cli_.send(req);
  8279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8280. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8281. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8282. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8283. }
  8284. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8285. Request req;
  8286. req.method = "PROPFIND";
  8287. req.path = "/dav-re/123";
  8288. auto res = cli_.send(req);
  8289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8290. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8291. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8292. }
  8293. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8294. Request req;
  8295. req.method = "MKCOL";
  8296. req.path = "/dav-mkcol";
  8297. auto res = cli_.send(req);
  8298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8299. EXPECT_EQ(StatusCode::Created_201, res->status);
  8300. }
  8301. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8302. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8303. Request req;
  8304. req.method = "REPORT";
  8305. req.path = "/dav-report";
  8306. req.body = xml;
  8307. auto res = cli_.send(req);
  8308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8309. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8310. EXPECT_EQ(xml, res->body);
  8311. }
  8312. // A content reader route must fire even when the request carries no body,
  8313. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8314. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8315. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8316. Request req;
  8317. req.method = "REPORT";
  8318. req.path = "/dav-report";
  8319. auto res = cli_.send(req);
  8320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8321. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8322. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8323. }
  8324. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8325. Request req;
  8326. req.method = "PROPFIND";
  8327. req.path = "/not-dav";
  8328. auto res = cli_.send(req);
  8329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8331. }
  8332. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8333. Request req;
  8334. req.method = "UNLOCK";
  8335. req.path = "/dav/dir";
  8336. cli_.set_keep_alive(true);
  8337. auto res = cli_.send(req);
  8338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8339. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8340. EXPECT_EQ("close", res->get_header_value("Connection"));
  8341. EXPECT_FALSE(cli_.is_socket_open());
  8342. }
  8343. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8344. // The mount point serves this path, but only for GET and HEAD.
  8345. auto get_res = cli_.Get("/dir/index.html");
  8346. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8347. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8348. Request req;
  8349. req.method = "PROPFIND";
  8350. req.path = "/dir/index.html";
  8351. auto res = cli_.send(req);
  8352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8353. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8354. }
  8355. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8356. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8357. cli_.set_keep_alive(true);
  8358. for (auto i = 0; i < 2; i++) {
  8359. Request req;
  8360. req.method = "PROPFIND";
  8361. req.path = "/dav/dir";
  8362. req.body = xml;
  8363. auto res = cli_.send(req);
  8364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8365. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8366. EXPECT_EQ(xml, res->body);
  8367. EXPECT_TRUE(cli_.is_socket_open());
  8368. }
  8369. // A built-in method must still be served on the same connection.
  8370. cli_.set_keep_alive(false);
  8371. auto res = cli_.Get("/hi");
  8372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8373. EXPECT_EQ(StatusCode::OK_200, res->status);
  8374. EXPECT_EQ("close", res->get_header_value("Connection"));
  8375. }
  8376. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8377. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8378. Request req;
  8379. req.method = "PROPFIND";
  8380. req.path = "/dav/dir";
  8381. req.set_header("Expect", "100-continue");
  8382. req.body = xml;
  8383. auto res = cli_.send(req);
  8384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8385. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8386. EXPECT_EQ(xml, res->body);
  8387. }
  8388. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8389. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8390. TEST_F(ServerTest, Gzip) {
  8391. Headers headers;
  8392. headers.emplace("Accept-Encoding", "gzip, deflate");
  8393. auto res = cli_.Get("/compress", headers);
  8394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8395. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8396. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8397. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8398. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8399. "7890123456789012345678901234567890",
  8400. res->body);
  8401. EXPECT_EQ(StatusCode::OK_200, res->status);
  8402. }
  8403. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8404. Headers headers;
  8405. headers.emplace("Accept-Encoding", "gzip, deflate");
  8406. auto res = cli_.Get("/compress-with-charset", headers);
  8407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8408. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8409. EXPECT_EQ("application/json; charset=utf-8",
  8410. res->get_header_value("Content-Type"));
  8411. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8412. "7890123456789012345678901234567890",
  8413. res->body);
  8414. EXPECT_EQ(StatusCode::OK_200, res->status);
  8415. }
  8416. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8417. Headers headers;
  8418. headers.emplace("Accept-Encoding", "");
  8419. auto res = cli_.Get("/compress", headers);
  8420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8421. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8422. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8423. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8424. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8425. "7890123456789012345678901234567890",
  8426. res->body);
  8427. EXPECT_EQ(StatusCode::OK_200, res->status);
  8428. }
  8429. TEST_F(ServerTest, GzipWithContentReceiver) {
  8430. Headers headers;
  8431. headers.emplace("Accept-Encoding", "gzip, deflate");
  8432. std::string body;
  8433. auto res =
  8434. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8435. EXPECT_EQ(100U, data_length);
  8436. body.append(data, data_length);
  8437. return true;
  8438. });
  8439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8440. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8441. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8442. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8443. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8444. "7890123456789012345678901234567890",
  8445. body);
  8446. EXPECT_EQ(StatusCode::OK_200, res->status);
  8447. }
  8448. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8449. Headers headers;
  8450. headers.emplace("Accept-Encoding", "gzip, deflate");
  8451. cli_.set_decompress(false);
  8452. auto res = cli_.Get("/compress", headers);
  8453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8454. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8456. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8457. EXPECT_EQ(33U, res->body.size());
  8458. EXPECT_EQ(StatusCode::OK_200, res->status);
  8459. }
  8460. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8461. Headers headers;
  8462. headers.emplace("Accept-Encoding", "");
  8463. std::string body;
  8464. auto res =
  8465. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8466. EXPECT_EQ(100U, data_length);
  8467. body.append(data, data_length);
  8468. return true;
  8469. });
  8470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8471. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8472. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8473. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8474. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8475. "7890123456789012345678901234567890",
  8476. body);
  8477. EXPECT_EQ(StatusCode::OK_200, res->status);
  8478. }
  8479. TEST_F(ServerTest, NoGzip) {
  8480. Headers headers;
  8481. headers.emplace("Accept-Encoding", "gzip, deflate");
  8482. auto res = cli_.Get("/nocompress", headers);
  8483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8484. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8485. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8486. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8487. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8488. "7890123456789012345678901234567890",
  8489. res->body);
  8490. EXPECT_EQ(StatusCode::OK_200, res->status);
  8491. }
  8492. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8493. Headers headers;
  8494. headers.emplace("Accept-Encoding", "gzip, deflate");
  8495. std::string body;
  8496. auto res = cli_.Get("/nocompress", headers,
  8497. [&](const char *data, size_t data_length) {
  8498. EXPECT_EQ(100U, data_length);
  8499. body.append(data, data_length);
  8500. return true;
  8501. });
  8502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8503. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8504. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8505. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8506. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8507. "7890123456789012345678901234567890",
  8508. body);
  8509. EXPECT_EQ(StatusCode::OK_200, res->status);
  8510. }
  8511. TEST_F(ServerTest, MultipartFormDataGzip) {
  8512. UploadFormDataItems items = {
  8513. {"key1", "test", "", ""},
  8514. {"key2", "--abcdefg123", "", ""},
  8515. };
  8516. cli_.set_compress(true);
  8517. auto res = cli_.Post("/compress-multipart", items);
  8518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8519. EXPECT_EQ(StatusCode::OK_200, res->status);
  8520. }
  8521. #endif
  8522. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8523. // Static file compression is opt-in, so these run their own server rather than
  8524. // flipping it on for the shared ServerTest fixture, which would silently
  8525. // rewrite what every other static file test is asserting.
  8526. class StaticFileCompressionTest : public ::testing::Test {
  8527. protected:
  8528. void TearDown() override {
  8529. if (t_.joinable()) {
  8530. svr_.stop();
  8531. t_.join();
  8532. }
  8533. }
  8534. int start(const std::function<void(Server &)> &configure = nullptr) {
  8535. // Serves the same tree as a directory of build-time compressed assets
  8536. // would be served: the mount point names the coding the files are already
  8537. // stored in. Registered before "/" so it is the one that matches.
  8538. svr_.set_mount_point("/pre-encoded", "./www",
  8539. {{"Content-Encoding", "gzip"}});
  8540. svr_.set_mount_point("/", "./www");
  8541. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8542. res.set_file_content("./www/dir/index.html", "text/html");
  8543. });
  8544. svr_.Get("/pre-encoded-file-content",
  8545. [](const Request & /*req*/, Response &res) {
  8546. res.set_header("Content-Encoding", "gzip");
  8547. res.set_file_content("./www/dir/index.html", "text/html");
  8548. });
  8549. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8550. res.set_content_provider(
  8551. 6, "text/plain",
  8552. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8553. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8554. return true;
  8555. });
  8556. });
  8557. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8558. res.set_content_provider(
  8559. 1000, "text/plain",
  8560. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8561. if (offset < 100) {
  8562. std::string data(100, 'A');
  8563. sink.write(data.data(), data.size());
  8564. return true;
  8565. }
  8566. std::this_thread::sleep_for(std::chrono::seconds(2));
  8567. std::string data(900, 'B');
  8568. sink.write(data.data(), data.size());
  8569. return true;
  8570. });
  8571. });
  8572. if (configure) { configure(svr_); }
  8573. auto port = svr_.bind_to_any_port(HOST);
  8574. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8575. svr_.wait_until_ready();
  8576. return port;
  8577. }
  8578. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8579. // Every file under ./www except 1MB.txt is smaller than the default
  8580. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8581. // it out of the way.
  8582. static void enable_without_floor(Server &svr) {
  8583. svr.set_static_file_compression(true);
  8584. svr.set_static_file_compression_min_length(0);
  8585. }
  8586. Server svr_;
  8587. std::thread t_;
  8588. };
  8589. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8590. auto port = start();
  8591. Client cli(HOST, port);
  8592. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8594. EXPECT_EQ(StatusCode::OK_200, res->status);
  8595. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8596. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8597. EXPECT_EQ(1048576U, res->body.size());
  8598. }
  8599. TEST_F(StaticFileCompressionTest, MountPoint) {
  8600. auto port = start(enable);
  8601. Client cli(HOST, port);
  8602. cli.set_decompress(false);
  8603. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8605. EXPECT_EQ(StatusCode::OK_200, res->status);
  8606. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8607. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8608. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8609. // The response stays self-delimiting: a length, not a chunked body.
  8610. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8611. EXPECT_EQ(std::to_string(res->body.size()),
  8612. res->get_header_value("Content-Length"));
  8613. EXPECT_LT(res->body.size(), 1048576U);
  8614. EXPECT_FALSE(res->body.empty());
  8615. }
  8616. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8617. auto port = start(enable);
  8618. Client cli(HOST, port);
  8619. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8621. EXPECT_EQ(StatusCode::OK_200, res->status);
  8622. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8623. EXPECT_EQ(1048576U, res->body.size());
  8624. }
  8625. TEST_F(StaticFileCompressionTest, FileContent) {
  8626. auto port = start(enable_without_floor);
  8627. Client cli(HOST, port);
  8628. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8630. EXPECT_EQ(StatusCode::OK_200, res->status);
  8631. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8632. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8633. EXPECT_EQ(104U, res->body.size());
  8634. }
  8635. // A handler that serves an already-encoded file names the coding itself. The
  8636. // file-backed path decided its coding from Accept-Encoding and the content
  8637. // type alone, so it compressed the stored bytes a second time and appended a
  8638. // second Content-Encoding field line.
  8639. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8640. auto port = start(enable_without_floor);
  8641. Client cli(HOST, port);
  8642. cli.set_decompress(false);
  8643. auto res = cli.Get("/pre-encoded-file-content",
  8644. Headers{{"Accept-Encoding", "gzip"}});
  8645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8646. EXPECT_EQ(StatusCode::OK_200, res->status);
  8647. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8648. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8649. // Vary belongs to a coding the server chose, and it chose none here.
  8650. EXPECT_FALSE(res->has_header("Vary"));
  8651. // The file travels exactly as it is stored on disk.
  8652. EXPECT_EQ(104U, res->body.size());
  8653. }
  8654. // The 1MB file clears the default floor, so this one runs the configuration a
  8655. // deployment would actually have.
  8656. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8657. auto port = start(enable);
  8658. Client cli(HOST, port);
  8659. cli.set_decompress(false);
  8660. auto res =
  8661. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8663. EXPECT_EQ(StatusCode::OK_200, res->status);
  8664. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8665. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8666. EXPECT_FALSE(res->has_header("Vary"));
  8667. EXPECT_EQ(1048576U, res->body.size());
  8668. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8669. }
  8670. TEST_F(StaticFileCompressionTest, Head) {
  8671. auto port = start(enable);
  8672. Client cli(HOST, port);
  8673. cli.set_decompress(false);
  8674. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8675. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8676. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8678. EXPECT_EQ(StatusCode::OK_200, res->status);
  8679. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8680. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8681. // HEAD still reports the size a GET would return.
  8682. EXPECT_EQ(get->get_header_value("Content-Length"),
  8683. res->get_header_value("Content-Length"));
  8684. EXPECT_TRUE(res->body.empty());
  8685. }
  8686. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8687. auto port = start(enable);
  8688. Client cli(HOST, port);
  8689. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8690. {"Accept-Encoding", "gzip"}});
  8691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8693. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8694. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8695. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8696. EXPECT_EQ("cd", res->body);
  8697. }
  8698. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8699. auto port = start(enable);
  8700. Client cli(HOST, port);
  8701. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8703. EXPECT_EQ(StatusCode::OK_200, res->status);
  8704. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8705. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8706. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8707. }
  8708. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8709. auto port = start(enable);
  8710. Client cli(HOST, port);
  8711. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8713. EXPECT_EQ(StatusCode::OK_200, res->status);
  8714. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8715. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8716. EXPECT_TRUE(res->body.empty());
  8717. }
  8718. TEST_F(StaticFileCompressionTest, MinLength) {
  8719. auto port = start(enable);
  8720. Client cli(HOST, port);
  8721. // 104 bytes, well under the default floor. Compressing it would add the
  8722. // gzip header and trailer to a body that already fits in one packet.
  8723. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8725. EXPECT_EQ(StatusCode::OK_200, res->status);
  8726. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8727. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8728. }
  8729. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8730. auto port = start([](Server &svr) {
  8731. svr.set_static_file_compression(true);
  8732. svr.set_static_file_compression_min_length(1);
  8733. });
  8734. Client cli(HOST, port);
  8735. cli.set_decompress(false);
  8736. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8738. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8739. // A 9-byte file comes back larger than it went in, because gzip's header and
  8740. // trailer outweigh anything deflate can save. That is the end of the range
  8741. // the floor exists to keep out.
  8742. EXPECT_GT(res->body.size(), 9U);
  8743. }
  8744. TEST_F(StaticFileCompressionTest, MaxLength) {
  8745. auto port = start([](Server &svr) {
  8746. svr.set_static_file_compression(true);
  8747. svr.set_static_file_compression_min_length(0);
  8748. svr.set_static_file_compression_max_length(1024);
  8749. });
  8750. Client cli(HOST, port);
  8751. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8752. // defines `small` as a macro on Windows.
  8753. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8754. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8755. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8756. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8757. // Under it: compressed.
  8758. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8759. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8760. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8761. }
  8762. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8763. auto port = start(enable_without_floor);
  8764. Client cli(HOST, port);
  8765. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8766. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8767. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8768. auto identity_etag = identity->get_header_value("ETag");
  8769. ASSERT_FALSE(identity_etag.empty());
  8770. auto gzipped =
  8771. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8772. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8773. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8774. auto gzip_etag = gzipped->get_header_value("ETag");
  8775. ASSERT_FALSE(gzip_etag.empty());
  8776. // Two representations, two validators.
  8777. EXPECT_NE(identity_etag, gzip_etag);
  8778. // Each one revalidates against the request that would produce it...
  8779. auto fresh =
  8780. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8781. {"If-None-Match", gzip_etag}});
  8782. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8783. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8784. auto fresh_identity =
  8785. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8786. {"If-None-Match", identity_etag}});
  8787. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8788. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8789. // ...and not against the other representation.
  8790. auto crossed =
  8791. cli.Get("/dir/index.html",
  8792. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8793. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8794. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8795. }
  8796. // The opt-in covers responses the server reads off disk itself. A caller's own
  8797. // known-length provider keeps its Content-Length and, more importantly, keeps
  8798. // delivering incrementally: routing it through a compressor would hold every
  8799. // write back until zlib's window filled.
  8800. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8801. auto port = start(enable);
  8802. Client cli(HOST, port);
  8803. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8805. EXPECT_EQ(StatusCode::OK_200, res->status);
  8806. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8807. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8808. EXPECT_EQ("aaabbb", res->body);
  8809. }
  8810. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8811. auto port = start(enable);
  8812. Client cli(HOST, port);
  8813. cli.set_read_timeout(1, 0);
  8814. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8815. Headers{{"Accept-Encoding", "gzip"}});
  8816. ASSERT_TRUE(handle.is_valid());
  8817. // The provider writes 100 bytes and then stalls for longer than the read
  8818. // timeout. Those first bytes have to arrive anyway: run the response through
  8819. // a compressor and zlib holds them until its window fills, so the read would
  8820. // come back empty instead.
  8821. char buf[256];
  8822. auto n = handle.read(buf, sizeof(buf));
  8823. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8824. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8825. }
  8826. #endif
  8827. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8828. TEST_F(ServerTest, Brotli) {
  8829. Headers headers;
  8830. headers.emplace("Accept-Encoding", "br");
  8831. auto res = cli_.Get("/compress", headers);
  8832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8833. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8834. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8835. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8836. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8837. "7890123456789012345678901234567890",
  8838. res->body);
  8839. EXPECT_EQ(StatusCode::OK_200, res->status);
  8840. }
  8841. #endif
  8842. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8843. TEST_F(ServerTest, Zstd) {
  8844. Headers headers;
  8845. headers.emplace("Accept-Encoding", "zstd");
  8846. auto res = cli_.Get("/compress", headers);
  8847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8848. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8850. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8851. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8852. "7890123456789012345678901234567890",
  8853. res->body);
  8854. EXPECT_EQ(StatusCode::OK_200, res->status);
  8855. }
  8856. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8857. Headers headers;
  8858. headers.emplace("Accept-Encoding", "");
  8859. auto res = cli_.Get("/compress", headers);
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8862. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8863. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8864. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8865. "7890123456789012345678901234567890",
  8866. res->body);
  8867. EXPECT_EQ(StatusCode::OK_200, res->status);
  8868. }
  8869. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8870. Headers headers;
  8871. headers.emplace("Accept-Encoding", "zstd");
  8872. std::string body;
  8873. auto res =
  8874. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8875. EXPECT_EQ(100U, data_length);
  8876. body.append(data, data_length);
  8877. return true;
  8878. });
  8879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8880. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8881. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8882. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8883. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8884. "7890123456789012345678901234567890",
  8885. body);
  8886. EXPECT_EQ(StatusCode::OK_200, res->status);
  8887. }
  8888. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8889. Headers headers;
  8890. headers.emplace("Accept-Encoding", "zstd");
  8891. cli_.set_decompress(false);
  8892. auto res = cli_.Get("/compress", headers);
  8893. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8894. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8895. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8896. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8898. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8899. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8900. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8901. EXPECT_EQ(StatusCode::OK_200, res->status);
  8902. ASSERT_EQ(26U, res->body.size());
  8903. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8904. 0);
  8905. }
  8906. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8907. Headers headers;
  8908. headers.emplace("Accept-Encoding", "");
  8909. std::string body;
  8910. auto res =
  8911. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8912. EXPECT_EQ(100U, data_length);
  8913. body.append(data, data_length);
  8914. return true;
  8915. });
  8916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8917. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8919. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8920. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8921. "7890123456789012345678901234567890",
  8922. body);
  8923. EXPECT_EQ(StatusCode::OK_200, res->status);
  8924. }
  8925. TEST_F(ServerTest, NoZstd) {
  8926. Headers headers;
  8927. headers.emplace("Accept-Encoding", "zstd");
  8928. auto res = cli_.Get("/nocompress", headers);
  8929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8930. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8931. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8932. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8933. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8934. "7890123456789012345678901234567890",
  8935. res->body);
  8936. EXPECT_EQ(StatusCode::OK_200, res->status);
  8937. }
  8938. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8939. Headers headers;
  8940. headers.emplace("Accept-Encoding", "zstd");
  8941. std::string body;
  8942. auto res = cli_.Get("/nocompress", headers,
  8943. [&](const char *data, size_t data_length) {
  8944. EXPECT_EQ(100U, data_length);
  8945. body.append(data, data_length);
  8946. return true;
  8947. });
  8948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8949. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8950. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8951. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8952. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8953. "7890123456789012345678901234567890",
  8954. body);
  8955. EXPECT_EQ(StatusCode::OK_200, res->status);
  8956. }
  8957. // TODO: How to enable zstd ??
  8958. TEST_F(ServerTest, MultipartFormDataZstd) {
  8959. UploadFormDataItems items = {
  8960. {"key1", "test", "", ""},
  8961. {"key2", "--abcdefg123", "", ""},
  8962. };
  8963. Headers headers;
  8964. headers.emplace("Accept-Encoding", "zstd");
  8965. cli_.set_compress(true);
  8966. auto res = cli_.Post("/compress-multipart", headers, items);
  8967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8968. EXPECT_EQ(StatusCode::OK_200, res->status);
  8969. }
  8970. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8971. Headers headers;
  8972. headers.emplace("Accept-Encoding", "zstd");
  8973. cli_.set_compress(true);
  8974. auto res = cli_.Put(
  8975. "/put", headers, 3,
  8976. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8977. sink.os << "PUT";
  8978. return true;
  8979. },
  8980. "text/plain");
  8981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8982. EXPECT_EQ(StatusCode::OK_200, res->status);
  8983. EXPECT_EQ("PUT", res->body);
  8984. }
  8985. // Pre-compression logging tests
  8986. TEST_F(ServerTest, PreCompressionLogging) {
  8987. // Test data for compression (matches the actual /compress endpoint content)
  8988. const std::string test_content =
  8989. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8990. "3456789012345678901234567890";
  8991. // Variables to capture logging data
  8992. std::string pre_compression_body;
  8993. std::string pre_compression_content_type;
  8994. std::string pre_compression_content_encoding;
  8995. std::string post_compression_body;
  8996. std::string post_compression_content_type;
  8997. std::string post_compression_content_encoding;
  8998. // Set up pre-compression logger
  8999. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9000. const Response &res) {
  9001. pre_compression_body = res.body;
  9002. pre_compression_content_type = res.get_header_value("Content-Type");
  9003. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9004. });
  9005. // Set up post-compression logger
  9006. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9007. post_compression_body = res.body;
  9008. post_compression_content_type = res.get_header_value("Content-Type");
  9009. post_compression_content_encoding =
  9010. res.get_header_value("Content-Encoding");
  9011. });
  9012. // Test with gzip compression
  9013. Headers headers;
  9014. headers.emplace("Accept-Encoding", "gzip");
  9015. auto res = cli_.Get("/compress", headers);
  9016. // Verify response was compressed
  9017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9018. EXPECT_EQ(StatusCode::OK_200, res->status);
  9019. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9020. // Verify pre-compression logger captured uncompressed content
  9021. EXPECT_EQ(test_content, pre_compression_body);
  9022. EXPECT_EQ("text/plain", pre_compression_content_type);
  9023. EXPECT_TRUE(pre_compression_content_encoding
  9024. .empty()); // No encoding header before compression
  9025. // Verify post-compression logger captured compressed content
  9026. EXPECT_NE(test_content,
  9027. post_compression_body); // Should be different after compression
  9028. EXPECT_EQ("text/plain", post_compression_content_type);
  9029. EXPECT_EQ("gzip", post_compression_content_encoding);
  9030. // Verify compressed content is smaller
  9031. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9032. }
  9033. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9034. const std::string test_content =
  9035. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9036. "3456789012345678901234567890";
  9037. std::string pre_compression_body;
  9038. std::string post_compression_body;
  9039. svr_.set_pre_compression_logger(
  9040. [&](const Request & /*req*/, const Response &res) {
  9041. pre_compression_body = res.body;
  9042. });
  9043. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9044. post_compression_body = res.body;
  9045. });
  9046. Headers headers;
  9047. headers.emplace("Accept-Encoding", "br");
  9048. auto res = cli_.Get("/compress", headers);
  9049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9050. EXPECT_EQ(StatusCode::OK_200, res->status);
  9051. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9052. // Verify pre-compression content is uncompressed
  9053. EXPECT_EQ(test_content, pre_compression_body);
  9054. // Verify post-compression content is compressed
  9055. EXPECT_NE(test_content, post_compression_body);
  9056. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9057. }
  9058. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9059. const std::string test_content =
  9060. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9061. "3456789012345678901234567890";
  9062. std::string pre_compression_body;
  9063. std::string post_compression_body;
  9064. svr_.set_pre_compression_logger(
  9065. [&](const Request & /*req*/, const Response &res) {
  9066. pre_compression_body = res.body;
  9067. });
  9068. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9069. post_compression_body = res.body;
  9070. });
  9071. // Request without compression (use /nocompress endpoint)
  9072. Headers headers;
  9073. auto res = cli_.Get("/nocompress", headers);
  9074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9075. EXPECT_EQ(StatusCode::OK_200, res->status);
  9076. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9077. // Pre-compression logger should not be called when no compression is applied
  9078. EXPECT_TRUE(
  9079. pre_compression_body.empty()); // Pre-compression logger not called
  9080. EXPECT_EQ(
  9081. test_content,
  9082. post_compression_body); // Post-compression logger captures final content
  9083. }
  9084. TEST_F(ServerTest, LoggerSeesContentLength) {
  9085. size_t logged_content_length = 0;
  9086. std::string logged_content_length_header;
  9087. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9088. logged_content_length = res.content_length_;
  9089. logged_content_length_header = res.get_header_value("Content-Length");
  9090. });
  9091. auto res = cli_.Get("/nocompress");
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_EQ(StatusCode::OK_200, res->status);
  9094. EXPECT_EQ(res->body.size(), logged_content_length);
  9095. EXPECT_EQ(std::to_string(logged_content_length),
  9096. logged_content_length_header);
  9097. }
  9098. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9099. const std::string test_content =
  9100. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9101. "3456789012345678901234567890";
  9102. std::string pre_compression_body;
  9103. bool pre_logger_called = false;
  9104. // Set only pre-compression logger
  9105. svr_.set_pre_compression_logger(
  9106. [&](const Request & /*req*/, const Response &res) {
  9107. pre_compression_body = res.body;
  9108. pre_logger_called = true;
  9109. });
  9110. Headers headers;
  9111. headers.emplace("Accept-Encoding", "gzip");
  9112. auto res = cli_.Get("/compress", headers);
  9113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9114. EXPECT_EQ(StatusCode::OK_200, res->status);
  9115. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9116. // Verify pre-compression logger was called
  9117. EXPECT_TRUE(pre_logger_called);
  9118. EXPECT_EQ(test_content, pre_compression_body);
  9119. }
  9120. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9121. {
  9122. // Test with Expect: 100-continue header - success case
  9123. // Server returns 100 Continue, client sends body, server returns 200 OK
  9124. Request req;
  9125. req.method = "POST";
  9126. req.path = "/post-large";
  9127. req.set_header("Expect", "100-continue");
  9128. req.body = LARGE_DATA;
  9129. Response res;
  9130. auto error = Error::Success;
  9131. cli_.set_keep_alive(true);
  9132. auto ret = cli_.send(req, res, error);
  9133. EXPECT_TRUE(ret);
  9134. EXPECT_EQ(StatusCode::OK_200, res.status);
  9135. EXPECT_EQ(LARGE_DATA, res.body);
  9136. }
  9137. {
  9138. // Test with Expect: 100-continue header - error case
  9139. // Client should not send the body when server returns an error
  9140. Request req;
  9141. req.method = "POST";
  9142. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9143. req.set_header("Expect", "100-continue");
  9144. req.body = LARGE_DATA;
  9145. Response res;
  9146. auto error = Error::Success;
  9147. auto start = std::chrono::high_resolution_clock::now();
  9148. cli_.set_keep_alive(true);
  9149. auto ret = cli_.send(req, res, error);
  9150. auto end = std::chrono::high_resolution_clock::now();
  9151. auto elapsed =
  9152. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9153. .count();
  9154. // With Expect: 100-continue, request completes successfully but with error
  9155. EXPECT_TRUE(ret);
  9156. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9157. EXPECT_EQ("close", res.get_header_value("Connection"));
  9158. EXPECT_FALSE(cli_.is_socket_open());
  9159. EXPECT_LE(elapsed, 2000);
  9160. }
  9161. {
  9162. // Send an extra GET request to ensure error recovery without hanging
  9163. Request req;
  9164. req.method = "GET";
  9165. req.path = "/hi";
  9166. auto start = std::chrono::high_resolution_clock::now();
  9167. auto res = cli_.send(req);
  9168. auto end = std::chrono::high_resolution_clock::now();
  9169. auto elapsed =
  9170. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9171. .count();
  9172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9173. EXPECT_EQ(StatusCode::OK_200, res->status);
  9174. EXPECT_EQ("Hello World!", res->body);
  9175. EXPECT_LE(elapsed, 500);
  9176. }
  9177. }
  9178. TEST(ZstdDecompressor, ChunkedDecompression) {
  9179. std::string data;
  9180. for (size_t i = 0; i < 32 * 1024; ++i) {
  9181. data.push_back(static_cast<char>('a' + i % 26));
  9182. }
  9183. std::string compressed_data;
  9184. {
  9185. httplib::detail::zstd_compressor compressor;
  9186. bool result = compressor.compress(
  9187. data.data(), data.size(),
  9188. /*last=*/true,
  9189. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9190. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9191. compressed_data_size);
  9192. return true;
  9193. });
  9194. ASSERT_TRUE(result);
  9195. }
  9196. std::string decompressed_data;
  9197. {
  9198. httplib::detail::zstd_decompressor decompressor;
  9199. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9200. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9201. size_t chunk_size = 130;
  9202. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9203. chunk_begin += chunk_size) {
  9204. size_t current_chunk_size =
  9205. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9206. bool result = decompressor.decompress(
  9207. compressed_data.data() + chunk_begin, current_chunk_size,
  9208. [&](const char *decompressed_data_chunk,
  9209. size_t decompressed_data_chunk_size) {
  9210. decompressed_data.insert(decompressed_data.size(),
  9211. decompressed_data_chunk,
  9212. decompressed_data_chunk_size);
  9213. return true;
  9214. });
  9215. ASSERT_TRUE(result);
  9216. }
  9217. }
  9218. ASSERT_EQ(data, decompressed_data);
  9219. }
  9220. TEST(ZstdDecompressor, Decompress) {
  9221. std::string original_text = "Compressed with ZSTD";
  9222. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9223. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9224. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9225. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9226. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9227. std::string decompressed_data;
  9228. {
  9229. httplib::detail::zstd_decompressor decompressor;
  9230. bool result = decompressor.decompress(
  9231. compressed_data.data(), compressed_data.size(),
  9232. [&](const char *decompressed_data_chunk,
  9233. size_t decompressed_data_chunk_size) {
  9234. decompressed_data.insert(decompressed_data.size(),
  9235. decompressed_data_chunk,
  9236. decompressed_data_chunk_size);
  9237. return true;
  9238. });
  9239. ASSERT_TRUE(result);
  9240. }
  9241. ASSERT_EQ(original_text, decompressed_data);
  9242. }
  9243. #endif
  9244. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9245. // separate chunks so that the server sees each part in its own read(). Used to
  9246. // place a read boundary at a specific offset of a request body.
  9247. static bool send_request_in_parts(time_t read_timeout_sec,
  9248. const std::vector<std::string> &parts,
  9249. std::string *resp = nullptr,
  9250. int port = PORT) {
  9251. auto error = Error::Success;
  9252. auto client_sock = detail::create_client_socket(
  9253. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9254. /*connection_timeout_sec=*/5, 0,
  9255. /*read_timeout_sec=*/5, 0,
  9256. /*write_timeout_sec=*/5, 0, std::string(), error);
  9257. if (client_sock == INVALID_SOCKET) { return false; }
  9258. auto ret = detail::process_client_socket(
  9259. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9260. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9261. for (size_t i = 0; i < parts.size(); i++) {
  9262. const auto &part = parts[i];
  9263. if (part.size() !=
  9264. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9265. return false;
  9266. }
  9267. if (i + 1 < parts.size()) {
  9268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9269. }
  9270. }
  9271. char buf[512];
  9272. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9273. while (line_reader.getline()) {
  9274. if (resp) { *resp += line_reader.ptr(); }
  9275. }
  9276. return true;
  9277. });
  9278. detail::close_socket(client_sock);
  9279. return ret;
  9280. }
  9281. // Sends a raw request to a server listening at HOST:PORT.
  9282. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9283. std::string *resp = nullptr, int port = PORT) {
  9284. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9285. }
  9286. #ifdef CPPHTTPLIB_SSL_ENABLED
  9287. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9289. ASSERT_TRUE(svr.is_valid());
  9290. svr.set_read_timeout(1, 0);
  9291. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9292. auto se = detail::scope_exit([&] {
  9293. svr.stop();
  9294. t.join();
  9295. ASSERT_FALSE(svr.is_running());
  9296. });
  9297. svr.wait_until_ready();
  9298. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9299. // keeps each wait well within the read timeout. The server gives up a
  9300. // second in, so the bytes sent after that fail.
  9301. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9302. parts.resize(26, std::string(1, '\0'));
  9303. EXPECT_FALSE(send_request_in_parts(5, parts));
  9304. }
  9305. #endif
  9306. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9307. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9308. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9309. const std::vector<std::string> &parts,
  9310. std::string *resp = nullptr,
  9311. int port = PORT) {
  9312. auto error = Error::Success;
  9313. auto sock = detail::create_client_socket(
  9314. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9315. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9316. /*write_timeout_sec=*/5, 0, std::string(), error);
  9317. if (sock == INVALID_SOCKET) { return false; }
  9318. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9319. auto ctx = SSL_CTX_new(TLS_client_method());
  9320. auto ssl = SSL_new(ctx);
  9321. auto ssl_se = detail::scope_exit([&] {
  9322. SSL_free(ssl);
  9323. SSL_CTX_free(ctx);
  9324. });
  9325. SSL_set_fd(ssl, static_cast<int>(sock));
  9326. if (SSL_connect(ssl) != 1) { return false; }
  9327. for (size_t i = 0; i < parts.size(); i++) {
  9328. const auto &part = parts[i];
  9329. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9330. static_cast<int>(part.size())) {
  9331. return false;
  9332. }
  9333. if (i + 1 < parts.size()) {
  9334. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9335. }
  9336. }
  9337. char buf[512];
  9338. int n;
  9339. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9340. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9341. }
  9342. return true;
  9343. }
  9344. #endif
  9345. // The request line, then a header value a byte at a time.
  9346. static std::vector<std::string> slow_request_head_parts() {
  9347. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9348. parts.resize(26, "a");
  9349. parts.emplace_back("\r\n\r\n");
  9350. return parts;
  9351. }
  9352. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9353. // within the one-second read timeout. The server gives up a second in, before
  9354. // the head is complete.
  9355. static void
  9356. expect_slow_request_head_dropped(Server &svr,
  9357. const std::function<std::string()> &send) {
  9358. std::atomic<bool> handled(false);
  9359. svr.Get("/", [&](const Request &, Response &res) {
  9360. handled = true;
  9361. res.set_content("ok", "text/plain");
  9362. });
  9363. svr.set_read_timeout(1, 0);
  9364. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9365. auto se = detail::scope_exit([&] {
  9366. svr.stop();
  9367. t.join();
  9368. ASSERT_FALSE(svr.is_running());
  9369. });
  9370. svr.wait_until_ready();
  9371. auto resp = send();
  9372. EXPECT_FALSE(handled);
  9373. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9374. }
  9375. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9376. Server svr;
  9377. expect_slow_request_head_dropped(svr, [] {
  9378. std::string resp;
  9379. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9380. return resp;
  9381. });
  9382. }
  9383. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9384. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9385. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9386. ASSERT_TRUE(svr.is_valid());
  9387. expect_slow_request_head_dropped(svr, [] {
  9388. std::string resp;
  9389. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9390. return resp;
  9391. });
  9392. }
  9393. #endif
  9394. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9395. Server svr;
  9396. std::string header_value;
  9397. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9398. header_value = req.get_header_value("foo");
  9399. res.set_content("ok", "text/plain");
  9400. });
  9401. thread t = thread([&] { svr.listen(HOST, PORT); });
  9402. auto se = detail::scope_exit([&] {
  9403. svr.stop();
  9404. t.join();
  9405. ASSERT_FALSE(svr.is_running());
  9406. });
  9407. svr.wait_until_ready();
  9408. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9409. // like characters are not treated the same - use vertical tab and escape.
  9410. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9411. "foo: \t \v bar \x1B\t \r\n"
  9412. "Connection: close\r\n"
  9413. "\r\n";
  9414. std::string res;
  9415. ASSERT_TRUE(send_request(5, req, &res));
  9416. EXPECT_EQ(header_value, "");
  9417. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9418. }
  9419. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9420. Server svr;
  9421. std::string received;
  9422. svr.Get("/order", [&](const Request &req, Response &res) {
  9423. received = entries_to_string(req.headers);
  9424. res.set_content("ok", "text/plain");
  9425. });
  9426. auto port = svr.bind_to_any_port(HOST);
  9427. thread t = thread([&] { svr.listen_after_bind(); });
  9428. auto se = detail::scope_exit([&] {
  9429. svr.stop();
  9430. t.join();
  9431. ASSERT_FALSE(svr.is_running());
  9432. });
  9433. svr.wait_until_ready();
  9434. const std::string req = "GET /order HTTP/1.1\r\n"
  9435. "Host: localhost\r\n"
  9436. "X-First: 1\r\n"
  9437. "X-Dup: a\r\n"
  9438. "X-Second: 2\r\n"
  9439. "X-Dup: b\r\n"
  9440. "Connection: close\r\n"
  9441. "\r\n";
  9442. std::string res;
  9443. ASSERT_TRUE(send_request(5, req, &res, port));
  9444. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9445. EXPECT_EQ(
  9446. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9447. received);
  9448. }
  9449. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9450. Server svr;
  9451. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9452. res.set_header("Set-Cookie", "first=1");
  9453. res.set_header("X-Between", "y");
  9454. res.set_header("Set-Cookie", "second=2");
  9455. res.set_content("ok", "text/plain");
  9456. });
  9457. auto port = svr.bind_to_any_port(HOST);
  9458. thread t = thread([&] { svr.listen_after_bind(); });
  9459. auto se = detail::scope_exit([&] {
  9460. svr.stop();
  9461. t.join();
  9462. ASSERT_FALSE(svr.is_running());
  9463. });
  9464. svr.wait_until_ready();
  9465. Client cli(HOST, port);
  9466. auto res = cli.Get("/cookies");
  9467. ASSERT_TRUE(res);
  9468. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9469. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9470. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9471. }
  9472. // A stream may send a byte at a time with a small extension on each chunk,
  9473. // however long it runs
  9474. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9475. Server svr;
  9476. svr.Post("/count", [](const Request &req, Response &res) {
  9477. res.set_content(std::to_string(req.body.size()), "text/plain");
  9478. });
  9479. auto port = svr.bind_to_any_port(HOST);
  9480. ASSERT_LT(0, port);
  9481. thread t = thread([&] { svr.listen_after_bind(); });
  9482. auto se = detail::scope_exit([&] {
  9483. svr.stop();
  9484. t.join();
  9485. ASSERT_FALSE(svr.is_running());
  9486. });
  9487. svr.wait_until_ready();
  9488. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9489. "\r\nTransfer-Encoding: chunked\r\n"
  9490. "Connection: close\r\n\r\n";
  9491. for (auto i = 0; i < 4096; i++) {
  9492. req += "1;a=b\r\nx\r\n";
  9493. }
  9494. req += "0\r\n\r\n";
  9495. std::string res;
  9496. ASSERT_TRUE(send_request(5, req, &res, port));
  9497. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9498. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9499. }
  9500. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9501. Server svr;
  9502. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9503. auto i = new int(0);
  9504. res.set_header("Trailer", "X-Safe, X-Reflected");
  9505. res.set_chunked_content_provider(
  9506. "text/plain",
  9507. [i](size_t /*offset*/, DataSink &sink) {
  9508. if (*i == 0) {
  9509. sink.os << "body";
  9510. } else {
  9511. Headers trailer;
  9512. // A valid trailer that must survive.
  9513. trailer.emplace("X-Safe", "safe");
  9514. // Attacker-controlled value carrying CR/LF (response splitting).
  9515. trailer.emplace("X-Reflected",
  9516. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9517. // Attacker-controlled name carrying CR/LF.
  9518. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9519. sink.done_with_trailer(trailer);
  9520. }
  9521. (*i)++;
  9522. return true;
  9523. },
  9524. [i](bool /*success*/) { delete i; });
  9525. });
  9526. thread t = thread([&] { svr.listen(HOST, PORT); });
  9527. auto se = detail::scope_exit([&] {
  9528. svr.stop();
  9529. t.join();
  9530. ASSERT_FALSE(svr.is_running());
  9531. });
  9532. svr.wait_until_ready();
  9533. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9534. "Host: " + HOST +
  9535. "\r\n"
  9536. "Connection: close\r\n"
  9537. "\r\n";
  9538. std::string res;
  9539. ASSERT_TRUE(send_request(5, req, &res));
  9540. // The injected fields must not appear anywhere in the raw response.
  9541. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9542. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9543. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9544. // Invalid trailers are dropped entirely, matching set_header().
  9545. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9546. // The valid trailer still passes through.
  9547. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9548. }
  9549. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9550. // A custom header writer gets only the fields the default one writes
  9551. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9552. std::string s;
  9553. for (const auto &h : hdrs) {
  9554. s += h.first + ": " + h.second + "\r\n";
  9555. }
  9556. s += "\r\n";
  9557. return strm.write(s.data(), s.size());
  9558. };
  9559. for (auto custom_writer : {false, true}) {
  9560. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9561. Server svr;
  9562. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9563. svr.set_post_routing_handler([](const Request &, Response &res) {
  9564. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9565. });
  9566. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9567. // res.headers is a public field an application can populate directly,
  9568. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9569. // A valid header that must survive.
  9570. res.headers.emplace("X-Safe", "safe");
  9571. // Attacker-controlled value carrying CR/LF (response splitting).
  9572. res.headers.emplace("X-Reflected",
  9573. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9574. // Attacker-controlled name carrying CR/LF.
  9575. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9576. res.set_content("body", "text/plain");
  9577. });
  9578. thread t = thread([&] { svr.listen(HOST, PORT); });
  9579. auto se = detail::scope_exit([&] {
  9580. svr.stop();
  9581. t.join();
  9582. ASSERT_FALSE(svr.is_running());
  9583. });
  9584. svr.wait_until_ready();
  9585. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9586. "Host: " + HOST +
  9587. "\r\n"
  9588. "Connection: close\r\n"
  9589. "\r\n";
  9590. std::string res;
  9591. ASSERT_TRUE(send_request(5, req, &res));
  9592. // The injected fields must not appear anywhere in the raw response.
  9593. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9594. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9595. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9596. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9597. // Invalid headers are dropped entirely, matching set_header().
  9598. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9599. // The valid header still passes through.
  9600. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9601. }
  9602. }
  9603. // Forward declaration: in split builds split.py strips `inline` and moves the
  9604. // definition into httplib.cc, so detail::write_request_line is not visible from
  9605. // the public httplib.h. Re-declaring it here lets the tests link against the
  9606. // symbol in both header-only and split builds.
  9607. namespace httplib {
  9608. namespace detail {
  9609. ssize_t write_request_line(Stream &strm, const std::string &method,
  9610. const std::string &path);
  9611. } // namespace detail
  9612. } // namespace httplib
  9613. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9614. // A well-formed target is written verbatim.
  9615. {
  9616. detail::BufferStream strm;
  9617. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9618. EXPECT_GT(n, 0);
  9619. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9620. }
  9621. // A target carrying CR/LF, SP or other control octets must be rejected
  9622. // before anything reaches the wire, otherwise it splits the request line and
  9623. // injects a header or a whole request.
  9624. const std::string evil_targets[] = {
  9625. "/a\r\nInjected: pwned",
  9626. "/a\rInjected",
  9627. "/a\nInjected",
  9628. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9629. "/a b",
  9630. "/a\tb",
  9631. "/a\x7f",
  9632. };
  9633. for (const auto &evil : evil_targets) {
  9634. detail::BufferStream strm;
  9635. auto n = detail::write_request_line(strm, "GET", evil);
  9636. EXPECT_LT(n, 0);
  9637. EXPECT_TRUE(strm.get_buffer().empty());
  9638. }
  9639. }
  9640. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9641. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9642. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9643. // target reaches write_request. The client must fail cleanly with
  9644. // Error::Write instead of putting a request-line-less, header-injecting
  9645. // request on the wire.
  9646. Server svr;
  9647. svr.Get("/a", [](const Request &, Response &res) {
  9648. res.set_content("ok", "text/plain");
  9649. });
  9650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9651. auto se = detail::scope_exit([&] {
  9652. svr.stop();
  9653. thread.join();
  9654. ASSERT_FALSE(svr.is_running());
  9655. });
  9656. svr.wait_until_ready();
  9657. {
  9658. Client cli(HOST, PORT);
  9659. cli.set_path_encode(false);
  9660. // The request is rejected before anything is written, so the connection
  9661. // stays silent and the subsequent response read would otherwise block for
  9662. // the full default read timeout. Shorten it -- the assertion is on the
  9663. // error, not the timeout.
  9664. cli.set_read_timeout(1, 0);
  9665. auto res = cli.Get("/a\r\nInjected: pwned");
  9666. EXPECT_FALSE(res);
  9667. EXPECT_EQ(Error::Write, res.error());
  9668. }
  9669. }
  9670. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9671. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9672. // including extension methods.
  9673. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9674. for (const auto &method : good_methods) {
  9675. detail::BufferStream strm;
  9676. auto n = detail::write_request_line(strm, method, "/");
  9677. EXPECT_GT(n, 0);
  9678. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9679. }
  9680. // A method carrying CR/LF would split the request line and smuggle a whole
  9681. // request ahead of the real one. A space or an empty method corrupts the
  9682. // request line. All must be rejected before anything reaches the wire.
  9683. const std::string evil_methods[] = {
  9684. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9685. "GET\r\nInjected: pwned",
  9686. "GET\r",
  9687. "GET\n",
  9688. "GE T",
  9689. "",
  9690. };
  9691. for (const auto &evil : evil_methods) {
  9692. detail::BufferStream strm;
  9693. auto n = detail::write_request_line(strm, evil, "/");
  9694. EXPECT_LT(n, 0);
  9695. EXPECT_TRUE(strm.get_buffer().empty());
  9696. }
  9697. }
  9698. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9699. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9700. // through Client::send must fail with Error::Write and no request, neither
  9701. // the smuggled one nor the real one, may reach the server.
  9702. Server svr;
  9703. std::atomic<int> request_count(0);
  9704. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9705. request_count++;
  9706. res.status = StatusCode::OK_200;
  9707. return Server::HandlerResponse::Handled;
  9708. });
  9709. auto port = svr.bind_to_any_port(HOST);
  9710. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9711. auto se = detail::scope_exit([&] {
  9712. svr.stop();
  9713. thread.join();
  9714. ASSERT_FALSE(svr.is_running());
  9715. });
  9716. svr.wait_until_ready();
  9717. {
  9718. Client cli(HOST, port);
  9719. const std::string evil_methods[] = {
  9720. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9721. "GE T",
  9722. "",
  9723. };
  9724. for (const auto &evil : evil_methods) {
  9725. Request req;
  9726. req.method = evil;
  9727. req.path = "/";
  9728. auto res = cli.send(req);
  9729. EXPECT_FALSE(res);
  9730. EXPECT_EQ(Error::Write, res.error());
  9731. }
  9732. auto handle =
  9733. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9734. EXPECT_FALSE(handle.is_valid());
  9735. EXPECT_EQ(Error::Write, handle.error);
  9736. // A valid request on the same client still goes through.
  9737. auto res = cli.Get("/");
  9738. ASSERT_TRUE(res);
  9739. EXPECT_EQ(StatusCode::OK_200, res->status);
  9740. }
  9741. EXPECT_EQ(1, request_count.load());
  9742. }
  9743. // Sends a raw request and verifies that there isn't a crash or exception.
  9744. static void test_raw_request(const std::string &req,
  9745. std::string *out = nullptr) {
  9746. Server svr;
  9747. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9748. res.set_content("ok", "text/plain");
  9749. });
  9750. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9751. res.set_content("ok", "text/plain");
  9752. });
  9753. svr.Get("/header_field_value_check",
  9754. [&](const Request & /*req*/, Response &res) {
  9755. res.set_content("ok", "text/plain");
  9756. });
  9757. svr.CustomRoute("PROPFIND", "/dav",
  9758. [&](const Request & /*req*/, Response &res) {
  9759. res.status = StatusCode::MultiStatus_207;
  9760. });
  9761. // Server read timeout must be longer than the client read timeout for the
  9762. // bug to reproduce, probably to force the server to process a request
  9763. // without a trailing blank line.
  9764. const time_t client_read_timeout_sec = 1;
  9765. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9766. bool listen_thread_ok = false;
  9767. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9768. auto se = detail::scope_exit([&] {
  9769. svr.stop();
  9770. t.join();
  9771. ASSERT_FALSE(svr.is_running());
  9772. EXPECT_TRUE(listen_thread_ok);
  9773. });
  9774. svr.wait_until_ready();
  9775. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9776. }
  9777. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9778. // A certain header line causes an exception if the header property is parsed
  9779. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9780. test_raw_request(
  9781. "GET /hi HTTP/1.1\r\n"
  9782. " : "
  9783. " "
  9784. " ");
  9785. }
  9786. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9787. // A certain header line causes an exception if the header property *name* is
  9788. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9789. // greedy matcher and requires backtracking when there are a lot of ":"
  9790. // characters.
  9791. // This occurs with libc++ but not libstdc++.
  9792. test_raw_request(
  9793. "GET /hi HTTP/1.1\r\n"
  9794. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9795. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9796. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9797. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9798. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9799. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9800. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9801. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9802. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9803. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9804. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9805. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9806. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9807. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9808. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9809. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9810. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9811. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9812. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9813. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9814. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9815. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9816. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9817. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9818. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9819. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9820. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9821. "&&&%%%");
  9822. }
  9823. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9824. // Make sure this doesn't crash the server.
  9825. // In a previous version of the header line regex, the "\r" rendered the line
  9826. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9827. // a new position where the leading white space ended and the field value
  9828. // began.
  9829. // The crash occurs with libc++ but not libstdc++.
  9830. test_raw_request("GET /hi HTTP/1.1\r\n"
  9831. "a:" +
  9832. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9833. "\r\n"
  9834. "\r\n");
  9835. }
  9836. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9837. const char *rejected[] = {
  9838. // RFC 9112 §3: one SP between the parts, and nothing else
  9839. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9840. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9841. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9842. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9843. // A request-target has no fragment
  9844. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9845. // An HTTP/1.1 request needs a Host
  9846. "GET /hi HTTP/1.1\r\n\r\n",
  9847. };
  9848. for (auto request : rejected) {
  9849. std::string out;
  9850. test_raw_request(request, &out);
  9851. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9852. }
  9853. std::string out;
  9854. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9855. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9856. }
  9857. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9858. // RFC 9112 §6.1
  9859. const char *requests[] = {
  9860. "PUT /put_hi HTTP/1.1\r\n"
  9861. "Host: localhost\r\n"
  9862. "Content-Length: 0\r\n"
  9863. "Transfer-Encoding: chunked\r\n"
  9864. "\r\n"
  9865. "0\r\n\r\n",
  9866. "PUT /put_hi HTTP/1.0\r\n"
  9867. "Connection: keep-alive\r\n"
  9868. "Transfer-Encoding: chunked\r\n"
  9869. "\r\n"
  9870. "0\r\n\r\n",
  9871. };
  9872. for (auto request : requests) {
  9873. std::string out;
  9874. test_raw_request(request, &out);
  9875. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9876. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9877. }
  9878. }
  9879. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9880. std::string out;
  9881. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9882. "Content-Type: text/plain\r\n"
  9883. "Transfer-Encoding: chunked\r\n"
  9884. "\r\n"
  9885. "nothex\r\n",
  9886. &out);
  9887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9888. }
  9889. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9890. std::string out;
  9891. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9892. "Content-Type: text/plain\r\n"
  9893. "Transfer-Encoding: chunked\r\n"
  9894. "\r\n"
  9895. "3\r\n"
  9896. "xyz\r\n"
  9897. "NaN\r\n",
  9898. &out);
  9899. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9900. }
  9901. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9902. std::string out;
  9903. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9904. "Content-Type: text/plain\r\n"
  9905. "Transfer-Encoding: chunked\r\n"
  9906. "\r\n"
  9907. // Length is too large for 64 bits.
  9908. "1ffffffffffffffff\r\n"
  9909. "xyz\r\n",
  9910. &out);
  9911. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9912. }
  9913. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9914. test_raw_request("GET /hi HTTP/1.1\r\n"
  9915. "Content-Type: text/plain\r\n\r");
  9916. }
  9917. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9918. std::string out;
  9919. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9920. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9921. }
  9922. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9923. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9924. std::string out;
  9925. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9926. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9927. }
  9928. }
  9929. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9930. std::string out;
  9931. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9932. "Host: localhost\r\n"
  9933. "Connection: close\r\n\r\n",
  9934. &out);
  9935. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9936. }
  9937. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9938. Server svr;
  9939. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9940. EXPECT_TRUE(!req.remote_addr.empty());
  9941. });
  9942. thread t = thread([&] { svr.listen(HOST, PORT); });
  9943. auto se = detail::scope_exit([&] {
  9944. svr.stop();
  9945. t.join();
  9946. ASSERT_FALSE(svr.is_running());
  9947. });
  9948. svr.wait_until_ready();
  9949. // Send an invalid request line to trigger Bad Request
  9950. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9951. std::string out;
  9952. ASSERT_TRUE(send_request(5, bad_req, &out));
  9953. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9954. }
  9955. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9956. // answered right away rather than blocking on a read that waits for EOF.
  9957. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9958. std::string out;
  9959. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9960. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9961. }
  9962. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9963. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9964. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9965. for (const auto *method : methods) {
  9966. Server svr;
  9967. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9968. EXPECT_FALSE(svr.is_valid()) << method;
  9969. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9970. }
  9971. }
  9972. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9973. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9974. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9975. for (const auto *method : methods) {
  9976. Server svr;
  9977. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9978. EXPECT_FALSE(svr.is_valid()) << method;
  9979. }
  9980. }
  9981. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9982. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9983. "COPY", "MOVE", "LOCK",
  9984. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9985. Server svr;
  9986. for (const auto *method : methods) {
  9987. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9988. }
  9989. EXPECT_TRUE(svr.is_valid());
  9990. }
  9991. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9992. Server svr;
  9993. svr.CustomRoute("POST", "/x",
  9994. [](const Request &, Response &, const ContentReader &) {});
  9995. EXPECT_FALSE(svr.is_valid());
  9996. }
  9997. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9998. Server svr;
  9999. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10000. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10001. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10002. EXPECT_FALSE(svr.is_valid());
  10003. }
  10004. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10005. Server svr;
  10006. auto captured = Error::Success;
  10007. svr.set_error_logger(
  10008. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10009. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10010. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10011. }
  10012. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10013. std::string out;
  10014. std::string request(
  10015. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10016. test_raw_request(request, &out);
  10017. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10018. }
  10019. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10020. std::string out;
  10021. std::string request(
  10022. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10023. test_raw_request(request, &out);
  10024. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10025. }
  10026. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10027. std::string out;
  10028. std::string request(
  10029. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10030. test_raw_request(request, &out);
  10031. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10032. }
  10033. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10034. std::string out;
  10035. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10036. "Host: localhost\r\n"
  10037. "Test: \r\n\r\n",
  10038. &out);
  10039. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10040. }
  10041. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10042. Server svr;
  10043. std::string x_custom;
  10044. std::string cookie;
  10045. std::string xff;
  10046. std::string x_unicode;
  10047. std::string x_iis;
  10048. svr.Get("/check", [&](const Request &req, Response &res) {
  10049. x_custom = req.get_header_value("X-Custom");
  10050. cookie = req.get_header_value("Cookie");
  10051. xff = req.get_header_value("X-Forwarded-For");
  10052. x_unicode = req.get_header_value("X-Unicode");
  10053. x_iis = req.get_header_value("X-IIS");
  10054. res.set_content("ok", "text/plain");
  10055. });
  10056. thread t = thread([&] { svr.listen(HOST, PORT); });
  10057. auto se = detail::scope_exit([&] {
  10058. svr.stop();
  10059. t.join();
  10060. ASSERT_FALSE(svr.is_running());
  10061. });
  10062. svr.wait_until_ready();
  10063. const std::string req = "GET /check HTTP/1.1\r\n"
  10064. "Host: localhost\r\n"
  10065. "X-Custom: a%0D%0AInjected: b\r\n"
  10066. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10067. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10068. "X-Unicode: %E3%81%82\r\n"
  10069. "X-IIS: %u00E9\r\n"
  10070. "Connection: close\r\n"
  10071. "\r\n";
  10072. std::string res;
  10073. ASSERT_TRUE(send_request(5, req, &res));
  10074. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10075. // Every value must be returned verbatim (wire form), with no decoding.
  10076. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10077. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10078. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10079. EXPECT_EQ("%E3%81%82", x_unicode);
  10080. EXPECT_EQ("%u00E9", x_iis);
  10081. }
  10082. // Applications that previously relied on automatic percent-decoding can
  10083. // reproduce the old behavior by explicitly calling decode_path_component()
  10084. // or, for RFC 3986 conformance, decode_uri_component().
  10085. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10086. Server svr;
  10087. std::string decoded;
  10088. svr.Get("/check", [&](const Request &req, Response &res) {
  10089. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10090. res.set_content("ok", "text/plain");
  10091. });
  10092. thread t = thread([&] { svr.listen(HOST, PORT); });
  10093. auto se = detail::scope_exit([&] {
  10094. svr.stop();
  10095. t.join();
  10096. ASSERT_FALSE(svr.is_running());
  10097. });
  10098. svr.wait_until_ready();
  10099. const std::string req = "GET /check HTTP/1.1\r\n"
  10100. "Host: localhost\r\n"
  10101. "X-Custom: hello%20world\r\n"
  10102. "Connection: close\r\n"
  10103. "\r\n";
  10104. std::string res;
  10105. ASSERT_TRUE(send_request(5, req, &res));
  10106. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10107. EXPECT_EQ("hello world", decoded);
  10108. }
  10109. // Regression test for #2033. Browsers send Referer values that include
  10110. // percent-encoded characters such as %0A inside the URL. Decoding the
  10111. // header value would either trip the post-decode CR/LF/NUL guard (the
  10112. // original bug, returning 400) or, after that guard was relaxed, silently
  10113. // store a literal LF — both unacceptable. The wire form must round-trip.
  10114. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10115. Server svr;
  10116. std::string referer;
  10117. svr.Get("/check", [&](const Request &req, Response &res) {
  10118. referer = req.get_header_value("Referer");
  10119. res.set_content("ok", "text/plain");
  10120. });
  10121. thread t = thread([&] { svr.listen(HOST, PORT); });
  10122. auto se = detail::scope_exit([&] {
  10123. svr.stop();
  10124. t.join();
  10125. ASSERT_FALSE(svr.is_running());
  10126. });
  10127. svr.wait_until_ready();
  10128. const std::string req = "GET /check HTTP/1.1\r\n"
  10129. "Host: localhost\r\n"
  10130. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10131. "Connection: close\r\n"
  10132. "\r\n";
  10133. std::string res;
  10134. ASSERT_TRUE(send_request(5, req, &res));
  10135. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10136. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10137. }
  10138. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10139. Server svr;
  10140. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10141. res.set_header("Cache-Control", "no-cache");
  10142. res.set_chunked_content_provider(
  10143. "text/event-stream", [](size_t offset, DataSink &sink) {
  10144. std::string s = "data:";
  10145. s += std::to_string(offset);
  10146. s += "\n\n";
  10147. auto ret = sink.write(s.data(), s.size());
  10148. EXPECT_TRUE(ret);
  10149. std::this_thread::sleep_for(std::chrono::seconds(1));
  10150. return true;
  10151. });
  10152. });
  10153. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10154. svr.wait_until_ready();
  10155. Client client(HOST, PORT);
  10156. const Headers headers = {{"Accept", "text/event-stream"}};
  10157. auto get_thread = std::thread([&client, &headers]() {
  10158. auto res = client.Get(
  10159. "/events", headers,
  10160. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10161. });
  10162. auto se = detail::scope_exit([&] {
  10163. svr.stop();
  10164. get_thread.join();
  10165. listen_thread.join();
  10166. ASSERT_FALSE(svr.is_running());
  10167. });
  10168. // Give GET time to get a few messages.
  10169. std::this_thread::sleep_for(std::chrono::seconds(2));
  10170. }
  10171. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10172. httplib::Server svr;
  10173. svr.Post("/hi",
  10174. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10175. res.status = StatusCode::OK_200;
  10176. });
  10177. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10178. svr.wait_until_ready();
  10179. Client cli(HOST, PORT);
  10180. auto res = cli.Post("/hi", "data", "text/plain");
  10181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10182. EXPECT_EQ(StatusCode::OK_200, res->status);
  10183. svr.stop();
  10184. thread.join();
  10185. ASSERT_FALSE(svr.is_running());
  10186. res = cli.Post("/hi", "data", "text/plain");
  10187. ASSERT_FALSE(res);
  10188. }
  10189. TEST(ServerStopTest, ListenFailure) {
  10190. Server svr;
  10191. auto t = thread([&]() {
  10192. auto ret = svr.listen("????", PORT);
  10193. EXPECT_FALSE(ret);
  10194. });
  10195. svr.wait_until_ready();
  10196. svr.stop();
  10197. t.join();
  10198. }
  10199. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10200. TEST(ServerStopTest, Decommision) {
  10201. Server svr;
  10202. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10203. for (int i = 0; i < 4; i++) {
  10204. auto is_even = !(i % 2);
  10205. std::thread t{[&] {
  10206. try {
  10207. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10208. if (is_even) {
  10209. throw std::runtime_error("Some thing that happens to go wrong.");
  10210. }
  10211. svr.listen(HOST, PORT);
  10212. } catch (...) { svr.decommission(); }
  10213. }};
  10214. svr.wait_until_ready();
  10215. // Server is up
  10216. {
  10217. Client cli(HOST, PORT);
  10218. auto res = cli.Get("/hi");
  10219. if (is_even) {
  10220. EXPECT_FALSE(res);
  10221. } else {
  10222. EXPECT_TRUE(res);
  10223. EXPECT_EQ("hi...", res->body);
  10224. }
  10225. }
  10226. svr.stop();
  10227. t.join();
  10228. // Server is down...
  10229. {
  10230. Client cli(HOST, PORT);
  10231. auto res = cli.Get("/hi");
  10232. EXPECT_FALSE(res);
  10233. }
  10234. }
  10235. }
  10236. #endif
  10237. // Helper function for string body upload progress tests
  10238. template <typename SetupHandler, typename ClientCall>
  10239. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10240. ClientCall &&client_call,
  10241. const string &body) {
  10242. Server svr;
  10243. setup_handler(svr);
  10244. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10245. auto se = detail::scope_exit([&] {
  10246. svr.stop();
  10247. t.join();
  10248. });
  10249. svr.wait_until_ready();
  10250. Client cli(HOST, PORT);
  10251. vector<uint64_t> progress_values;
  10252. bool progress_called = false;
  10253. auto res =
  10254. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10255. progress_values.push_back(current);
  10256. progress_called = true;
  10257. return true;
  10258. });
  10259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10260. EXPECT_EQ(200, res->status);
  10261. EXPECT_TRUE(progress_called);
  10262. }
  10263. TEST(UploadProgressTest, PostStringBodyBasic) {
  10264. TestStringBodyUploadProgress(
  10265. [](Server &svr) {
  10266. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10267. res.set_content("received", "text/plain");
  10268. });
  10269. },
  10270. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10271. return cli.Post("/test", body, "text/plain", progress_callback);
  10272. },
  10273. "test data for upload progress");
  10274. }
  10275. TEST(UploadProgressTest, PutStringBodyBasic) {
  10276. TestStringBodyUploadProgress(
  10277. [](Server &svr) {
  10278. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10279. res.set_content("put received", "text/plain");
  10280. });
  10281. },
  10282. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10283. return cli.Put("/test", body, "text/plain", progress_callback);
  10284. },
  10285. "put test data for upload progress");
  10286. }
  10287. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10288. TestStringBodyUploadProgress(
  10289. [](Server &svr) {
  10290. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10291. res.set_content("patch received", "text/plain");
  10292. });
  10293. },
  10294. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10295. return cli.Patch("/test", body, "text/plain", progress_callback);
  10296. },
  10297. "patch test data for upload progress");
  10298. }
  10299. // Helper function for content provider upload progress tests
  10300. template <typename SetupHandler, typename ClientCall>
  10301. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10302. ClientCall &&client_call) {
  10303. Server svr;
  10304. setup_handler(svr);
  10305. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10306. auto se = detail::scope_exit([&] {
  10307. svr.stop();
  10308. t.join();
  10309. });
  10310. svr.wait_until_ready();
  10311. Client cli(HOST, PORT);
  10312. vector<uint64_t> progress_values;
  10313. auto res =
  10314. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10315. progress_values.push_back(current);
  10316. return true;
  10317. });
  10318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10319. EXPECT_EQ(200, res->status);
  10320. EXPECT_FALSE(progress_values.empty());
  10321. }
  10322. TEST(UploadProgressTest, PostContentProviderProgress) {
  10323. TestContentProviderUploadProgress(
  10324. [](Server &svr) {
  10325. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10326. res.set_content("provider received", "text/plain");
  10327. });
  10328. },
  10329. [](Client &cli, UploadProgress progress_callback) {
  10330. return cli.Post(
  10331. "/test", 9,
  10332. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10333. sink.os << "test data";
  10334. return true;
  10335. },
  10336. "text/plain", progress_callback);
  10337. });
  10338. }
  10339. // Helper function for multipart upload progress tests
  10340. template <typename SetupHandler, typename ClientCall>
  10341. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10342. ClientCall &&client_call,
  10343. const string &endpoint) {
  10344. Server svr;
  10345. setup_handler(svr);
  10346. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10347. auto se = detail::scope_exit([&] {
  10348. svr.stop();
  10349. t.join();
  10350. });
  10351. svr.wait_until_ready();
  10352. Client cli(HOST, PORT);
  10353. vector<uint64_t> progress_values;
  10354. UploadFormDataItems items = {
  10355. {"field1", "value1", "", ""},
  10356. {"field2", "longer value for progress tracking test", "", ""},
  10357. {"file1", "file content data for upload progress", "test.txt",
  10358. "text/plain"}};
  10359. auto res = client_call(cli, endpoint, items,
  10360. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10361. progress_values.push_back(current);
  10362. return true;
  10363. });
  10364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10365. EXPECT_EQ(200, res->status);
  10366. EXPECT_FALSE(progress_values.empty());
  10367. }
  10368. TEST(UploadProgressTest, PostMultipartProgress) {
  10369. TestMultipartUploadProgress(
  10370. [](Server &svr) {
  10371. svr.Post("/multipart", [](const Request &req, Response &res) {
  10372. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10373. res.set_content("multipart received", "text/plain");
  10374. });
  10375. },
  10376. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10377. UploadProgress progress_callback) {
  10378. return cli.Post(endpoint, items, progress_callback);
  10379. },
  10380. "/multipart");
  10381. }
  10382. // Helper function for basic download progress tests
  10383. template <typename SetupHandler, typename ClientCall>
  10384. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10385. ClientCall &&client_call, const string &endpoint,
  10386. size_t expected_content_size) {
  10387. Server svr;
  10388. setup_handler(svr);
  10389. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10390. auto se = detail::scope_exit([&] {
  10391. svr.stop();
  10392. t.join();
  10393. });
  10394. svr.wait_until_ready();
  10395. Client cli(HOST, PORT);
  10396. vector<uint64_t> progress_values;
  10397. auto res = client_call(cli, endpoint,
  10398. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10399. progress_values.push_back(current);
  10400. return true;
  10401. });
  10402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10403. EXPECT_EQ(200, res->status);
  10404. EXPECT_FALSE(progress_values.empty());
  10405. EXPECT_EQ(expected_content_size, res->body.size());
  10406. }
  10407. TEST(DownloadProgressTest, GetBasic) {
  10408. TestBasicDownloadProgress(
  10409. [](Server &svr) {
  10410. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10411. string content(1000, 'D');
  10412. res.set_content(content, "text/plain");
  10413. });
  10414. },
  10415. [](Client &cli, const string &endpoint,
  10416. DownloadProgress progress_callback) {
  10417. return cli.Get(endpoint, progress_callback);
  10418. },
  10419. "/download", 1000u);
  10420. }
  10421. // Helper function for content receiver download progress tests
  10422. template <typename SetupHandler, typename ClientCall>
  10423. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10424. ClientCall &&client_call,
  10425. const string &endpoint,
  10426. size_t expected_content_size) {
  10427. Server svr;
  10428. setup_handler(svr);
  10429. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10430. auto se = detail::scope_exit([&] {
  10431. svr.stop();
  10432. t.join();
  10433. });
  10434. svr.wait_until_ready();
  10435. Client cli(HOST, PORT);
  10436. vector<uint64_t> progress_values;
  10437. string received_body;
  10438. auto res = client_call(
  10439. cli, endpoint,
  10440. [&](const char *data, size_t data_length) -> bool {
  10441. received_body.append(data, data_length);
  10442. return true;
  10443. },
  10444. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10445. progress_values.push_back(current);
  10446. return true;
  10447. });
  10448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10449. EXPECT_EQ(200, res->status);
  10450. EXPECT_FALSE(progress_values.empty());
  10451. EXPECT_EQ(expected_content_size, received_body.size());
  10452. EXPECT_TRUE(res->body.empty());
  10453. }
  10454. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10455. TestContentReceiverDownloadProgress(
  10456. [](Server &svr) {
  10457. svr.Get("/download-receiver",
  10458. [](const Request & /*req*/, Response &res) {
  10459. string content(2000, 'R');
  10460. res.set_content(content, "text/plain");
  10461. });
  10462. },
  10463. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10464. DownloadProgress progress_callback) {
  10465. return cli.Get(endpoint, content_receiver, progress_callback);
  10466. },
  10467. "/download-receiver", 2000u);
  10468. }
  10469. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10470. // A provider reaching a pass with nothing to hand over - an empty buffer
  10471. // popped off a queue, say - must not be taken to mean the body is finished.
  10472. // It used to end the loop with the terminating chunk unwritten while the
  10473. // server still considered the response complete, so the peer waited for an
  10474. // end that never arrived.
  10475. Server svr;
  10476. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10477. auto step = std::make_shared<int>(0);
  10478. res.set_chunked_content_provider("text/plain",
  10479. [step](size_t /*offset*/, DataSink &sink) {
  10480. switch ((*step)++) {
  10481. case 0: sink.write("", 0); break;
  10482. case 1: sink.write("hello", 5); break;
  10483. default: sink.done(); break;
  10484. }
  10485. return true;
  10486. });
  10487. });
  10488. auto port = svr.bind_to_any_port(HOST);
  10489. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10490. auto listen_se = detail::scope_exit([&] {
  10491. svr.stop();
  10492. listen_thread.join();
  10493. ASSERT_FALSE(svr.is_running());
  10494. });
  10495. svr.wait_until_ready();
  10496. Client cli(HOST, port);
  10497. // Without the fix the body is never terminated, so bound the wait rather
  10498. // than letting the test hang on the default read timeout.
  10499. cli.set_read_timeout(5, 0);
  10500. auto res = cli.Get("/stream");
  10501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10502. EXPECT_EQ(StatusCode::OK_200, res->status);
  10503. EXPECT_EQ("hello", res->body);
  10504. }
  10505. TEST(StreamingTest, NoContentLengthStreaming) {
  10506. Server svr;
  10507. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10508. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10509. if (offset < 6) {
  10510. sink.os << (offset < 3 ? "a" : "b");
  10511. } else {
  10512. sink.done();
  10513. }
  10514. return true;
  10515. });
  10516. });
  10517. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10518. auto listen_se = detail::scope_exit([&] {
  10519. svr.stop();
  10520. listen_thread.join();
  10521. ASSERT_FALSE(svr.is_running());
  10522. });
  10523. svr.wait_until_ready();
  10524. Client client(HOST, PORT);
  10525. auto get_thread = std::thread([&client]() {
  10526. std::string s;
  10527. auto res =
  10528. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10529. s += std::string(data, len);
  10530. return true;
  10531. });
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(StatusCode::OK_200, res->status);
  10534. EXPECT_EQ("aaabbb", s);
  10535. });
  10536. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10537. // Give GET time to get a few messages.
  10538. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10539. }
  10540. TEST(MountTest, Unmount) {
  10541. Server svr;
  10542. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10543. auto se = detail::scope_exit([&] {
  10544. svr.stop();
  10545. listen_thread.join();
  10546. ASSERT_FALSE(svr.is_running());
  10547. });
  10548. svr.wait_until_ready();
  10549. Client cli("localhost", PORT);
  10550. svr.set_mount_point("/mount2", "./www2");
  10551. auto res = cli.Get("/");
  10552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10554. res = cli.Get("/mount2/dir/test.html");
  10555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10556. EXPECT_EQ(StatusCode::OK_200, res->status);
  10557. svr.set_mount_point("/", "./www");
  10558. res = cli.Get("/dir/");
  10559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10560. EXPECT_EQ(StatusCode::OK_200, res->status);
  10561. svr.remove_mount_point("/");
  10562. res = cli.Get("/dir/");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10565. svr.remove_mount_point("/mount2");
  10566. res = cli.Get("/mount2/dir/test.html");
  10567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10569. }
  10570. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10571. Server svr;
  10572. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10573. svr.Get("/api/hello", [](const Request &, Response &res) {
  10574. res.set_content("api", "text/plain");
  10575. });
  10576. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10577. auto se = detail::scope_exit([&] {
  10578. svr.stop();
  10579. listen_thread.join();
  10580. ASSERT_FALSE(svr.is_running());
  10581. });
  10582. svr.wait_until_ready();
  10583. Client cli(HOST, PORT);
  10584. auto res = cli.Get("/dir/test.html");
  10585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10586. EXPECT_EQ(StatusCode::OK_200, res->status);
  10587. res = cli.Get("/api/hello");
  10588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10589. EXPECT_EQ(StatusCode::OK_200, res->status);
  10590. EXPECT_EQ("api", res->body);
  10591. }
  10592. TEST(MountTest, PathSegmentBoundary) {
  10593. Server svr;
  10594. svr.set_mount_point("/mount2", "./www2");
  10595. svr.set_mount_point("/", "./www");
  10596. auto port = svr.bind_to_any_port(HOST);
  10597. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10598. auto se = detail::scope_exit([&] {
  10599. svr.stop();
  10600. listen_thread.join();
  10601. ASSERT_FALSE(svr.is_running());
  10602. });
  10603. svr.wait_until_ready();
  10604. Client cli(HOST, port);
  10605. auto res = cli.Get("/mount2/dir/test.html");
  10606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10607. EXPECT_EQ(StatusCode::OK_200, res->status);
  10608. // "/mount2" must not match part-way through a path segment.
  10609. res = cli.Get("/mount2dir/test.html");
  10610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10611. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10612. // A mount point ending in '/' keeps matching every path below it.
  10613. res = cli.Get("/dir/test.html");
  10614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10615. EXPECT_EQ(StatusCode::OK_200, res->status);
  10616. }
  10617. TEST(MountTest, Redicect) {
  10618. Server svr;
  10619. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10620. auto se = detail::scope_exit([&] {
  10621. svr.stop();
  10622. listen_thread.join();
  10623. ASSERT_FALSE(svr.is_running());
  10624. });
  10625. svr.set_mount_point("/", "./www");
  10626. svr.wait_until_ready();
  10627. Client cli("localhost", PORT);
  10628. auto res = cli.Get("/dir/");
  10629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10630. EXPECT_EQ(StatusCode::OK_200, res->status);
  10631. res = cli.Get("/dir");
  10632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10633. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10634. res = cli.Get("/file");
  10635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10636. EXPECT_EQ(StatusCode::OK_200, res->status);
  10637. res = cli.Get("/file/");
  10638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10639. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10640. cli.set_follow_location(true);
  10641. res = cli.Get("/dir");
  10642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10643. EXPECT_EQ(StatusCode::OK_200, res->status);
  10644. }
  10645. TEST(MountTest, MultibytesPathName) {
  10646. Server svr;
  10647. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10648. auto se = detail::scope_exit([&] {
  10649. svr.stop();
  10650. listen_thread.join();
  10651. ASSERT_FALSE(svr.is_running());
  10652. });
  10653. svr.set_mount_point("/", "./www");
  10654. svr.wait_until_ready();
  10655. Client cli("localhost", PORT);
  10656. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10658. EXPECT_EQ(StatusCode::OK_200, res->status);
  10659. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10660. }
  10661. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10662. // in the pre-routing handler sees the path of every file that is served
  10663. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10664. Server svr;
  10665. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10666. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10667. if (req.path == "/dir/test.html") {
  10668. res.status = StatusCode::Unauthorized_401;
  10669. return Server::HandlerResponse::Handled;
  10670. }
  10671. return Server::HandlerResponse::Unhandled;
  10672. });
  10673. auto port = svr.bind_to_any_port(HOST);
  10674. ASSERT_LT(0, port);
  10675. thread t = thread([&] { svr.listen_after_bind(); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. t.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. Client cli(HOST, port);
  10683. for (auto path :
  10684. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10685. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10686. SCOPED_TRACE(path);
  10687. auto res = cli.Get(path);
  10688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10689. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10690. }
  10691. }
  10692. #ifdef _WIN32
  10693. // Issue #2435: mmap::open() must succeed even when another handle holds
  10694. // the file open for writing (e.g. an active log file).
  10695. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10696. const char *path = "mmap_concurrent_writer_test.txt";
  10697. const char *content = "hello";
  10698. {
  10699. std::ofstream f(path, std::ios::binary);
  10700. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10701. }
  10702. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10703. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10704. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10705. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10706. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10707. detail::mmap m(path);
  10708. ASSERT_TRUE(m.is_open());
  10709. EXPECT_EQ(strlen(content), m.size());
  10710. char buf[8];
  10711. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10712. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10713. }
  10714. #endif
  10715. #ifndef _WIN32
  10716. // A directory or a device has no size to serve.
  10717. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10718. const char *path = "./mmap_not_regular_test_dir";
  10719. ASSERT_EQ(0, ::mkdir(path, 0755));
  10720. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10721. for (auto p : {path, "/dev/null"}) {
  10722. detail::mmap m(p);
  10723. EXPECT_FALSE(m.is_open()) << p;
  10724. EXPECT_EQ(0U, m.size()) << p;
  10725. }
  10726. Server svr;
  10727. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10728. res.set_file_content("/dev/null");
  10729. });
  10730. auto port = svr.bind_to_any_port(HOST);
  10731. thread t = thread([&] { svr.listen_after_bind(); });
  10732. auto se = detail::scope_exit([&] {
  10733. svr.stop();
  10734. t.join();
  10735. });
  10736. svr.wait_until_ready();
  10737. auto res = Client(HOST, port).Get("/null");
  10738. ASSERT_TRUE(res);
  10739. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10740. }
  10741. #endif
  10742. #ifdef __linux__
  10743. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10744. TEST(MmapTest, FileIsNotMapped) {
  10745. const char *path = "mmap_not_mapped_test.txt";
  10746. {
  10747. std::ofstream f(path, std::ios::binary);
  10748. f << "hello";
  10749. }
  10750. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10751. detail::mmap m(path);
  10752. ASSERT_TRUE(m.is_open());
  10753. std::ifstream maps("/proc/self/maps");
  10754. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10755. std::istreambuf_iterator<char>());
  10756. EXPECT_EQ(std::string::npos, mappings.find(path));
  10757. }
  10758. #endif
  10759. TEST(KeepAliveTest, ReadTimeout) {
  10760. Server svr;
  10761. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10762. std::this_thread::sleep_for(std::chrono::seconds(2));
  10763. res.set_content("a", "text/plain");
  10764. });
  10765. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10766. res.set_content("b", "text/plain");
  10767. });
  10768. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10769. auto se = detail::scope_exit([&] {
  10770. svr.stop();
  10771. listen_thread.join();
  10772. ASSERT_FALSE(svr.is_running());
  10773. });
  10774. svr.wait_until_ready();
  10775. Client cli("localhost", PORT);
  10776. cli.set_keep_alive(true);
  10777. cli.set_read_timeout(std::chrono::seconds(1));
  10778. auto resa = cli.Get("/a");
  10779. ASSERT_FALSE(resa);
  10780. EXPECT_EQ(Error::Read, resa.error());
  10781. auto resb = cli.Get("/b");
  10782. ASSERT_TRUE(resb);
  10783. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10784. EXPECT_EQ("b", resb->body);
  10785. }
  10786. TEST(KeepAliveTest, MaxCount) {
  10787. size_t keep_alive_max_count = 3;
  10788. Server svr;
  10789. svr.set_keep_alive_max_count(keep_alive_max_count);
  10790. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10791. res.set_content("Hello World!", "text/plain");
  10792. });
  10793. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10794. auto se = detail::scope_exit([&] {
  10795. svr.stop();
  10796. listen_thread.join();
  10797. ASSERT_FALSE(svr.is_running());
  10798. });
  10799. svr.wait_until_ready();
  10800. Client cli(HOST, PORT);
  10801. cli.set_keep_alive(true);
  10802. for (size_t i = 0; i < 5; i++) {
  10803. auto result = cli.Get("/hi");
  10804. ASSERT_TRUE(result);
  10805. EXPECT_EQ(StatusCode::OK_200, result->status);
  10806. if (i == keep_alive_max_count - 1) {
  10807. EXPECT_EQ("close", result->get_header_value("Connection"));
  10808. } else {
  10809. EXPECT_FALSE(result->has_header("Connection"));
  10810. }
  10811. }
  10812. }
  10813. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10814. // can pull the next one into the server's buffer. The server must serve it
  10815. // without waiting for the socket to become readable again. The keep-alive
  10816. // timeout outlasts the client's read timeout, so a request left waiting for it
  10817. // shows up as a missing response.
  10818. static void serve_pipelining_routes(Server &svr,
  10819. const std::function<void(int)> &client) {
  10820. svr.set_keep_alive_timeout(5);
  10821. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10822. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10823. });
  10824. svr.Post("/echo", [](const Request &req, Response &res) {
  10825. res.set_content("echo " + req.body, "text/plain");
  10826. });
  10827. auto port = svr.bind_to_any_port(HOST);
  10828. thread t = thread([&] { svr.listen_after_bind(); });
  10829. auto se = detail::scope_exit([&] {
  10830. svr.stop();
  10831. t.join();
  10832. });
  10833. svr.wait_until_ready();
  10834. client(port);
  10835. }
  10836. static std::string
  10837. send_pipelined_requests(const std::vector<std::string> &parts) {
  10838. Server svr;
  10839. std::string res;
  10840. serve_pipelining_routes(svr, [&](int port) {
  10841. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10842. });
  10843. return res;
  10844. }
  10845. static void expect_in_order(const std::string &res,
  10846. const std::vector<std::string> &bodies) {
  10847. size_t pos = 0;
  10848. for (const auto &body : bodies) {
  10849. pos = res.find(body, pos);
  10850. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10851. pos += body.size();
  10852. }
  10853. }
  10854. TEST(KeepAliveTest, PipelinedRequests) {
  10855. auto res = send_pipelined_requests(
  10856. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10857. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10858. "Content-Length: 4\r\n\r\nbody"
  10859. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10860. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10861. }
  10862. // The second request starts in the server's buffer and ends on the socket.
  10863. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10864. auto res =
  10865. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10866. "GET /hi/2 HTTP/1.1\r\nHo",
  10867. "st: localhost\r\nConnection: close\r\n\r\n"});
  10868. expect_in_order(res, {"hi 1", "hi 2"});
  10869. }
  10870. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10871. // CRLF after a body does not turn into a 400 for the next request.
  10872. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10873. auto res = send_pipelined_requests(
  10874. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10875. "Content-Length: 4\r\n\r\nbody\r\n"
  10876. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10877. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10878. expect_in_order(res, {"echo body", "hi 2"});
  10879. }
  10880. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10881. // must not be served as the next request.
  10882. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10883. auto res = send_pipelined_requests(
  10884. {"INVALID REQUEST LINE\r\n\r\n"
  10885. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10886. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10887. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10888. }
  10889. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10890. // Over TLS, the next request is held by the TLS library as already decrypted
  10891. // data rather than on the socket.
  10892. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10894. std::string res;
  10895. serve_pipelining_routes(svr, [&](int port) {
  10896. // One part, so all three requests arrive in one TLS record
  10897. EXPECT_TRUE(send_ssl_request_in_parts(
  10898. 2,
  10899. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10900. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10901. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10902. &res, port));
  10903. });
  10904. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10905. }
  10906. #endif
  10907. TEST(KeepAliveTest, Issue1041) {
  10908. Server svr;
  10909. svr.set_keep_alive_timeout(3);
  10910. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10911. res.set_content("Hello World!", "text/plain");
  10912. });
  10913. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10914. auto se = detail::scope_exit([&] {
  10915. svr.stop();
  10916. listen_thread.join();
  10917. ASSERT_FALSE(svr.is_running());
  10918. });
  10919. svr.wait_until_ready();
  10920. Client cli(HOST, PORT);
  10921. cli.set_keep_alive(true);
  10922. auto result = cli.Get("/hi");
  10923. ASSERT_TRUE(result);
  10924. EXPECT_EQ(StatusCode::OK_200, result->status);
  10925. std::this_thread::sleep_for(std::chrono::seconds(5));
  10926. result = cli.Get("/hi");
  10927. ASSERT_TRUE(result);
  10928. EXPECT_EQ(StatusCode::OK_200, result->status);
  10929. }
  10930. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10931. Server svr;
  10932. svr.set_keep_alive_max_count(0);
  10933. std::set<int> remote_ports;
  10934. svr.Get("/hi", [&](const Request &req, Response &res) {
  10935. remote_ports.insert(req.remote_port);
  10936. res.set_content("hi", "text/plain");
  10937. });
  10938. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10939. auto se = detail::scope_exit([&] {
  10940. svr.stop();
  10941. listen_thread.join();
  10942. ASSERT_FALSE(svr.is_running());
  10943. });
  10944. svr.wait_until_ready();
  10945. Client cli(HOST, PORT);
  10946. cli.set_keep_alive(true);
  10947. for (int i = 0; i < 3; i++) {
  10948. auto res = cli.Get("/hi");
  10949. ASSERT_TRUE(res);
  10950. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10951. }
  10952. // All three over one connection
  10953. EXPECT_EQ(1u, remote_ports.size());
  10954. }
  10955. TEST(KeepAliveTest, Issue1959) {
  10956. Server svr;
  10957. svr.set_keep_alive_timeout(5);
  10958. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10959. res.set_content("a", "text/plain");
  10960. });
  10961. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10962. auto se = detail::scope_exit([&] {
  10963. if (!svr.is_running()) return;
  10964. svr.stop();
  10965. listen_thread.join();
  10966. ASSERT_FALSE(svr.is_running());
  10967. });
  10968. svr.wait_until_ready();
  10969. Client cli("localhost", PORT);
  10970. cli.set_keep_alive(true);
  10971. using namespace std::chrono;
  10972. auto start = steady_clock::now();
  10973. cli.Get("/a");
  10974. svr.stop();
  10975. listen_thread.join();
  10976. auto end = steady_clock::now();
  10977. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10978. EXPECT_LT(elapsed, 5000);
  10979. }
  10980. #ifdef CPPHTTPLIB_SSL_ENABLED
  10981. TEST(KeepAliveTest, SSLClientReconnection) {
  10982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10983. ASSERT_TRUE(svr.is_valid());
  10984. svr.set_keep_alive_timeout(1);
  10985. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10986. res.set_content("Hello World!", "text/plain");
  10987. });
  10988. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10989. auto se = detail::scope_exit([&] {
  10990. svr.stop();
  10991. listen_thread.join();
  10992. ASSERT_FALSE(svr.is_running());
  10993. });
  10994. svr.wait_until_ready();
  10995. SSLClient cli(HOST, PORT);
  10996. cli.enable_server_certificate_verification(false);
  10997. cli.set_keep_alive(true);
  10998. auto result = cli.Get("/hi");
  10999. ASSERT_TRUE(result);
  11000. EXPECT_EQ(StatusCode::OK_200, result->status);
  11001. result = cli.Get("/hi");
  11002. ASSERT_TRUE(result);
  11003. EXPECT_EQ(StatusCode::OK_200, result->status);
  11004. std::this_thread::sleep_for(std::chrono::seconds(2));
  11005. // Recoonect
  11006. result = cli.Get("/hi");
  11007. ASSERT_TRUE(result);
  11008. EXPECT_EQ(StatusCode::OK_200, result->status);
  11009. result = cli.Get("/hi");
  11010. ASSERT_TRUE(result);
  11011. EXPECT_EQ(StatusCode::OK_200, result->status);
  11012. }
  11013. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11015. ASSERT_TRUE(svr.is_valid());
  11016. svr.set_keep_alive_timeout(1);
  11017. std::string content = "reconnect";
  11018. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11019. res.set_content("Hello World!", "text/plain");
  11020. });
  11021. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11022. auto se = detail::scope_exit([&] {
  11023. svr.stop();
  11024. listen_thread.join();
  11025. ASSERT_FALSE(svr.is_running());
  11026. });
  11027. svr.wait_until_ready();
  11028. SSLClient cli(HOST, PORT);
  11029. cli.enable_server_certificate_verification(false);
  11030. cli.set_keep_alive(true);
  11031. auto result = cli.Post(
  11032. "/hi", content.size(),
  11033. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11034. sink.write(content.c_str(), content.size());
  11035. return true;
  11036. },
  11037. "text/plain");
  11038. ASSERT_TRUE(result);
  11039. EXPECT_EQ(200, result->status);
  11040. std::this_thread::sleep_for(std::chrono::seconds(2));
  11041. // Recoonect
  11042. result = cli.Post(
  11043. "/hi", content.size(),
  11044. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11045. sink.write(content.c_str(), content.size());
  11046. return true;
  11047. },
  11048. "text/plain");
  11049. ASSERT_TRUE(result);
  11050. EXPECT_EQ(200, result->status);
  11051. result = cli.Post(
  11052. "/hi", content.size(),
  11053. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11054. sink.write(content.c_str(), content.size());
  11055. return true;
  11056. },
  11057. "text/plain");
  11058. ASSERT_TRUE(result);
  11059. EXPECT_EQ(200, result->status);
  11060. }
  11061. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11062. using namespace httplib::tls;
  11063. {
  11064. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11065. ASSERT_TRUE(svr.is_valid());
  11066. svr.Get("/sni", [&](const Request &req, Response &res) {
  11067. std::string expected = req.sni();
  11068. EXPECT_EQ(expected, req.get_param_value("expected"));
  11069. res.set_content("ok", "text/plain");
  11070. });
  11071. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11072. auto se = detail::scope_exit([&] {
  11073. svr.stop();
  11074. listen_thread.join();
  11075. ASSERT_FALSE(svr.is_running());
  11076. });
  11077. svr.wait_until_ready();
  11078. {
  11079. SSLClient cli("localhost", PORT);
  11080. cli.enable_server_certificate_verification(false);
  11081. auto res = cli.Get("/sni?expected=localhost");
  11082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11083. }
  11084. {
  11085. SSLClient cli("::1", PORT);
  11086. cli.enable_server_certificate_verification(false);
  11087. auto res = cli.Get("/sni?expected=");
  11088. // NOTE: This may fail if the server is listening on IPv4 only
  11089. // (e.g., when localhost resolves to 127.0.0.1 only)
  11090. if (res) {
  11091. EXPECT_EQ(StatusCode::OK_200, res->status);
  11092. } else {
  11093. EXPECT_EQ(Error::Connection, res.error());
  11094. }
  11095. }
  11096. }
  11097. }
  11098. // The SNI of a failed handshake does not reach the next connection that the
  11099. // same worker thread serves
  11100. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11102. ASSERT_TRUE(svr.is_valid());
  11103. svr.new_task_queue = [] { return new ThreadPool(1); };
  11104. svr.Get("/sni", [](const Request &req, Response &res) {
  11105. res.set_content(req.sni(), "text/plain");
  11106. });
  11107. auto port = svr.bind_to_any_port("127.0.0.1");
  11108. ASSERT_LT(0, port);
  11109. thread t = thread([&] { svr.listen_after_bind(); });
  11110. auto se = detail::scope_exit([&] {
  11111. svr.stop();
  11112. t.join();
  11113. ASSERT_FALSE(svr.is_running());
  11114. });
  11115. svr.wait_until_ready();
  11116. {
  11117. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11118. SSLClient cli("localhost", port);
  11119. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11120. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11121. auto res = cli.Get("/sni");
  11122. ASSERT_FALSE(res);
  11123. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11124. }
  11125. // An IP host sends no SNI (RFC 6066)
  11126. SSLClient cli("127.0.0.1", port);
  11127. cli.enable_server_certificate_verification(false);
  11128. auto res = cli.Get("/sni");
  11129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11130. EXPECT_EQ("", res->body);
  11131. }
  11132. #endif
  11133. TEST(ClientProblemDetectionTest, ContentProvider) {
  11134. Server svr;
  11135. size_t content_length = 1024 * 1024;
  11136. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11137. res.set_content_provider(
  11138. content_length, "text/plain",
  11139. [&](size_t offset, size_t length, DataSink &sink) {
  11140. auto out_len = std::min(length, static_cast<size_t>(1024));
  11141. std::string out(out_len, '@');
  11142. sink.write(out.data(), out_len);
  11143. return offset < 4096;
  11144. },
  11145. [](bool success) { ASSERT_FALSE(success); });
  11146. });
  11147. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11148. res.set_content_provider(
  11149. 0, "text/plain",
  11150. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11151. EXPECT_TRUE(false);
  11152. return true;
  11153. },
  11154. [](bool success) { ASSERT_FALSE(success); });
  11155. });
  11156. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11157. auto se = detail::scope_exit([&] {
  11158. svr.stop();
  11159. listen_thread.join();
  11160. ASSERT_FALSE(svr.is_running());
  11161. });
  11162. svr.wait_until_ready();
  11163. Client cli("localhost", PORT);
  11164. {
  11165. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11166. size_t /*data_length*/) { return false; });
  11167. ASSERT_FALSE(res);
  11168. }
  11169. {
  11170. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11171. size_t /*data_length*/) { return false; });
  11172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11173. }
  11174. }
  11175. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11176. // A provider that reports success without writing anything and without
  11177. // calling done() used to be handed the same offset and length again on every
  11178. // pass, so it spun for as long as the peer stayed connected.
  11179. Server svr;
  11180. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11181. res.set_content("ok", "text/plain");
  11182. });
  11183. auto port = svr.bind_to_any_port(HOST);
  11184. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11185. auto se = detail::scope_exit([&] {
  11186. svr.stop();
  11187. listen_thread.join();
  11188. ASSERT_FALSE(svr.is_running());
  11189. });
  11190. svr.wait_until_ready();
  11191. std::atomic<int> call_count{0};
  11192. Client cli(HOST, port);
  11193. auto res = cli.Post(
  11194. "/", 1024,
  11195. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11196. // Give up after enough passes to show the spin, so that losing the
  11197. // check below fails this test instead of hanging it.
  11198. return ++call_count < 100;
  11199. },
  11200. "text/plain");
  11201. ASSERT_FALSE(res);
  11202. EXPECT_EQ(Error::Write, res.error());
  11203. EXPECT_EQ(1, call_count.load());
  11204. }
  11205. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11206. // A writer only has to assign `write`. The other three used to be left as
  11207. // empty std::functions, so a provider calling one threw
  11208. // std::bad_function_call out of the thread running it and took the whole
  11209. // process down.
  11210. DataSink sink;
  11211. std::string written;
  11212. sink.write = [&](const char *data, size_t data_len) {
  11213. written.append(data, data_len);
  11214. return true;
  11215. };
  11216. EXPECT_TRUE(sink.is_writable());
  11217. sink.done();
  11218. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11219. EXPECT_TRUE(written.empty());
  11220. }
  11221. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11222. // A sink that cannot carry trailers still has to finish.
  11223. DataSink sink;
  11224. auto done_count = 0;
  11225. sink.done = [&]() { done_count++; };
  11226. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11227. EXPECT_EQ(1, done_count);
  11228. }
  11229. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11230. Server svr;
  11231. const std::string body(4096, 'x');
  11232. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11233. res.set_content_provider(body.size(), "text/plain",
  11234. [&](size_t offset, size_t length, DataSink &sink) {
  11235. sink.write(body.data() + offset, length);
  11236. sink.done();
  11237. return true;
  11238. });
  11239. });
  11240. auto port = svr.bind_to_any_port(HOST);
  11241. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11242. auto se = detail::scope_exit([&] {
  11243. svr.stop();
  11244. listen_thread.join();
  11245. ASSERT_FALSE(svr.is_running());
  11246. });
  11247. svr.wait_until_ready();
  11248. Client cli(HOST, port);
  11249. auto res = cli.Get("/");
  11250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11251. EXPECT_EQ(StatusCode::OK_200, res->status);
  11252. EXPECT_EQ(body, res->body);
  11253. }
  11254. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11255. Server svr;
  11256. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11257. res.set_content_provider(
  11258. 1024, "text/plain",
  11259. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11260. sink.write("hello", 5);
  11261. sink.done(); // short of the 1024 bytes the response promised
  11262. return true;
  11263. });
  11264. });
  11265. auto port = svr.bind_to_any_port(HOST);
  11266. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11267. auto se = detail::scope_exit([&] {
  11268. svr.stop();
  11269. listen_thread.join();
  11270. ASSERT_FALSE(svr.is_running());
  11271. });
  11272. svr.wait_until_ready();
  11273. Client cli(HOST, port);
  11274. cli.set_read_timeout(5, 0);
  11275. // The response is short of its Content-Length, so the client cannot read a
  11276. // complete body. What matters is that this returns at all: a no-op done()
  11277. // would leave the writer looping over a provider that never makes progress.
  11278. auto res = cli.Get("/");
  11279. EXPECT_FALSE(res);
  11280. }
  11281. // Read as the next response by a peer that sees it after a framed body.
  11282. static const std::string smuggled_response =
  11283. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11284. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11285. Server svr;
  11286. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11287. res.set_content_provider(
  11288. 5, "text/plain",
  11289. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11290. auto data = "AAAAA" + smuggled_response;
  11291. sink.write(data.data(), data.size());
  11292. return true;
  11293. });
  11294. });
  11295. thread t = thread([&] { svr.listen(HOST, PORT); });
  11296. auto se = detail::scope_exit([&] {
  11297. svr.stop();
  11298. t.join();
  11299. ASSERT_FALSE(svr.is_running());
  11300. });
  11301. svr.wait_until_ready();
  11302. std::string resp;
  11303. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11304. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11305. resp.clear();
  11306. ASSERT_TRUE(send_request(
  11307. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11308. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11309. }
  11310. TEST(NoContentTest, BodyIsNotSent) {
  11311. Server svr;
  11312. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11313. res.status = StatusCode::NoContent_204;
  11314. res.set_content(smuggled_response, "text/plain");
  11315. });
  11316. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11317. res.status = StatusCode::NotModified_304;
  11318. res.set_chunked_content_provider(
  11319. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11320. sink.write(smuggled_response.data(), smuggled_response.size());
  11321. sink.done();
  11322. return true;
  11323. });
  11324. });
  11325. thread t = thread([&] { svr.listen(HOST, PORT); });
  11326. auto se = detail::scope_exit([&] {
  11327. svr.stop();
  11328. t.join();
  11329. ASSERT_FALSE(svr.is_running());
  11330. });
  11331. svr.wait_until_ready();
  11332. for (auto path : {"/204", "/304"}) {
  11333. std::string resp;
  11334. ASSERT_TRUE(send_request(
  11335. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11336. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11337. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11338. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11339. }
  11340. }
  11341. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11342. Server svr;
  11343. std::atomic<bool> smuggled(false);
  11344. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11345. res.set_content("ok", "text/plain");
  11346. });
  11347. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11348. smuggled = true;
  11349. });
  11350. auto port = svr.bind_to_any_port(HOST);
  11351. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11352. auto se = detail::scope_exit([&] {
  11353. svr.stop();
  11354. listen_thread.join();
  11355. ASSERT_FALSE(svr.is_running());
  11356. });
  11357. svr.wait_until_ready();
  11358. // What follows the body would be read as the next request.
  11359. Client cli(HOST, port);
  11360. auto res = cli.Post(
  11361. "/", 5,
  11362. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11363. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11364. sink.write(data.data(), data.size());
  11365. return true;
  11366. },
  11367. "text/plain");
  11368. ASSERT_FALSE(res);
  11369. EXPECT_EQ(Error::Write, res.error());
  11370. EXPECT_FALSE(smuggled);
  11371. }
  11372. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11373. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11374. // The compressed path builds the whole body before connecting, so this
  11375. // fails client-side and never reaches a server.
  11376. Client cli(HOST, PORT);
  11377. cli.set_compress(true);
  11378. auto res = cli.Post(
  11379. "/", 1024,
  11380. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11381. sink.write("hello", 5);
  11382. sink.done(); // short of the 1024 bytes the request announced
  11383. return true;
  11384. },
  11385. "text/plain");
  11386. ASSERT_FALSE(res);
  11387. EXPECT_EQ(Error::Write, res.error());
  11388. }
  11389. #endif
  11390. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11391. Server svr;
  11392. svr.set_error_handler([](Request const &, Response &res) -> void {
  11393. res.set_chunked_content_provider(
  11394. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11395. sink.os << "hello";
  11396. sink.os << "world";
  11397. sink.done();
  11398. return true;
  11399. });
  11400. });
  11401. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11402. auto se = detail::scope_exit([&] {
  11403. svr.stop();
  11404. listen_thread.join();
  11405. ASSERT_FALSE(svr.is_running());
  11406. });
  11407. svr.wait_until_ready();
  11408. Client cli("localhost", PORT);
  11409. auto res = cli.Get("/");
  11410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11411. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11412. EXPECT_EQ("helloworld", res->body);
  11413. }
  11414. // A body set after a content provider must replace it, not be sent through it.
  11415. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11416. Server svr;
  11417. svr.set_mount_point("/", "./www");
  11418. svr.set_file_request_handler([](const Request &req, Response &res) {
  11419. if (req.path == "/dir/test.html") {
  11420. res.status = StatusCode::Forbidden_403;
  11421. res.set_content(std::string(5000, 'D'), "text/plain");
  11422. } else if (req.path == "/file") {
  11423. res.status = StatusCode::Forbidden_403;
  11424. res.body = "Denied";
  11425. }
  11426. });
  11427. auto port = svr.bind_to_any_port(HOST);
  11428. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11429. auto se = detail::scope_exit([&] {
  11430. svr.stop();
  11431. t.join();
  11432. ASSERT_FALSE(svr.is_running());
  11433. });
  11434. svr.wait_until_ready();
  11435. Client cli(HOST, port);
  11436. {
  11437. auto res = cli.Get("/dir/test.html");
  11438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11439. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11440. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11441. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11442. }
  11443. {
  11444. auto res = cli.Get("/file");
  11445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11446. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11447. EXPECT_EQ("Denied", res->body);
  11448. }
  11449. {
  11450. auto res = cli.Get("/dir/index.html");
  11451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11452. EXPECT_EQ(StatusCode::OK_200, res->status);
  11453. EXPECT_EQ(0U, res->body.find("<html>"));
  11454. }
  11455. }
  11456. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11457. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11458. Server svr;
  11459. std::vector<bool> released;
  11460. std::mutex released_mutex;
  11461. auto releaser = [&](bool success) {
  11462. std::lock_guard<std::mutex> guard(released_mutex);
  11463. released.push_back(success);
  11464. };
  11465. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11466. return sink.write(&"hello"[offset], length);
  11467. };
  11468. svr.Get("/sized", [&](const Request &, Response &res) {
  11469. res.status = StatusCode::NotFound_404;
  11470. res.set_content_provider(5, "text/plain", provider, releaser);
  11471. });
  11472. svr.Get("/chunked", [&](const Request &, Response &res) {
  11473. res.status = StatusCode::ServiceUnavailable_503;
  11474. res.set_chunked_content_provider(
  11475. "text/plain",
  11476. [](size_t, DataSink &sink) {
  11477. sink.os << "chunk";
  11478. sink.done();
  11479. return true;
  11480. },
  11481. releaser);
  11482. });
  11483. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11484. res.set_content_provider(5, "text/plain", provider, releaser);
  11485. throw std::runtime_error("after the provider");
  11486. });
  11487. svr.set_error_handler([](const Request &req, Response &res) {
  11488. // Leave the exception handler's content to it.
  11489. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11490. res.set_content(std::string(1000, 'E'), "text/html");
  11491. return Server::HandlerResponse::Handled;
  11492. });
  11493. svr.set_exception_handler(
  11494. [](const Request &, Response &res, std::exception_ptr) {
  11495. res.status = StatusCode::InternalServerError_500;
  11496. res.set_content(std::string(1000, 'X'), "text/html");
  11497. });
  11498. auto port = svr.bind_to_any_port(HOST);
  11499. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11500. auto se = detail::scope_exit([&] {
  11501. svr.stop();
  11502. t.join();
  11503. ASSERT_FALSE(svr.is_running());
  11504. });
  11505. svr.wait_until_ready();
  11506. Client cli(HOST, port);
  11507. {
  11508. auto res = cli.Get("/sized");
  11509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11510. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11511. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11512. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11513. }
  11514. {
  11515. auto res = cli.Get("/chunked");
  11516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11517. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11518. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11519. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11520. }
  11521. {
  11522. auto res = cli.Get("/throw");
  11523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11524. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11525. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11526. }
  11527. std::lock_guard<std::mutex> guard(released_mutex);
  11528. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11529. }
  11530. #endif
  11531. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11532. Server svr;
  11533. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11534. return sink.write(&"abc"[offset], length);
  11535. };
  11536. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11537. res.set_file_content("./www/dir/test.html");
  11538. res.set_content("body", "text/plain");
  11539. });
  11540. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11541. res.set_content(std::string(100, 'B'), "text/plain");
  11542. res.set_file_content("./www/dir/test.html");
  11543. });
  11544. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11545. res.set_content(std::string(100, 'B'), "text/plain");
  11546. res.set_content_provider(3, "text/x-provider", abc);
  11547. });
  11548. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11549. res.set_content_provider(3, "text/x-provider", abc);
  11550. res.set_content(std::string(100, 'B'), "text/plain");
  11551. });
  11552. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11553. res.set_content_provider(3, "text/x-provider", abc);
  11554. res.set_file_content("./www/dir/test.html", "text/x-file");
  11555. });
  11556. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11557. res.set_file_content("./www/dir/test.html");
  11558. res.set_header("Content-Type", "text/x-handler");
  11559. });
  11560. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11561. res.set_content_provider(3, "text/plain", abc);
  11562. res.body = "direct";
  11563. });
  11564. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11565. res.set_file_content("./www/dir/test.html");
  11566. res.body = "direct";
  11567. });
  11568. auto port = svr.bind_to_any_port(HOST);
  11569. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11570. auto se = detail::scope_exit([&] {
  11571. svr.stop();
  11572. t.join();
  11573. ASSERT_FALSE(svr.is_running());
  11574. });
  11575. svr.wait_until_ready();
  11576. Client cli(HOST, port);
  11577. auto expect_body = [&](const char *path, const std::string &body,
  11578. const std::string &type) {
  11579. // Uncompressed, so Content-Length can be compared with the body.
  11580. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11581. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11582. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11583. EXPECT_EQ(body, res->body) << path;
  11584. EXPECT_EQ(std::to_string(body.size()),
  11585. res->get_header_value("Content-Length"))
  11586. << path;
  11587. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11588. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11589. };
  11590. expect_body("/file-then-body", "body", "text/plain");
  11591. expect_body("/body-then-file", "test.html", "text/html");
  11592. expect_body("/body-then-provider", "abc", "text/x-provider");
  11593. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11594. expect_body("/provider-then-file", "test.html", "text/x-file");
  11595. expect_body("/file-then-header", "test.html", "text/x-handler");
  11596. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11597. expect_body("/file-then-direct-body", "direct", "text/plain");
  11598. // Ranges are checked against the body, not the dropped provider.
  11599. {
  11600. auto res = cli.Get("/provider-then-direct-body",
  11601. Headers{{make_range_header({{1, 2}})}});
  11602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11604. EXPECT_EQ("ir", res->body);
  11605. }
  11606. {
  11607. auto res = cli.Get("/file-then-direct-body",
  11608. Headers{{make_range_header({{7, 8}})}});
  11609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11610. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11611. }
  11612. }
  11613. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11614. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11615. const char *path = "./truncated_while_served.txt";
  11616. const size_t size = 32 * 1024 * 1024;
  11617. {
  11618. std::ofstream f(path, std::ios::binary);
  11619. f << std::string(size, 'x');
  11620. }
  11621. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11622. // Over TLS, where the bytes are encrypted in this process rather than
  11623. // copied by send().
  11624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11625. svr.Get("/file", [&](const Request &, Response &res) {
  11626. res.set_file_content(path, "text/plain");
  11627. });
  11628. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11629. auto se = detail::scope_exit([&] {
  11630. svr.stop();
  11631. thread.join();
  11632. ASSERT_FALSE(svr.is_running());
  11633. });
  11634. svr.wait_until_ready();
  11635. // The file shrinks once the first bytes are in, as a rewrite in place
  11636. // would, and reading the mapping past its new end used to raise SIGBUS.
  11637. SSLClient cli(HOST, PORT);
  11638. cli.enable_server_certificate_verification(false);
  11639. size_t received = 0;
  11640. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11641. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11642. received += len;
  11643. return true;
  11644. });
  11645. EXPECT_FALSE(res);
  11646. EXPECT_LT(received, size);
  11647. }
  11648. #endif
  11649. // Forward declaration (see the base64_encode note).
  11650. namespace httplib {
  11651. namespace detail {
  11652. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11653. const std::string &content_type,
  11654. EncodingType encoding);
  11655. } // namespace detail
  11656. } // namespace httplib
  11657. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11658. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11659. ASSERT_TRUE(mm->is_open());
  11660. Response res;
  11661. detail::set_file_content_provider(res, mm, "text/html",
  11662. detail::EncodingType::None);
  11663. std::string out;
  11664. DataSink sink;
  11665. sink.write = [&](const char *d, size_t l) {
  11666. out.append(d, l);
  11667. return true;
  11668. };
  11669. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11670. EXPECT_EQ("test.html", out);
  11671. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11672. EXPECT_EQ("test.html", out);
  11673. }
  11674. TEST(LongPollingTest, ClientCloseDetection) {
  11675. Server svr;
  11676. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11677. res.set_chunked_content_provider(
  11678. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11679. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11680. sink.os << "hello";
  11681. auto count = 10;
  11682. while (count > 0 && sink.is_writable()) {
  11683. this_thread::sleep_for(chrono::milliseconds(10));
  11684. count--;
  11685. }
  11686. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11687. return true;
  11688. });
  11689. });
  11690. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11691. auto se = detail::scope_exit([&] {
  11692. svr.stop();
  11693. listen_thread.join();
  11694. ASSERT_FALSE(svr.is_running());
  11695. });
  11696. svr.wait_until_ready();
  11697. Client cli("localhost", PORT);
  11698. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11699. EXPECT_EQ("hello", string(data, data_length));
  11700. return false; // close the socket immediately.
  11701. });
  11702. ASSERT_FALSE(res);
  11703. }
  11704. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11705. Server svr;
  11706. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11707. res.set_chunked_content_provider(
  11708. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11709. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11710. sink.os << "hello";
  11711. EXPECT_TRUE(sink.os.good());
  11712. // Wait for the client to close the connection
  11713. auto count = 10;
  11714. while (count > 0 && sink.is_writable()) {
  11715. this_thread::sleep_for(chrono::milliseconds(10));
  11716. count--;
  11717. }
  11718. // After client disconnect, write repeatedly until the socket
  11719. // write actually fails (small writes may be absorbed by the
  11720. // kernel buffer)
  11721. std::string chunk(1024, 'x');
  11722. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11723. sink.os << chunk;
  11724. }
  11725. EXPECT_TRUE(sink.os.fail());
  11726. return true;
  11727. });
  11728. });
  11729. auto port = svr.bind_to_any_port("localhost");
  11730. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11731. auto se = detail::scope_exit([&] {
  11732. svr.stop();
  11733. listen_thread.join();
  11734. ASSERT_FALSE(svr.is_running());
  11735. });
  11736. svr.wait_until_ready();
  11737. Client cli("localhost", port);
  11738. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11739. EXPECT_EQ("hello", string(data, data_length));
  11740. return false; // close the socket immediately.
  11741. });
  11742. ASSERT_FALSE(res);
  11743. }
  11744. TEST(GetWithParametersTest, GetWithParameters) {
  11745. Server svr;
  11746. svr.Get("/", [&](const Request &req, Response &) {
  11747. EXPECT_EQ("world", req.get_param_value("hello"));
  11748. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11749. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11750. });
  11751. svr.Get("/params", [&](const Request &req, Response &) {
  11752. EXPECT_EQ("world", req.get_param_value("hello"));
  11753. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11754. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11755. });
  11756. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11757. EXPECT_EQ("resource-id", req.matches[1]);
  11758. EXPECT_EQ("foo", req.get_param_value("param1"));
  11759. EXPECT_EQ("bar", req.get_param_value("param2"));
  11760. });
  11761. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11762. EXPECT_EQ("user-id", req.path_params.at("id"));
  11763. EXPECT_EQ("foo", req.get_param_value("param1"));
  11764. EXPECT_EQ("bar", req.get_param_value("param2"));
  11765. });
  11766. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11767. auto se = detail::scope_exit([&] {
  11768. svr.stop();
  11769. listen_thread.join();
  11770. ASSERT_FALSE(svr.is_running());
  11771. });
  11772. svr.wait_until_ready();
  11773. {
  11774. Client cli(HOST, PORT);
  11775. Params params;
  11776. params.emplace("hello", "world");
  11777. params.emplace("hello2", "world2");
  11778. params.emplace("hello3", "world3");
  11779. auto res = cli.Get("/", params, Headers{});
  11780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11781. EXPECT_EQ(StatusCode::OK_200, res->status);
  11782. }
  11783. {
  11784. Client cli(HOST, PORT);
  11785. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11787. EXPECT_EQ(StatusCode::OK_200, res->status);
  11788. }
  11789. {
  11790. Client cli(HOST, PORT);
  11791. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11793. EXPECT_EQ(StatusCode::OK_200, res->status);
  11794. }
  11795. {
  11796. Client cli(HOST, PORT);
  11797. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11799. EXPECT_EQ(StatusCode::OK_200, res->status);
  11800. }
  11801. }
  11802. TEST(GetWithParametersTest, GetWithParameters2) {
  11803. Server svr;
  11804. svr.Get("/", [&](const Request &req, Response &res) {
  11805. auto text = req.get_param_value("hello");
  11806. res.set_content(text, "text/plain");
  11807. });
  11808. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11809. auto se = detail::scope_exit([&] {
  11810. svr.stop();
  11811. listen_thread.join();
  11812. ASSERT_FALSE(svr.is_running());
  11813. });
  11814. svr.wait_until_ready();
  11815. Client cli("localhost", PORT);
  11816. Params params;
  11817. params.emplace("hello", "world");
  11818. std::string body;
  11819. auto res = cli.Get("/", params, Headers{},
  11820. [&](const char *data, size_t data_length) {
  11821. body.append(data, data_length);
  11822. return true;
  11823. });
  11824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11825. EXPECT_EQ(StatusCode::OK_200, res->status);
  11826. EXPECT_EQ("world", body);
  11827. }
  11828. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11829. Server svr;
  11830. svr.Get("/search", [&](const Request &req, Response &res) {
  11831. auto q = req.get_param_value("q");
  11832. res.set_content(q, "text/plain");
  11833. });
  11834. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11835. auto se = detail::scope_exit([&] {
  11836. svr.stop();
  11837. listen_thread.join();
  11838. ASSERT_FALSE(svr.is_running());
  11839. });
  11840. svr.wait_until_ready();
  11841. Client cli("localhost", PORT);
  11842. // Verify that Get(path, params) works without requiring Headers argument
  11843. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11845. EXPECT_EQ(StatusCode::OK_200, res->status);
  11846. EXPECT_EQ("cpp-httplib", res->body);
  11847. }
  11848. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11849. auto host = "httpbingo.org";
  11850. auto path = std::string{"/range/32"};
  11851. #ifdef CPPHTTPLIB_SSL_ENABLED
  11852. SSLClient cli(host);
  11853. #else
  11854. Client cli(host);
  11855. #endif
  11856. cli.set_default_headers({make_range_header({{1, 10}})});
  11857. cli.set_connection_timeout(5);
  11858. {
  11859. auto res = cli.Get(path);
  11860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11861. EXPECT_EQ("bcdefghijk", res->body);
  11862. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11863. }
  11864. {
  11865. auto res = cli.Get(path);
  11866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11867. EXPECT_EQ("bcdefghijk", res->body);
  11868. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11869. }
  11870. }
  11871. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11872. Server svr;
  11873. svr.set_default_headers({{"Hello", "World"}});
  11874. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11875. res.set_content("ok", "text/plain");
  11876. });
  11877. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11878. auto se = detail::scope_exit([&] {
  11879. svr.stop();
  11880. listen_thread.join();
  11881. ASSERT_FALSE(svr.is_running());
  11882. });
  11883. svr.wait_until_ready();
  11884. Client cli("localhost", PORT);
  11885. auto res = cli.Get("/");
  11886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11887. EXPECT_EQ(StatusCode::OK_200, res->status);
  11888. EXPECT_EQ("ok", res->body);
  11889. EXPECT_EQ("World", res->get_header_value("Hello"));
  11890. }
  11891. #ifdef CPPHTTPLIB_SSL_ENABLED
  11892. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11894. ASSERT_TRUE(svr.is_valid());
  11895. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11896. std::this_thread::sleep_for(std::chrono::seconds(2));
  11897. res.set_content("a", "text/plain");
  11898. });
  11899. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11900. res.set_content("b", "text/plain");
  11901. });
  11902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11903. auto se = detail::scope_exit([&] {
  11904. svr.stop();
  11905. listen_thread.join();
  11906. ASSERT_FALSE(svr.is_running());
  11907. });
  11908. svr.wait_until_ready();
  11909. SSLClient cli("localhost", PORT);
  11910. cli.enable_server_certificate_verification(false);
  11911. cli.set_keep_alive(true);
  11912. cli.set_read_timeout(std::chrono::seconds(1));
  11913. auto resa = cli.Get("/a");
  11914. ASSERT_TRUE(!resa);
  11915. EXPECT_EQ(Error::Read, resa.error());
  11916. auto resb = cli.Get("/b");
  11917. ASSERT_TRUE(resb);
  11918. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11919. EXPECT_EQ("b", resb->body);
  11920. }
  11921. // Closing an idle keep-alive connection sends close_notify and returns. The
  11922. // server must not wait for the client's close_notify: an idle client never
  11923. // sends one, so the worker would be held until the read timeout expires, and
  11924. // stop() would wait for it.
  11925. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11927. ASSERT_TRUE(svr.is_valid());
  11928. svr.set_keep_alive_timeout(1);
  11929. svr.set_read_timeout(10, 0);
  11930. svr.Get("/", [](const Request &, Response &res) {
  11931. res.set_content("ok", "text/plain");
  11932. });
  11933. auto port = svr.bind_to_any_port(HOST);
  11934. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11935. auto se = detail::scope_exit([&] {
  11936. if (listen_thread.joinable()) {
  11937. svr.stop();
  11938. listen_thread.join();
  11939. }
  11940. });
  11941. svr.wait_until_ready();
  11942. SSLClient cli(HOST, port);
  11943. cli.enable_server_certificate_verification(false);
  11944. cli.set_keep_alive(true);
  11945. auto res = cli.Get("/");
  11946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11947. EXPECT_EQ(StatusCode::OK_200, res->status);
  11948. // Stay idle past the keep-alive timeout so the server closes the connection.
  11949. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11950. auto start = std::chrono::steady_clock::now();
  11951. svr.stop();
  11952. listen_thread.join();
  11953. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11954. std::chrono::steady_clock::now() - start)
  11955. .count();
  11956. EXPECT_LT(elapsed, 3000);
  11957. }
  11958. #endif
  11959. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11960. protected:
  11961. ServerTestWithAI_PASSIVE()
  11962. : cli_(HOST, PORT)
  11963. #ifdef CPPHTTPLIB_SSL_ENABLED
  11964. ,
  11965. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11966. #endif
  11967. {
  11968. #ifdef CPPHTTPLIB_SSL_ENABLED
  11969. cli_.enable_server_certificate_verification(false);
  11970. #endif
  11971. }
  11972. virtual void SetUp() {
  11973. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11974. res.set_content("Hello World!", "text/plain");
  11975. });
  11976. t_ = thread(
  11977. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11978. svr_.wait_until_ready();
  11979. }
  11980. virtual void TearDown() {
  11981. svr_.stop();
  11982. t_.join();
  11983. }
  11984. #ifdef CPPHTTPLIB_SSL_ENABLED
  11985. SSLClient cli_;
  11986. SSLServer svr_;
  11987. #else
  11988. Client cli_;
  11989. Server svr_;
  11990. #endif
  11991. thread t_;
  11992. };
  11993. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11994. auto res = cli_.Get("/hi");
  11995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11996. EXPECT_EQ(StatusCode::OK_200, res->status);
  11997. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11998. EXPECT_EQ("Hello World!", res->body);
  11999. }
  12000. class ServerUpDownTest : public ::testing::Test {
  12001. protected:
  12002. ServerUpDownTest() : cli_(HOST, PORT) {}
  12003. virtual void SetUp() {
  12004. t_ = thread([&]() {
  12005. svr_.bind_to_any_port(HOST);
  12006. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12007. ASSERT_TRUE(svr_.listen_after_bind());
  12008. });
  12009. svr_.wait_until_ready();
  12010. }
  12011. virtual void TearDown() {
  12012. svr_.stop();
  12013. t_.join();
  12014. }
  12015. Client cli_;
  12016. Server svr_;
  12017. thread t_;
  12018. };
  12019. TEST_F(ServerUpDownTest, QuickStartStop) {
  12020. // Should not crash, especially when run with
  12021. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12022. }
  12023. class PayloadMaxLengthTest : public ::testing::Test {
  12024. protected:
  12025. PayloadMaxLengthTest()
  12026. : cli_(HOST, PORT)
  12027. #ifdef CPPHTTPLIB_SSL_ENABLED
  12028. ,
  12029. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12030. #endif
  12031. {
  12032. #ifdef CPPHTTPLIB_SSL_ENABLED
  12033. cli_.enable_server_certificate_verification(false);
  12034. #endif
  12035. }
  12036. virtual void SetUp() {
  12037. svr_.set_payload_max_length(8);
  12038. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12039. res.set_content("test", "text/plain");
  12040. });
  12041. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12042. svr_.wait_until_ready();
  12043. }
  12044. virtual void TearDown() {
  12045. svr_.stop();
  12046. t_.join();
  12047. }
  12048. #ifdef CPPHTTPLIB_SSL_ENABLED
  12049. SSLClient cli_;
  12050. SSLServer svr_;
  12051. #else
  12052. Client cli_;
  12053. Server svr_;
  12054. #endif
  12055. thread t_;
  12056. };
  12057. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12058. auto res = cli_.Post("/test", "123456789", "text/plain");
  12059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12060. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12061. res = cli_.Post("/test", "12345678", "text/plain");
  12062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12063. EXPECT_EQ(StatusCode::OK_200, res->status);
  12064. }
  12065. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12066. // Test chunked encoding with payload exceeding the 8-byte limit
  12067. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12068. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12070. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12071. }
  12072. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12073. // Test chunked encoding with payload within the 8-byte limit
  12074. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12075. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12077. EXPECT_EQ(StatusCode::OK_200, res->status);
  12078. }
  12079. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12080. // Test using send_request to send chunked data exceeding payload limit
  12081. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12082. "Host: " +
  12083. std::string(HOST) + ":" + std::to_string(PORT) +
  12084. "\r\n"
  12085. "Transfer-Encoding: chunked\r\n"
  12086. "Connection: close\r\n"
  12087. "\r\n"
  12088. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12089. "0123456789\r\n"
  12090. "0\r\n" // End chunk
  12091. "\r\n";
  12092. std::string response;
  12093. bool result = send_request(1, chunked_request, &response);
  12094. if (!result) {
  12095. // If send_request fails, it might be because the server closed the
  12096. // connection due to payload limit enforcement, which is acceptable
  12097. SUCCEED()
  12098. << "Server rejected oversized chunked request (connection closed)";
  12099. } else {
  12100. // If we got a response, check if it's an error response or connection was
  12101. // closed early Short response length indicates connection was closed due to
  12102. // payload limit
  12103. if (response.length() <= 10) {
  12104. SUCCEED() << "Server closed connection for oversized chunked request";
  12105. } else {
  12106. // Check for error status codes
  12107. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12108. response.find("Payload Too Large") != std::string::npos ||
  12109. response.find("400") != std::string::npos);
  12110. }
  12111. }
  12112. }
  12113. class LargePayloadMaxLengthTest : public ::testing::Test {
  12114. protected:
  12115. LargePayloadMaxLengthTest()
  12116. : cli_(HOST, PORT)
  12117. #ifdef CPPHTTPLIB_SSL_ENABLED
  12118. ,
  12119. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12120. #endif
  12121. {
  12122. #ifdef CPPHTTPLIB_SSL_ENABLED
  12123. cli_.enable_server_certificate_verification(false);
  12124. #endif
  12125. }
  12126. virtual void SetUp() {
  12127. // Set 10MB payload limit
  12128. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12129. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12130. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12131. res.set_content("Large payload test", "text/plain");
  12132. });
  12133. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12134. svr_.wait_until_ready();
  12135. }
  12136. virtual void TearDown() {
  12137. svr_.stop();
  12138. t_.join();
  12139. }
  12140. #ifdef CPPHTTPLIB_SSL_ENABLED
  12141. SSLClient cli_;
  12142. SSLServer svr_;
  12143. #else
  12144. Client cli_;
  12145. Server svr_;
  12146. #endif
  12147. thread t_;
  12148. };
  12149. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12150. // Test chunked encoding with payload within 10MB limit
  12151. std::string medium_payload(5 * 1024 * 1024,
  12152. 'A'); // 5MB payload, within 10MB limit
  12153. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12155. EXPECT_EQ(StatusCode::OK_200, res->status);
  12156. }
  12157. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12158. // Test chunked encoding with payload exceeding 10MB limit
  12159. std::string large_payload(12 * 1024 * 1024,
  12160. 'B'); // 12MB payload, exceeds 10MB limit
  12161. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12162. // Server may either return 413 or close the connection
  12163. if (res) {
  12164. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12165. } else {
  12166. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12167. }
  12168. }
  12169. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12170. Server svr;
  12171. svr.Get("/", [](const Request &, Response &res) {
  12172. // Claims the most the client accepts, far more than it sends, then drops
  12173. // the connection.
  12174. res.set_content_provider(std::string().max_size(), "text/plain",
  12175. [](size_t, size_t, DataSink &sink) {
  12176. sink.write("abc", 3);
  12177. return false;
  12178. });
  12179. });
  12180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12181. auto se = detail::scope_exit([&] {
  12182. svr.stop();
  12183. thread.join();
  12184. ASSERT_FALSE(svr.is_running());
  12185. });
  12186. svr.wait_until_ready();
  12187. Client cli(HOST, PORT);
  12188. cli.set_payload_max_length(0);
  12189. EXPECT_FALSE(cli.Get("/"));
  12190. }
  12191. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12192. // Stream API does, not as a plain read failure
  12193. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12194. Server svr;
  12195. svr.Get("/big", [](const Request &, Response &res) {
  12196. res.set_content(std::string(100000, 'b'), "text/plain");
  12197. });
  12198. auto port = svr.bind_to_any_port(HOST);
  12199. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12200. auto se = detail::scope_exit([&] {
  12201. svr.stop();
  12202. thread.join();
  12203. });
  12204. svr.wait_until_ready();
  12205. Client cli(HOST, port);
  12206. cli.set_payload_max_length(1000);
  12207. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12208. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12209. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12210. [](const char *, size_t) { return true; });
  12211. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12212. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12213. // Small on the wire, over the limit once decompressed
  12214. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12215. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12216. #endif
  12217. }
  12218. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12219. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12220. // path.
  12221. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12222. Server svr;
  12223. const size_t LIMIT = 64 * 1024; // 64KB
  12224. svr.set_payload_max_length(LIMIT);
  12225. size_t total = 0;
  12226. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12227. const ContentReader &content_reader) {
  12228. content_reader([&](const char * /*data*/, size_t len) {
  12229. total += len;
  12230. return true;
  12231. });
  12232. res.status = 200;
  12233. res.set_content("stream_ok", "text/plain");
  12234. });
  12235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12236. auto se = detail::scope_exit([&] {
  12237. svr.stop();
  12238. thread.join();
  12239. ASSERT_FALSE(svr.is_running());
  12240. });
  12241. svr.wait_until_ready();
  12242. // Prepare 256KB raw data and gzip-compress it
  12243. std::string raw(256 * 1024, 'A');
  12244. std::string gz;
  12245. {
  12246. z_stream zs{};
  12247. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12248. Z_DEFAULT_STRATEGY);
  12249. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12250. zs.avail_in = static_cast<uInt>(raw.size());
  12251. char outbuf[4096];
  12252. int ret;
  12253. do {
  12254. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12255. zs.avail_out = sizeof(outbuf);
  12256. ret = deflate(&zs, Z_FINISH);
  12257. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12258. } while (ret != Z_STREAM_END);
  12259. deflateEnd(&zs);
  12260. }
  12261. Client cli(HOST, PORT);
  12262. cli.set_connection_timeout(std::chrono::seconds(5));
  12263. Headers headers = {{"Content-Encoding", "gzip"}};
  12264. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12265. "application/octet-stream");
  12266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12267. // Server must reject oversized decompressed payloads with 413.
  12268. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12269. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12270. EXPECT_LE(total, LIMIT);
  12271. }
  12272. #endif
  12273. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12274. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12275. // the payload must be passed through untouched instead of being rejected.
  12276. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12277. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12278. Server svr;
  12279. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12280. res.set_content(body, "image/jpeg");
  12281. res.set_header("Content-Encoding", "UTF-8");
  12282. });
  12283. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12284. res.set_content(body, "image/jpeg");
  12285. res.set_header("Content-Encoding", "identity");
  12286. });
  12287. svr.Post("/echo", [](const Request &req, Response &res) {
  12288. res.set_content(req.body, "image/jpeg");
  12289. });
  12290. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12291. auto se = detail::scope_exit([&] {
  12292. svr.stop();
  12293. t.join();
  12294. ASSERT_FALSE(svr.is_running());
  12295. });
  12296. svr.wait_until_ready();
  12297. Client cli(HOST, PORT);
  12298. {
  12299. auto res = cli.Get("/image");
  12300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12301. EXPECT_EQ(StatusCode::OK_200, res->status);
  12302. EXPECT_EQ(body, res->body);
  12303. }
  12304. {
  12305. auto res = cli.Get("/identity");
  12306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12307. EXPECT_EQ(StatusCode::OK_200, res->status);
  12308. EXPECT_EQ(body, res->body);
  12309. }
  12310. {
  12311. // The same applies to a request body reaching the server.
  12312. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12313. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12315. EXPECT_EQ(StatusCode::OK_200, res->status);
  12316. EXPECT_EQ(body, res->body);
  12317. }
  12318. }
  12319. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12320. // gzip-encoded response even when the build has no zlib support.
  12321. static const char GZIPPED_HELLO_WORLD[] = {
  12322. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12323. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12324. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12325. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12326. // A content coding is a whole token, not something the field value merely
  12327. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12328. // as "fibre" look like Brotli, and turned a multi-coding value like
  12329. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12330. // it was never meant to see.
  12331. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12332. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12333. Server svr;
  12334. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12335. res.set_content(body, "image/jpeg");
  12336. res.set_header("Content-Encoding", "fibre");
  12337. });
  12338. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12339. res.set_content(body, "image/jpeg");
  12340. res.set_header("Content-Encoding", "gzip, br");
  12341. });
  12342. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12343. res.set_content(body, "image/jpeg");
  12344. res.set_header("Content-Encoding", "x-zstd-ish");
  12345. });
  12346. auto port = svr.bind_to_any_port(HOST);
  12347. thread t = thread([&]() { svr.listen_after_bind(); });
  12348. auto se = detail::scope_exit([&] {
  12349. svr.stop();
  12350. t.join();
  12351. ASSERT_FALSE(svr.is_running());
  12352. });
  12353. svr.wait_until_ready();
  12354. Client cli(HOST, port);
  12355. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12356. auto res = cli.Get(path);
  12357. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12358. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12359. // Not a coding we recognize, so the payload comes back untouched
  12360. EXPECT_EQ(body, res->body) << path;
  12361. }
  12362. }
  12363. // A content coding cpp-httplib recognizes but was not built with must be
  12364. // reported as such. Handing the still-compressed payload back to the caller
  12365. // would silently corrupt it.
  12366. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12367. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12368. Server svr;
  12369. // "image/jpeg" keeps the server from applying a content coding of its own,
  12370. // so the hand-crafted Content-Encoding below survives.
  12371. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12372. res.set_content(gzipped, "image/jpeg");
  12373. res.set_header("Content-Encoding", "gzip");
  12374. });
  12375. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12376. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12377. res.set_content(gzipped, "image/jpeg");
  12378. res.set_header("Content-Encoding", "GZIP");
  12379. });
  12380. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12381. auto se = detail::scope_exit([&] {
  12382. svr.stop();
  12383. t.join();
  12384. ASSERT_FALSE(svr.is_running());
  12385. });
  12386. svr.wait_until_ready();
  12387. Client cli(HOST, PORT);
  12388. {
  12389. auto res = cli.Get("/gzipped");
  12390. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12392. EXPECT_EQ("Hello World!", res->body);
  12393. #else
  12394. ASSERT_FALSE(res);
  12395. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12396. #endif
  12397. }
  12398. {
  12399. // open_stream() must behave the same way.
  12400. auto handle = cli.open_stream("GET", "/gzipped");
  12401. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12402. ASSERT_TRUE(handle.is_valid());
  12403. std::string received;
  12404. char buf[256];
  12405. ssize_t n;
  12406. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12407. received.append(buf, static_cast<size_t>(n));
  12408. }
  12409. EXPECT_EQ("Hello World!", received);
  12410. #else
  12411. EXPECT_FALSE(handle.is_valid());
  12412. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12413. #endif
  12414. }
  12415. {
  12416. // A differently-cased coding must not be mistaken for an unknown one, or
  12417. // the body would be handed back still compressed.
  12418. auto res = cli.Get("/gzipped-uppercase");
  12419. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12421. EXPECT_EQ("Hello World!", res->body);
  12422. #else
  12423. ASSERT_FALSE(res);
  12424. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12425. #endif
  12426. }
  12427. }
  12428. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12429. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12430. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12431. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12432. // body a second time and appending a second Content-Encoding field line, so
  12433. // clients that decode one coding per listed value handed back raw gzip bytes.
  12434. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12435. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12436. Server svr;
  12437. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12438. // keeps the server from applying a coding of its own.
  12439. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12440. res.set_content(gzipped, "text/plain");
  12441. res.set_header("Content-Encoding", "gzip");
  12442. });
  12443. auto port = svr.bind_to_any_port(HOST);
  12444. thread t = thread([&]() { svr.listen_after_bind(); });
  12445. auto se = detail::scope_exit([&] {
  12446. svr.stop();
  12447. t.join();
  12448. ASSERT_FALSE(svr.is_running());
  12449. });
  12450. svr.wait_until_ready();
  12451. Client cli(HOST, port);
  12452. Headers headers = {{"Accept-Encoding", "gzip"}};
  12453. auto res = cli.Get("/pre-gzipped", headers);
  12454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12455. EXPECT_EQ(StatusCode::OK_200, res->status);
  12456. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12457. EXPECT_EQ("Hello World!", res->body);
  12458. }
  12459. // set_compress(false) sends every handler response as it is, buffered or
  12460. // streamed
  12461. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12462. const std::string text(1000, 'a');
  12463. Server svr;
  12464. svr.set_compress(false);
  12465. svr.Get("/buffered", [&](const Request &, Response &res) {
  12466. res.set_content(text, "text/plain");
  12467. });
  12468. svr.Get("/streamed", [&](const Request &, Response &res) {
  12469. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12470. sink.write(text.data(), text.size());
  12471. sink.done();
  12472. return true;
  12473. });
  12474. });
  12475. auto port = svr.bind_to_any_port(HOST);
  12476. ASSERT_LT(0, port);
  12477. thread t = thread([&] { svr.listen_after_bind(); });
  12478. auto se = detail::scope_exit([&] {
  12479. svr.stop();
  12480. t.join();
  12481. ASSERT_FALSE(svr.is_running());
  12482. });
  12483. svr.wait_until_ready();
  12484. Client cli(HOST, port);
  12485. cli.set_decompress(false);
  12486. for (auto path : {"/buffered", "/streamed"}) {
  12487. SCOPED_TRACE(path);
  12488. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12490. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12491. EXPECT_EQ(text, res->body);
  12492. }
  12493. }
  12494. // A chunked provider settles its coding where the headers are written and
  12495. // reuses it at write time. Both ends of that have to hold: a handler's own
  12496. // Content-Encoding suppresses the coding, and a response without one is still
  12497. // compressed as it always was.
  12498. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12499. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12500. const std::string plain = "Hello World! Hello World! Hello World!";
  12501. Server svr;
  12502. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12503. res.set_header("Content-Encoding", "gzip");
  12504. res.set_chunked_content_provider(
  12505. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12506. sink.write(gzipped.data(), gzipped.size());
  12507. sink.done();
  12508. return true;
  12509. });
  12510. });
  12511. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12512. res.set_chunked_content_provider(
  12513. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12514. sink.write(plain.data(), plain.size());
  12515. sink.done();
  12516. return true;
  12517. });
  12518. });
  12519. auto port = svr.bind_to_any_port(HOST);
  12520. thread t = thread([&]() { svr.listen_after_bind(); });
  12521. auto se = detail::scope_exit([&] {
  12522. svr.stop();
  12523. t.join();
  12524. ASSERT_FALSE(svr.is_running());
  12525. });
  12526. svr.wait_until_ready();
  12527. Client cli(HOST, port);
  12528. Headers headers = {{"Accept-Encoding", "gzip"}};
  12529. {
  12530. auto res = cli.Get("/pre-gzipped", headers);
  12531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12532. EXPECT_EQ(StatusCode::OK_200, res->status);
  12533. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12534. EXPECT_EQ("Hello World!", res->body);
  12535. }
  12536. {
  12537. auto res = cli.Get("/negotiated", headers);
  12538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12539. EXPECT_EQ(StatusCode::OK_200, res->status);
  12540. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12541. EXPECT_EQ(plain, res->body);
  12542. }
  12543. }
  12544. #endif
  12545. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12546. // the same message as the comma-joined one, so both have to be read the same
  12547. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12548. // single gzip coding, and a body the sender says was encoded twice was handed
  12549. // back after one pass, still compressed but presented as decoded.
  12550. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12551. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12552. Server svr;
  12553. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12554. res.set_content(body, "image/jpeg");
  12555. res.headers.emplace("Content-Encoding", "gzip");
  12556. res.headers.emplace("Content-Encoding", "gzip");
  12557. });
  12558. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12559. res.set_content(body, "image/jpeg");
  12560. res.set_header("Content-Encoding", "gzip, gzip");
  12561. });
  12562. auto port = svr.bind_to_any_port(HOST);
  12563. thread t = thread([&]() { svr.listen_after_bind(); });
  12564. auto se = detail::scope_exit([&] {
  12565. svr.stop();
  12566. t.join();
  12567. ASSERT_FALSE(svr.is_running());
  12568. });
  12569. svr.wait_until_ready();
  12570. Client cli(HOST, port);
  12571. // Two codings is not something cpp-httplib decodes, so both representations
  12572. // take the pass-through path rather than one of them being gunzipped once.
  12573. for (const char *path : {"/split", "/joined"}) {
  12574. auto res = cli.Get(path);
  12575. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12576. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12577. EXPECT_EQ(body, res->body) << path;
  12578. }
  12579. }
  12580. // Regression test for DoS vulnerability: a malicious server sending a response
  12581. // without Content-Length header must not cause unbounded memory consumption on
  12582. // the client side. The client should stop reading after a reasonable limit,
  12583. // similar to the server-side set_payload_max_length protection.
  12584. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12585. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12586. #ifndef _WIN32
  12587. signal(SIGPIPE, SIG_IGN);
  12588. #endif
  12589. auto server_thread = std::thread([] {
  12590. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12591. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12592. default_socket_options(srv);
  12593. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12594. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12595. sockaddr_in addr{};
  12596. addr.sin_family = AF_INET;
  12597. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12598. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12599. int opt = 1;
  12600. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12601. #ifdef _WIN32
  12602. reinterpret_cast<const char *>(&opt),
  12603. #else
  12604. &opt,
  12605. #endif
  12606. sizeof(opt));
  12607. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12608. ::listen(srv, 1);
  12609. sockaddr_in cli_addr{};
  12610. socklen_t cli_len = sizeof(cli_addr);
  12611. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12612. if (cli != INVALID_SOCKET) {
  12613. char buf[4096];
  12614. ::recv(cli, buf, sizeof(buf), 0);
  12615. // Malicious response: no Content-Length, no chunked encoding
  12616. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12617. "Connection: close\r\n"
  12618. "\r\n";
  12619. ::send(cli,
  12620. #ifdef _WIN32
  12621. static_cast<const char *>(response_header.c_str()),
  12622. static_cast<int>(response_header.size()),
  12623. #else
  12624. response_header.c_str(), response_header.size(),
  12625. #endif
  12626. 0);
  12627. // Send 10MB of data
  12628. std::string chunk(64 * 1024, 'A');
  12629. size_t total_sent = 0;
  12630. while (total_sent < MALICIOUS_DATA_SIZE) {
  12631. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12632. auto sent = ::send(cli,
  12633. #ifdef _WIN32
  12634. static_cast<const char *>(chunk.c_str()),
  12635. static_cast<int>(to_send),
  12636. #else
  12637. chunk.c_str(), to_send,
  12638. #endif
  12639. 0);
  12640. if (sent <= 0) break;
  12641. total_sent += static_cast<size_t>(sent);
  12642. }
  12643. detail::close_socket(cli);
  12644. }
  12645. detail::close_socket(srv);
  12646. });
  12647. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12648. size_t total_read = 0;
  12649. {
  12650. Client cli("127.0.0.1", PORT + 2);
  12651. cli.set_read_timeout(5, 0);
  12652. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12653. auto stream = cli.open_stream("GET", "/malicious");
  12654. ASSERT_TRUE(stream.is_valid());
  12655. char buffer[64 * 1024];
  12656. ssize_t n;
  12657. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12658. total_read += static_cast<size_t>(n);
  12659. }
  12660. } // StreamHandle and Client destroyed here, closing the socket
  12661. server_thread.join();
  12662. // With set_payload_max_length, the client must stop reading before consuming
  12663. // all 10MB. The read loop should be cut off at or near the configured limit.
  12664. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12665. << "Client read " << total_read << " bytes, exceeding the configured "
  12666. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12667. }
  12668. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12669. // the entire response body without truncation.
  12670. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12671. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12672. #ifndef _WIN32
  12673. signal(SIGPIPE, SIG_IGN);
  12674. #endif
  12675. auto server_thread = std::thread([] {
  12676. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12677. default_socket_options(srv);
  12678. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12679. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12680. sockaddr_in addr{};
  12681. addr.sin_family = AF_INET;
  12682. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12683. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12684. int opt = 1;
  12685. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12686. #ifdef _WIN32
  12687. reinterpret_cast<const char *>(&opt),
  12688. #else
  12689. &opt,
  12690. #endif
  12691. sizeof(opt));
  12692. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12693. ::listen(srv, 1);
  12694. sockaddr_in cli_addr{};
  12695. socklen_t cli_len = sizeof(cli_addr);
  12696. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12697. if (cli != INVALID_SOCKET) {
  12698. char buf[4096];
  12699. ::recv(cli, buf, sizeof(buf), 0);
  12700. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12701. "Connection: close\r\n"
  12702. "\r\n";
  12703. ::send(cli,
  12704. #ifdef _WIN32
  12705. static_cast<const char *>(response_header.c_str()),
  12706. static_cast<int>(response_header.size()),
  12707. #else
  12708. response_header.c_str(), response_header.size(),
  12709. #endif
  12710. 0);
  12711. std::string chunk(64 * 1024, 'A');
  12712. size_t total_sent = 0;
  12713. while (total_sent < DATA_SIZE) {
  12714. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12715. auto sent = ::send(cli,
  12716. #ifdef _WIN32
  12717. static_cast<const char *>(chunk.c_str()),
  12718. static_cast<int>(to_send),
  12719. #else
  12720. chunk.c_str(), to_send,
  12721. #endif
  12722. 0);
  12723. if (sent <= 0) break;
  12724. total_sent += static_cast<size_t>(sent);
  12725. }
  12726. #ifdef _WIN32
  12727. ::shutdown(cli, SD_SEND);
  12728. #else
  12729. ::shutdown(cli, SHUT_WR);
  12730. #endif
  12731. // Drain until the client closes its end, ensuring all data is delivered
  12732. char drain[1024];
  12733. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12734. detail::close_socket(cli);
  12735. }
  12736. detail::close_socket(srv);
  12737. });
  12738. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12739. size_t total_read = 0;
  12740. {
  12741. Client cli("127.0.0.1", PORT + 2);
  12742. cli.set_read_timeout(5, 0);
  12743. cli.set_payload_max_length(0); // 0 means no limit
  12744. auto stream = cli.open_stream("GET", "/data");
  12745. ASSERT_TRUE(stream.is_valid());
  12746. char buffer[64 * 1024];
  12747. ssize_t n;
  12748. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12749. total_read += static_cast<size_t>(n);
  12750. }
  12751. }
  12752. server_thread.join();
  12753. EXPECT_EQ(total_read, DATA_SIZE)
  12754. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12755. << " bytes without truncation, but only read " << total_read << " bytes.";
  12756. }
  12757. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12758. // enormous Content-Length must not cause the client to pre-allocate a huge
  12759. // response body buffer. The reservation is capped at payload_max_length_, and
  12760. // the read itself fails when the body exceeds the limit.
  12761. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12762. #ifndef _WIN32
  12763. signal(SIGPIPE, SIG_IGN);
  12764. #endif
  12765. auto server_thread = std::thread([] {
  12766. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12767. default_socket_options(srv);
  12768. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12769. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12770. sockaddr_in addr{};
  12771. addr.sin_family = AF_INET;
  12772. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12773. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12774. int opt = 1;
  12775. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12776. #ifdef _WIN32
  12777. reinterpret_cast<const char *>(&opt),
  12778. #else
  12779. &opt,
  12780. #endif
  12781. sizeof(opt));
  12782. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12783. ::listen(srv, 1);
  12784. sockaddr_in cli_addr{};
  12785. socklen_t cli_len = sizeof(cli_addr);
  12786. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12787. if (cli != INVALID_SOCKET) {
  12788. char buf[4096];
  12789. ::recv(cli, buf, sizeof(buf), 0);
  12790. // Malicious response: claim a 20GB body but send only a tiny payload.
  12791. std::string response = "HTTP/1.1 200 OK\r\n"
  12792. "Content-Length: 20000000000\r\n"
  12793. "\r\n"
  12794. "abc";
  12795. ::send(cli,
  12796. #ifdef _WIN32
  12797. static_cast<const char *>(response.c_str()),
  12798. static_cast<int>(response.size()),
  12799. #else
  12800. response.c_str(), response.size(),
  12801. #endif
  12802. 0);
  12803. detail::close_socket(cli);
  12804. }
  12805. detail::close_socket(srv);
  12806. });
  12807. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12808. {
  12809. Client cli("127.0.0.1", PORT + 2);
  12810. cli.set_read_timeout(5, 0);
  12811. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12812. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12813. // (server claims more bytes than payload_max_length permits), but it must
  12814. // not exhaust memory before getting there.
  12815. auto res = cli.Get("/malicious");
  12816. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12817. }
  12818. server_thread.join();
  12819. }
  12820. // Verify that content_receiver bypasses the default payload_max_length,
  12821. // allowing streaming downloads larger than 100MB without requiring an explicit
  12822. // set_payload_max_length call.
  12823. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12824. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12825. #ifndef _WIN32
  12826. signal(SIGPIPE, SIG_IGN);
  12827. #endif
  12828. auto server_thread = std::thread([] {
  12829. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12830. default_socket_options(srv);
  12831. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12832. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12833. sockaddr_in addr{};
  12834. addr.sin_family = AF_INET;
  12835. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12836. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12837. int opt = 1;
  12838. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12839. #ifdef _WIN32
  12840. reinterpret_cast<const char *>(&opt),
  12841. #else
  12842. &opt,
  12843. #endif
  12844. sizeof(opt));
  12845. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12846. ::listen(srv, 1);
  12847. sockaddr_in cli_addr{};
  12848. socklen_t cli_len = sizeof(cli_addr);
  12849. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12850. if (cli != INVALID_SOCKET) {
  12851. char buf[4096];
  12852. ::recv(cli, buf, sizeof(buf), 0);
  12853. // Response with Content-Length larger than default 100MB limit
  12854. auto content_length = std::to_string(DATA_SIZE);
  12855. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12856. "Content-Length: " +
  12857. content_length +
  12858. "\r\n"
  12859. "Connection: close\r\n"
  12860. "\r\n";
  12861. ::send(cli,
  12862. #ifdef _WIN32
  12863. static_cast<const char *>(response_header.c_str()),
  12864. static_cast<int>(response_header.size()),
  12865. #else
  12866. response_header.c_str(), response_header.size(),
  12867. #endif
  12868. 0);
  12869. std::string chunk(64 * 1024, 'A');
  12870. size_t total_sent = 0;
  12871. while (total_sent < DATA_SIZE) {
  12872. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12873. auto sent = ::send(cli,
  12874. #ifdef _WIN32
  12875. static_cast<const char *>(chunk.c_str()),
  12876. static_cast<int>(to_send),
  12877. #else
  12878. chunk.c_str(), to_send,
  12879. #endif
  12880. 0);
  12881. if (sent <= 0) break;
  12882. total_sent += static_cast<size_t>(sent);
  12883. }
  12884. detail::close_socket(cli);
  12885. }
  12886. detail::close_socket(srv);
  12887. });
  12888. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12889. size_t total_received = 0;
  12890. {
  12891. Client cli("127.0.0.1", PORT + 2);
  12892. cli.set_read_timeout(10, 0);
  12893. // Do NOT call set_payload_max_length — use the default 100MB limit
  12894. auto res =
  12895. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12896. total_received += data_length;
  12897. return true;
  12898. });
  12899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12900. EXPECT_EQ(StatusCode::OK_200, res->status);
  12901. }
  12902. server_thread.join();
  12903. EXPECT_EQ(total_received, DATA_SIZE)
  12904. << "With content_receiver, the client should read all " << DATA_SIZE
  12905. << " bytes despite the default 100MB payload_max_length, but only read "
  12906. << total_received << " bytes.";
  12907. }
  12908. // Verify that an explicit set_payload_max_length smaller than the response is
  12909. // enforced even when a content_receiver is used.
  12910. TEST(ClientVulnerabilityTest,
  12911. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12912. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12913. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12914. #ifndef _WIN32
  12915. signal(SIGPIPE, SIG_IGN);
  12916. #endif
  12917. auto server_thread = std::thread([] {
  12918. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12919. default_socket_options(srv);
  12920. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12921. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12922. sockaddr_in addr{};
  12923. addr.sin_family = AF_INET;
  12924. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12925. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12926. int opt = 1;
  12927. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12928. #ifdef _WIN32
  12929. reinterpret_cast<const char *>(&opt),
  12930. #else
  12931. &opt,
  12932. #endif
  12933. sizeof(opt));
  12934. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12935. ::listen(srv, 1);
  12936. sockaddr_in cli_addr{};
  12937. socklen_t cli_len = sizeof(cli_addr);
  12938. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12939. if (cli != INVALID_SOCKET) {
  12940. char buf[4096];
  12941. ::recv(cli, buf, sizeof(buf), 0);
  12942. auto content_length = std::to_string(DATA_SIZE);
  12943. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12944. "Content-Length: " +
  12945. content_length +
  12946. "\r\n"
  12947. "Connection: close\r\n"
  12948. "\r\n";
  12949. ::send(cli,
  12950. #ifdef _WIN32
  12951. static_cast<const char *>(response_header.c_str()),
  12952. static_cast<int>(response_header.size()),
  12953. #else
  12954. response_header.c_str(), response_header.size(),
  12955. #endif
  12956. 0);
  12957. std::string chunk(64 * 1024, 'A');
  12958. size_t total_sent = 0;
  12959. while (total_sent < DATA_SIZE) {
  12960. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12961. auto sent = ::send(cli,
  12962. #ifdef _WIN32
  12963. static_cast<const char *>(chunk.c_str()),
  12964. static_cast<int>(to_send),
  12965. #else
  12966. chunk.c_str(), to_send,
  12967. #endif
  12968. 0);
  12969. if (sent <= 0) break;
  12970. total_sent += static_cast<size_t>(sent);
  12971. }
  12972. detail::close_socket(cli);
  12973. }
  12974. detail::close_socket(srv);
  12975. });
  12976. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12977. size_t total_received = 0;
  12978. {
  12979. Client cli("127.0.0.1", PORT + 2);
  12980. cli.set_read_timeout(10, 0);
  12981. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12982. auto res =
  12983. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12984. total_received += data_length;
  12985. return true;
  12986. });
  12987. // Should fail because 200MB exceeds the explicit 150MB limit
  12988. EXPECT_FALSE(res);
  12989. }
  12990. server_thread.join();
  12991. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12992. << "Client with content_receiver should respect the explicit "
  12993. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12994. << total_received << " bytes.";
  12995. }
  12996. // Verify that an explicit set_payload_max_length larger than the response
  12997. // allows the content_receiver to read all data successfully.
  12998. TEST(ClientVulnerabilityTest,
  12999. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13000. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13001. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13002. #ifndef _WIN32
  13003. signal(SIGPIPE, SIG_IGN);
  13004. #endif
  13005. auto server_thread = std::thread([] {
  13006. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13007. default_socket_options(srv);
  13008. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13009. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13010. sockaddr_in addr{};
  13011. addr.sin_family = AF_INET;
  13012. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13013. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13014. int opt = 1;
  13015. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13016. #ifdef _WIN32
  13017. reinterpret_cast<const char *>(&opt),
  13018. #else
  13019. &opt,
  13020. #endif
  13021. sizeof(opt));
  13022. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13023. ::listen(srv, 1);
  13024. sockaddr_in cli_addr{};
  13025. socklen_t cli_len = sizeof(cli_addr);
  13026. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13027. if (cli != INVALID_SOCKET) {
  13028. char buf[4096];
  13029. ::recv(cli, buf, sizeof(buf), 0);
  13030. auto content_length = std::to_string(DATA_SIZE);
  13031. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13032. "Content-Length: " +
  13033. content_length +
  13034. "\r\n"
  13035. "Connection: close\r\n"
  13036. "\r\n";
  13037. ::send(cli,
  13038. #ifdef _WIN32
  13039. static_cast<const char *>(response_header.c_str()),
  13040. static_cast<int>(response_header.size()),
  13041. #else
  13042. response_header.c_str(), response_header.size(),
  13043. #endif
  13044. 0);
  13045. std::string chunk(64 * 1024, 'A');
  13046. size_t total_sent = 0;
  13047. while (total_sent < DATA_SIZE) {
  13048. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13049. auto sent = ::send(cli,
  13050. #ifdef _WIN32
  13051. static_cast<const char *>(chunk.c_str()),
  13052. static_cast<int>(to_send),
  13053. #else
  13054. chunk.c_str(), to_send,
  13055. #endif
  13056. 0);
  13057. if (sent <= 0) break;
  13058. total_sent += static_cast<size_t>(sent);
  13059. }
  13060. #ifdef _WIN32
  13061. ::shutdown(cli, SD_SEND);
  13062. #else
  13063. ::shutdown(cli, SHUT_WR);
  13064. #endif
  13065. char drain[1024];
  13066. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13067. detail::close_socket(cli);
  13068. }
  13069. detail::close_socket(srv);
  13070. });
  13071. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13072. size_t total_received = 0;
  13073. {
  13074. Client cli("127.0.0.1", PORT + 2);
  13075. cli.set_read_timeout(10, 0);
  13076. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13077. auto res =
  13078. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13079. total_received += data_length;
  13080. return true;
  13081. });
  13082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13083. EXPECT_EQ(StatusCode::OK_200, res->status);
  13084. }
  13085. server_thread.join();
  13086. EXPECT_EQ(total_received, DATA_SIZE)
  13087. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13088. << " bytes (larger than " << DATA_SIZE
  13089. << " bytes response), content_receiver should read all data, but only "
  13090. "read "
  13091. << total_received << " bytes.";
  13092. }
  13093. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13094. // Regression test for "zip bomb" attack on the client side: a malicious server
  13095. // sends a small gzip-compressed response that decompresses to a huge payload.
  13096. // The client must enforce payload_max_length on the decompressed size.
  13097. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13098. constexpr size_t DECOMPRESSED_SIZE =
  13099. 10 * 1024 * 1024; // 10MB after decompression
  13100. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13101. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13102. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13103. std::string compressed;
  13104. {
  13105. httplib::detail::gzip_compressor compressor;
  13106. bool ok =
  13107. compressor.compress(uncompressed.data(), uncompressed.size(),
  13108. /*last=*/true, [&](const char *buf, size_t len) {
  13109. compressed.append(buf, len);
  13110. return true;
  13111. });
  13112. ASSERT_TRUE(ok);
  13113. }
  13114. // Sanity: compressed data should be much smaller than the decompressed size
  13115. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13116. #ifndef _WIN32
  13117. signal(SIGPIPE, SIG_IGN);
  13118. #endif
  13119. // Set up the listening socket in the main thread so the server is guaranteed
  13120. // to be ready before the client connects (eliminates race condition).
  13121. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13122. default_socket_options(srv);
  13123. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13124. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13125. sockaddr_in addr{};
  13126. addr.sin_family = AF_INET;
  13127. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13128. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13129. int opt = 1;
  13130. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13131. #ifdef _WIN32
  13132. reinterpret_cast<const char *>(&opt),
  13133. #else
  13134. &opt,
  13135. #endif
  13136. sizeof(opt));
  13137. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13138. ASSERT_EQ(0, ::listen(srv, 1));
  13139. auto server_thread = std::thread([&compressed, srv] {
  13140. sockaddr_in cli_addr{};
  13141. socklen_t cli_len = sizeof(cli_addr);
  13142. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13143. if (cli != INVALID_SOCKET) {
  13144. // Read the full HTTP request (until \r\n\r\n)
  13145. char buf[4096];
  13146. size_t total = 0;
  13147. while (total < sizeof(buf)) {
  13148. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13149. if (n <= 0) break;
  13150. total += static_cast<size_t>(n);
  13151. // Check for end of headers
  13152. if (total >= 4) {
  13153. std::string req(buf, total);
  13154. if (req.find("\r\n\r\n") != std::string::npos) break;
  13155. }
  13156. }
  13157. // Malicious response: gzip-compressed body, no Content-Length
  13158. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13159. "Content-Encoding: gzip\r\n"
  13160. "Connection: close\r\n"
  13161. "\r\n";
  13162. ::send(cli,
  13163. #ifdef _WIN32
  13164. static_cast<const char *>(response_header.c_str()),
  13165. static_cast<int>(response_header.size()),
  13166. #else
  13167. response_header.c_str(), response_header.size(),
  13168. #endif
  13169. 0);
  13170. // Send the compressed payload (small on the wire, huge when decompressed)
  13171. size_t total_sent = 0;
  13172. while (total_sent < compressed.size()) {
  13173. auto to_send = std::min(compressed.size() - total_sent,
  13174. static_cast<size_t>(64 * 1024));
  13175. auto sent =
  13176. ::send(cli,
  13177. #ifdef _WIN32
  13178. static_cast<const char *>(compressed.c_str() + total_sent),
  13179. static_cast<int>(to_send),
  13180. #else
  13181. compressed.c_str() + total_sent, to_send,
  13182. #endif
  13183. 0);
  13184. if (sent <= 0) break;
  13185. total_sent += static_cast<size_t>(sent);
  13186. }
  13187. detail::close_socket(cli);
  13188. }
  13189. });
  13190. auto se = detail::scope_exit([&] {
  13191. detail::close_socket(srv);
  13192. server_thread.join();
  13193. });
  13194. size_t total_decompressed = 0;
  13195. {
  13196. Client cli("127.0.0.1", PORT + 3);
  13197. cli.set_read_timeout(5, 0);
  13198. cli.set_decompress(true);
  13199. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13200. auto stream = cli.open_stream("GET", "/zipbomb");
  13201. ASSERT_TRUE(stream.is_valid());
  13202. char buffer[64 * 1024];
  13203. ssize_t n;
  13204. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13205. total_decompressed += static_cast<size_t>(n);
  13206. }
  13207. }
  13208. // The decompressed size must be capped by payload_max_length. Without
  13209. // protection, the client would decompress the full 10MB from a tiny
  13210. // compressed payload, enabling a zip bomb DoS attack.
  13211. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13212. << "Client decompressed " << total_decompressed
  13213. << " bytes from a gzip response. The decompressed size should be "
  13214. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13215. }
  13216. #endif
  13217. TEST(HostAndPortPropertiesTest, NoSSL) {
  13218. httplib::Client cli("www.google.com", 1234);
  13219. ASSERT_EQ("www.google.com", cli.host());
  13220. ASSERT_EQ(1234, cli.port());
  13221. }
  13222. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13223. httplib::Client cli("www.google.com:1234");
  13224. ASSERT_EQ("www.google.com", cli.host());
  13225. ASSERT_EQ(1234, cli.port());
  13226. }
  13227. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13228. // Port number that overflows int — should not crash, client becomes invalid
  13229. httplib::Client cli("http://www.google.com:99999999999999999999");
  13230. ASSERT_FALSE(cli.is_valid());
  13231. }
  13232. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13233. // Port 99999 exceeds valid range (1-65535) — should not crash
  13234. httplib::Client cli("http://www.google.com:99999");
  13235. ASSERT_FALSE(cli.is_valid());
  13236. auto res = cli.Get("/");
  13237. EXPECT_FALSE(res);
  13238. EXPECT_EQ(Error::Connection, res.error());
  13239. }
  13240. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13241. httplib::Client cli("http://user:pass@localhost:1234");
  13242. ASSERT_FALSE(cli.is_valid());
  13243. EXPECT_FALSE(cli.Get("/"));
  13244. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13245. }
  13246. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13247. httplib::Client cli("http://www.google.com:80abc");
  13248. ASSERT_FALSE(cli.is_valid());
  13249. }
  13250. #ifdef CPPHTTPLIB_SSL_ENABLED
  13251. TEST(HostAndPortPropertiesTest, SSL) {
  13252. httplib::SSLClient cli("www.google.com");
  13253. ASSERT_EQ("www.google.com", cli.host());
  13254. ASSERT_EQ(443, cli.port());
  13255. }
  13256. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13257. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13258. std::string cert;
  13259. read_file(CA_CERT_FILE, cert);
  13260. httplib::SSLClient httplib_client("www.google.com");
  13261. // Load CA store first time
  13262. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13263. // Load CA store second time (update)
  13264. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13265. // Verify client is still valid and can make connections
  13266. httplib_client.enable_server_certificate_verification(true);
  13267. auto res = httplib_client.Get("/");
  13268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13269. // Google may return 200 or 301 depending on various factors
  13270. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13271. res->status == StatusCode::MovedPermanently_301);
  13272. }
  13273. TEST(SSLClientTest, ServerNameIndication_Online) {
  13274. auto host = "httpbingo.org";
  13275. auto path = std::string{"/get"};
  13276. SSLClient cli(host, 443);
  13277. auto res = cli.Get(path);
  13278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13279. ASSERT_EQ(StatusCode::OK_200, res->status);
  13280. }
  13281. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13282. // Use a site that will cause SSL verification failure due to self-signed cert
  13283. SSLClient cli("self-signed.badssl.com", 443);
  13284. cli.enable_server_certificate_verification(true);
  13285. auto res = cli.Get("/");
  13286. ASSERT_TRUE(!res);
  13287. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13288. // Verify backend error is captured for SSLServerVerification
  13289. // This occurs when certificate verification fails
  13290. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13291. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13292. EXPECT_NE(0UL, res.ssl_backend_error());
  13293. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13294. res.ssl_error());
  13295. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13296. #if !defined(_WIN32) || \
  13297. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13298. // On non-Windows or when Windows Schannel is disabled, the error comes
  13299. // from OpenSSL's verification
  13300. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13301. res.ssl_backend_error());
  13302. #endif
  13303. #endif
  13304. }
  13305. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13306. // Use a site where hostname doesn't match the certificate
  13307. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13308. SSLClient cli("wrong.host.badssl.com", 443);
  13309. cli.enable_server_certificate_verification(true);
  13310. cli.enable_server_hostname_verification(true);
  13311. auto res = cli.Get("/");
  13312. ASSERT_TRUE(!res);
  13313. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13314. // Verify backend error is captured for hostname verification failure
  13315. EXPECT_NE(0UL, res.ssl_backend_error());
  13316. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13317. res.ssl_error());
  13318. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13319. #if !defined(_WIN32) || \
  13320. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13321. // On non-Windows or when Windows Schannel is disabled, the error comes
  13322. // from OpenSSL's hostname verification
  13323. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13324. res.ssl_backend_error());
  13325. #endif
  13326. #endif
  13327. }
  13328. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13329. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13330. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13331. SSLClient cli("www.google.com", 443);
  13332. cli.enable_server_certificate_verification(true);
  13333. auto res = cli.Get("/");
  13334. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13335. }
  13336. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13337. SSLClient cli("www.google.com", 443);
  13338. cli.enable_server_certificate_verification(true);
  13339. cli.enable_windows_certificate_verification(false);
  13340. auto res = cli.Get("/");
  13341. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13342. }
  13343. // The server sends an intermediate cross-signed by a root Windows trusts,
  13344. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13345. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13346. SSLClient cli("accounts.spotify.com", 443);
  13347. auto res = cli.Get("/");
  13348. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13349. << " ssl_backend_error=" << res.ssl_backend_error();
  13350. }
  13351. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13352. // policy status, which no backend reports for a self-signed certificate.
  13353. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13354. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13355. ASSERT_TRUE(svr.is_valid());
  13356. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13357. auto se = detail::scope_exit([&] {
  13358. svr.stop();
  13359. t.join();
  13360. ASSERT_FALSE(svr.is_running());
  13361. });
  13362. svr.wait_until_ready();
  13363. SSLClient cli("127.0.0.1", PORT);
  13364. cli.set_connection_timeout(30);
  13365. auto res = cli.Get("/");
  13366. ASSERT_FALSE(res);
  13367. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13368. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13369. }
  13370. #endif
  13371. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13372. Client cli("https://google.com");
  13373. auto res = cli.Get("/");
  13374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13375. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13376. }
  13377. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13378. SSLClient cli("google.com");
  13379. cli.set_ca_cert_path(CA_CERT_FILE);
  13380. auto res = cli.Get("/");
  13381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13382. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13383. }
  13384. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13385. SSLClient cli("google.com");
  13386. cli.enable_server_certificate_verification(true);
  13387. cli.set_ca_cert_path("hello");
  13388. auto res = cli.Get("/");
  13389. ASSERT_TRUE(!res);
  13390. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13391. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13392. // should be set
  13393. EXPECT_EQ(0, res.ssl_error());
  13394. // Verify backend error is captured for SSLLoadingCerts
  13395. // This error occurs when loading CA certificates fails
  13396. EXPECT_NE(0UL, res.ssl_backend_error());
  13397. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13398. // OpenSSL specific error codes:
  13399. // > openssl errstr 0x80000002
  13400. // error:80000002:system library::No such file or directory
  13401. // > openssl errstr 0xA000126
  13402. // error:0A000126:SSL routines::unexpected eof while reading
  13403. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13404. res.ssl_backend_error() == 0xA000126);
  13405. #endif
  13406. }
  13407. TEST(SSLClientTest, ServerCertificateVerification4) {
  13408. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13409. ASSERT_TRUE(svr.is_valid());
  13410. svr.Get("/test", [&](const Request &, Response &res) {
  13411. res.set_content("test", "text/plain");
  13412. svr.stop();
  13413. ASSERT_TRUE(true);
  13414. });
  13415. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13416. auto se = detail::scope_exit([&] {
  13417. t.join();
  13418. ASSERT_FALSE(svr.is_running());
  13419. });
  13420. svr.wait_until_ready();
  13421. SSLClient cli("127.0.0.1", PORT);
  13422. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13423. cli.enable_server_certificate_verification(true);
  13424. cli.set_connection_timeout(30);
  13425. auto res = cli.Get("/test");
  13426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13427. ASSERT_EQ(StatusCode::OK_200, res->status);
  13428. }
  13429. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13430. std::string cert;
  13431. read_file(CA_CERT_FILE, cert);
  13432. SSLClient cli("google.com");
  13433. cli.load_ca_cert_store(cert.data(), cert.size());
  13434. const auto res = cli.Get("/");
  13435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13436. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13437. }
  13438. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13439. // clang-format off
  13440. static constexpr char cert[] =
  13441. "GlobalSign Root CA\n"
  13442. "==================\n"
  13443. "-----BEGIN CERTIFICATE-----\n"
  13444. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13445. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13446. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13447. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13448. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13449. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13450. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13451. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13452. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13453. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13454. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13455. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13456. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13457. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13458. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13459. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13460. "-----END CERTIFICATE-----\n";
  13461. // clang-format on
  13462. SSLClient cli("google.com");
  13463. cli.load_ca_cert_store(cert, sizeof(cert));
  13464. const auto res = cli.Get("/");
  13465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13466. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13467. }
  13468. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13469. SSLClient cli("www.youtube.com");
  13470. cli.set_ca_cert_path(CA_CERT_FILE);
  13471. cli.enable_server_certificate_verification(true);
  13472. cli.set_follow_location(true);
  13473. auto res = cli.Get("/");
  13474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13475. ASSERT_EQ(StatusCode::OK_200, res->status);
  13476. }
  13477. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13478. SSLClient cli("wWw.YouTube.Com");
  13479. cli.set_ca_cert_path(CA_CERT_FILE);
  13480. cli.enable_server_certificate_verification(true);
  13481. cli.enable_server_hostname_verification(true);
  13482. cli.set_follow_location(true);
  13483. auto res = cli.Get("/");
  13484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13485. ASSERT_EQ(StatusCode::OK_200, res->status);
  13486. }
  13487. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13488. SSLClient cli("gOoGlE.COm");
  13489. cli.enable_server_certificate_verification(true);
  13490. cli.enable_server_hostname_verification(true);
  13491. cli.set_follow_location(true);
  13492. auto res = cli.Get("/");
  13493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13494. ASSERT_EQ(StatusCode::OK_200, res->status);
  13495. }
  13496. TEST(SSLClientTest, Issue2004_Online) {
  13497. Client client("https://google.com");
  13498. client.set_follow_location(true);
  13499. auto res = client.Get("/");
  13500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13501. ASSERT_EQ(StatusCode::OK_200, res->status);
  13502. auto body = res->body;
  13503. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13504. }
  13505. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13506. // Create SSLClient with invalid cert/key to make is_valid() return false
  13507. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13508. "nonexistent_key.pem");
  13509. // is_valid() should be false due to cert loading failure
  13510. ASSERT_FALSE(cli.is_valid());
  13511. auto res = cli.Get("/");
  13512. ASSERT_FALSE(res);
  13513. EXPECT_EQ(Error::SSLConnection, res.error());
  13514. }
  13515. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13516. // Test for Issue #2251: SSL error not properly reported when client cert
  13517. // and key paths are swapped or mismatched
  13518. // This simulates the scenario where user accidentally swaps the cert and key
  13519. // files
  13520. // Using client cert file as private key and vice versa (completely wrong)
  13521. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13522. // Should fail validation due to cert/key mismatch
  13523. ASSERT_FALSE(cli.is_valid());
  13524. // Attempt to make a request should fail with proper error
  13525. auto res = cli.Get("/");
  13526. ASSERT_FALSE(res);
  13527. EXPECT_EQ(Error::SSLConnection, res.error());
  13528. // SSL error should be recorded in the Result object (this is the key fix for
  13529. // Issue #2251)
  13530. auto backend_error = res.ssl_backend_error();
  13531. EXPECT_NE(0u, backend_error);
  13532. }
  13533. // Tests cert/key mismatch detection at the TLS context level
  13534. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13535. // Test that using mismatched cert/key causes connection failure.
  13536. // We verify this at the SSLClient level rather than through internal
  13537. // TLS API functions.
  13538. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13539. cli.enable_server_certificate_verification(false);
  13540. cli.set_connection_timeout(2);
  13541. // The mismatch should cause a connection or handshake error
  13542. auto res = cli.Get("/test");
  13543. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13544. // Either way, the request should fail
  13545. EXPECT_FALSE(res);
  13546. }
  13547. #endif
  13548. #if 0
  13549. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13550. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13551. ASSERT_TRUE(cli != nullptr);
  13552. cli->set_address_family(AF_INET6);
  13553. cli->set_interface("en0");
  13554. auto res = cli->Get("/get");
  13555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13556. ASSERT_EQ(StatusCode::OK_200, res->status);
  13557. }
  13558. #endif
  13559. // Client certificate tests - work with all TLS backends
  13560. #ifdef CPPHTTPLIB_SSL_ENABLED
  13561. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13562. void ClientCertPresent(
  13563. const std::string &client_cert_file,
  13564. const std::string &client_private_key_file,
  13565. const std::string &client_encrypted_private_key_pass = std::string(),
  13566. const ClientCertServerSetup &setup = nullptr) {
  13567. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13568. ASSERT_TRUE(svr.is_valid());
  13569. if (setup) { setup(svr); }
  13570. svr.Get("/test", [&](const Request &req, Response &res) {
  13571. res.set_content("test", "text/plain");
  13572. auto cert = req.peer_cert();
  13573. ASSERT_TRUE(static_cast<bool>(cert));
  13574. std::string common_name = cert.subject_cn();
  13575. EXPECT_EQ("Common Name", common_name);
  13576. });
  13577. auto port = svr.bind_to_any_port(HOST);
  13578. ASSERT_LT(0, port);
  13579. thread t = thread([&]() { svr.listen_after_bind(); });
  13580. auto se = detail::scope_exit([&] {
  13581. svr.stop();
  13582. t.join();
  13583. ASSERT_FALSE(svr.is_running());
  13584. });
  13585. svr.wait_until_ready();
  13586. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13587. client_encrypted_private_key_pass);
  13588. cli.enable_server_certificate_verification(false);
  13589. cli.set_connection_timeout(30);
  13590. auto res = cli.Get("/test");
  13591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13592. ASSERT_EQ(StatusCode::OK_200, res->status);
  13593. }
  13594. TEST(SSLClientServerTest, ClientCertPresent) {
  13595. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13596. }
  13597. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13598. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13599. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13600. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13601. }
  13602. // Expects svr, which must require client certificates, to reject a client
  13603. // that has none
  13604. void RejectsClientWithoutCert(SSLServer &svr) {
  13605. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13606. auto port = svr.bind_to_any_port(HOST);
  13607. ASSERT_LT(0, port);
  13608. thread t = thread([&]() { svr.listen_after_bind(); });
  13609. auto se = detail::scope_exit([&] {
  13610. svr.stop();
  13611. t.join();
  13612. ASSERT_FALSE(svr.is_running());
  13613. });
  13614. svr.wait_until_ready();
  13615. SSLClient cli(HOST, port);
  13616. cli.set_connection_timeout(30);
  13617. // Skip the server certificate check, so that the request fails because the
  13618. // client certificate is missing rather than because cert.pem is not trusted
  13619. cli.enable_server_certificate_verification(false);
  13620. auto res = cli.Get("/test");
  13621. ASSERT_FALSE(res);
  13622. // The server rejects the client during the handshake, or on TLS 1.3 right
  13623. // after it, which the client notices on its first write or read
  13624. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13625. res.error() == Error::Write || res.error() == Error::Read)
  13626. << to_string(res.error());
  13627. if (res.error() == Error::SSLConnection) {
  13628. EXPECT_NE(0UL, res.ssl_backend_error());
  13629. }
  13630. // A rejection noticed on the write keeps the TLS error the write hit
  13631. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13632. }
  13633. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13635. ASSERT_TRUE(svr.is_valid());
  13636. if (setup) { setup(svr); }
  13637. RejectsClientWithoutCert(svr);
  13638. }
  13639. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13640. // A server that requires client certificates must keep requiring them after
  13641. // setup changes it, and keep accepting a client that has one
  13642. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13643. ClientCertMissing(setup);
  13644. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13645. setup);
  13646. }
  13647. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13648. ClientCertStillRequired([](SSLServer &svr) {
  13649. ASSERT_TRUE(tls::set_verify_callback(
  13650. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13651. });
  13652. }
  13653. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13654. ClientCertStillRequired([](SSLServer &svr) {
  13655. ASSERT_TRUE(tls::set_verify_callback(
  13656. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13657. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13658. });
  13659. }
  13660. // The client verifies the server certificate during the handshake, so a
  13661. // server that fails the check never gets the client certificate, even when a
  13662. // verifier of the client's own accepts it
  13663. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13664. struct Case {
  13665. const char *trusted_ca;
  13666. const char *host;
  13667. Error error;
  13668. };
  13669. // cert2.pem names localhost: the first client does not trust it, and the
  13670. // second trusts it but asks for another name
  13671. for (const auto &c :
  13672. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13673. Case{SERVER_CERT2_FILE, "example.com",
  13674. Error::SSLServerHostnameVerification}}) {
  13675. for (auto with_verifier : {false, true}) {
  13676. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13677. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13678. CLIENT_CA_CERT_FILE);
  13679. ASSERT_TRUE(svr.is_valid());
  13680. std::atomic<bool> got_client_cert{false};
  13681. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13682. [&](const tls::VerifyContext &) {
  13683. got_client_cert = true;
  13684. return true;
  13685. }));
  13686. auto port = svr.bind_to_any_port("127.0.0.1");
  13687. ASSERT_LT(0, port);
  13688. thread t = thread([&] { svr.listen_after_bind(); });
  13689. svr.wait_until_ready();
  13690. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13691. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13692. cli.set_ca_cert_path(c.trusted_ca);
  13693. if (with_verifier) {
  13694. cli.set_server_certificate_verifier(
  13695. [](const tls::VerifyContext &) { return true; });
  13696. }
  13697. auto res = cli.Get("/");
  13698. EXPECT_FALSE(res);
  13699. EXPECT_EQ(c.error, res.error());
  13700. svr.stop();
  13701. t.join();
  13702. EXPECT_FALSE(got_client_cert);
  13703. }
  13704. }
  13705. }
  13706. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13707. std::string cert_pem, key_pem, ca_pem;
  13708. read_file(SERVER_CERT_FILE, cert_pem);
  13709. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13710. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13711. ASSERT_TRUE(
  13712. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13713. }
  13714. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13716. ASSERT_TRUE(svr.is_valid());
  13717. UpdateCertsPemWithClientCA(svr);
  13718. RejectsClientWithoutCert(svr);
  13719. }
  13720. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13721. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13722. }
  13723. // A TLS error from one request must not show up in a later request's Result
  13724. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13726. ASSERT_TRUE(svr.is_valid());
  13727. svr.Get("/test", [](const Request &, Response &res) {
  13728. res.set_content("test", "text/plain");
  13729. });
  13730. auto port = svr.bind_to_any_port(HOST);
  13731. ASSERT_LT(0, port);
  13732. thread t = thread([&]() { svr.listen_after_bind(); });
  13733. auto se = detail::scope_exit([&] {
  13734. svr.stop();
  13735. t.join();
  13736. ASSERT_FALSE(svr.is_running());
  13737. });
  13738. svr.wait_until_ready();
  13739. SSLClient cli(HOST, port);
  13740. cli.set_connection_timeout(30);
  13741. cli.enable_server_hostname_verification(false);
  13742. // cert.pem is not trusted, so the handshake fails
  13743. ASSERT_FALSE(cli.Get("/test"));
  13744. cli.enable_server_certificate_verification(false);
  13745. auto res = cli.Get("/test");
  13746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13747. EXPECT_EQ(0, res.ssl_error());
  13748. EXPECT_EQ(0UL, res.ssl_backend_error());
  13749. }
  13750. // PEM memory-based constructor tests (works with all TLS backends).
  13751. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13752. // terminator after it.
  13753. void PemMemoryClientCertPresent(
  13754. const std::string &client_cert_file,
  13755. const std::string &client_private_key_file,
  13756. const std::string &client_encrypted_private_key_pass = std::string(),
  13757. bool exact_size = false) {
  13758. // Read PEM files into memory
  13759. std::string server_cert_pem, server_key_pem;
  13760. std::string client_ca_pem;
  13761. std::string client_cert_pem, client_key_pem;
  13762. read_file(SERVER_CERT_FILE, server_cert_pem);
  13763. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13764. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13765. read_file(client_cert_file, client_cert_pem);
  13766. read_file(client_private_key_file, client_key_pem);
  13767. std::list<std::vector<char>> exact_copies;
  13768. auto data = [&](const std::string &pem) -> const char * {
  13769. if (!exact_size) { return pem.c_str(); }
  13770. exact_copies.emplace_back(pem.begin(), pem.end());
  13771. return exact_copies.back().data();
  13772. };
  13773. // Create server with PEM memory
  13774. SSLServer::PemMemory server_pem = {
  13775. data(server_cert_pem),
  13776. server_cert_pem.size(),
  13777. data(server_key_pem),
  13778. server_key_pem.size(),
  13779. data(client_ca_pem),
  13780. client_ca_pem.size(),
  13781. nullptr // no password for server key
  13782. };
  13783. SSLServer svr(server_pem);
  13784. ASSERT_TRUE(svr.is_valid());
  13785. svr.Get("/test", [&](const Request &req, Response &res) {
  13786. res.set_content("test", "text/plain");
  13787. auto cert = req.peer_cert();
  13788. ASSERT_TRUE(static_cast<bool>(cert));
  13789. EXPECT_EQ("Common Name", cert.subject_cn());
  13790. });
  13791. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13792. auto se = detail::scope_exit([&] {
  13793. svr.stop();
  13794. t.join();
  13795. ASSERT_FALSE(svr.is_running());
  13796. });
  13797. svr.wait_until_ready();
  13798. // Create client with PEM memory
  13799. const char *password = client_encrypted_private_key_pass.empty()
  13800. ? nullptr
  13801. : client_encrypted_private_key_pass.c_str();
  13802. SSLClient::PemMemory client_pem = {
  13803. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13804. client_key_pem.size(), password};
  13805. SSLClient cli(HOST, PORT, client_pem);
  13806. cli.enable_server_certificate_verification(false);
  13807. cli.set_connection_timeout(30);
  13808. auto res = cli.Get("/test");
  13809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13810. ASSERT_EQ(StatusCode::OK_200, res->status);
  13811. }
  13812. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13813. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13814. }
  13815. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13816. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13817. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13818. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13819. }
  13820. // A server built from PEM memory with a client CA requires client certificates,
  13821. // also when the CA is a NUL-terminated string passed with a length of 0
  13822. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13823. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13824. read_file(SERVER_CERT_FILE, server_cert_pem);
  13825. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13826. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13827. SSLServer::PemMemory server_pem = {
  13828. server_cert_pem.c_str(),
  13829. server_cert_pem.size(),
  13830. server_key_pem.c_str(),
  13831. server_key_pem.size(),
  13832. client_ca_pem.c_str(),
  13833. client_ca_pem.size(),
  13834. nullptr // no password for server key
  13835. };
  13836. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13837. SCOPED_TRACE(client_ca_pem_len);
  13838. server_pem.client_ca_pem_len = client_ca_pem_len;
  13839. SSLServer svr(server_pem);
  13840. ASSERT_TRUE(svr.is_valid());
  13841. RejectsClientWithoutCert(svr);
  13842. }
  13843. // An empty CA fails to load instead of turning the check off
  13844. server_pem.client_ca_pem = "";
  13845. server_pem.client_ca_pem_len = 0;
  13846. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13847. }
  13848. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13849. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13850. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13851. true);
  13852. }
  13853. // A length shorter than the PEM cuts it short, so it no longer loads
  13854. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13855. std::string cert, key;
  13856. read_file(SERVER_CERT_FILE, cert);
  13857. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13858. for (auto cut_cert : {true, false}) {
  13859. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13860. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13861. SSLServer::PemMemory server_pem = {
  13862. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13863. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13864. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13865. key_len, nullptr};
  13866. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13867. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13868. key.c_str(), key_len, nullptr};
  13869. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13870. }
  13871. }
  13872. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13873. class NoListenSSLServer : public SSLServer {
  13874. public:
  13875. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13876. const char *client_ca_cert_file_path,
  13877. const char *client_ca_cert_dir_path = nullptr)
  13878. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13879. client_ca_cert_dir_path),
  13880. stop_(false) {}
  13881. std::atomic_bool stop_;
  13882. private:
  13883. bool process_and_close_socket(socket_t /*sock*/) override {
  13884. // Don't create SSL context
  13885. while (!stop_.load()) {
  13886. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13887. }
  13888. return true;
  13889. }
  13890. };
  13891. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13892. CLIENT_CA_CERT_FILE);
  13893. ASSERT_TRUE(svr.is_valid());
  13894. svr.Get("/test", [&](const Request &, Response &res) {
  13895. res.set_content("test", "text/plain");
  13896. });
  13897. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13898. auto se = detail::scope_exit([&] {
  13899. svr.stop_ = true;
  13900. svr.stop();
  13901. t.join();
  13902. ASSERT_FALSE(svr.is_running());
  13903. });
  13904. svr.wait_until_ready();
  13905. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13906. cli.enable_server_certificate_verification(false);
  13907. cli.set_connection_timeout(1);
  13908. auto res = cli.Get("/test");
  13909. ASSERT_TRUE(!res);
  13910. EXPECT_EQ(Error::SSLConnection, res.error());
  13911. // Timeout results in WantRead error code (maps to backend-specific value)
  13912. EXPECT_NE(0, res.ssl_error());
  13913. }
  13914. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13915. // Test SSLServer with client certificate verification using the standard
  13916. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13917. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13918. CLIENT_CA_CERT_DIR);
  13919. ASSERT_TRUE(svr.is_valid());
  13920. svr.Get("/test", [&](const Request &req, Response &res) {
  13921. res.set_content("test", "text/plain");
  13922. auto cert = req.peer_cert();
  13923. ASSERT_TRUE(static_cast<bool>(cert));
  13924. auto common_name = cert.subject_cn();
  13925. EXPECT_EQ("Common Name", common_name);
  13926. });
  13927. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13928. auto se = detail::scope_exit([&] {
  13929. svr.stop();
  13930. t.join();
  13931. ASSERT_FALSE(svr.is_running());
  13932. });
  13933. svr.wait_until_ready();
  13934. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13935. cli.enable_server_certificate_verification(false);
  13936. cli.set_connection_timeout(30);
  13937. auto res = cli.Get("/test");
  13938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13939. ASSERT_EQ(StatusCode::OK_200, res->status);
  13940. }
  13941. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13942. // Verifies that wildcard matching and exact matching work consistently
  13943. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13944. using namespace httplib::tls;
  13945. // We need a running server to test against
  13946. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13947. ASSERT_TRUE(svr.is_valid());
  13948. svr.Get("/test", [](const Request &, Response &res) {
  13949. res.set_content("ok", "text/plain");
  13950. });
  13951. thread t([&]() { svr.listen(HOST, PORT); });
  13952. auto se = detail::scope_exit([&] {
  13953. svr.stop();
  13954. t.join();
  13955. });
  13956. svr.wait_until_ready();
  13957. bool verify_callback_called = false;
  13958. bool verify_result_wrong = false;
  13959. SSLClient cli(HOST, PORT);
  13960. cli.enable_server_certificate_verification(true);
  13961. cli.set_ca_cert_path(CA_CERT_FILE);
  13962. cli.set_connection_timeout(5);
  13963. // Note: Test certificate has CN="Common Name", not "localhost"
  13964. bool verify_result_cn = false;
  13965. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13966. verify_callback_called = true;
  13967. if (!ctx.cert) return false;
  13968. // Test 1: "Common Name" should match (our test server cert CN)
  13969. verify_result_cn = ctx.check_hostname("Common Name");
  13970. // Test 2: wrong hostname should not match
  13971. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13972. return true; // Accept for the purpose of this test
  13973. });
  13974. auto res = cli.Get("/test");
  13975. // The request may succeed or fail depending on cert configuration
  13976. // but the callback should have been called
  13977. ASSERT_TRUE(verify_callback_called)
  13978. << "Verify callback should have been called";
  13979. // CN="Common Name" should match our test certificate
  13980. //
  13981. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13982. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13983. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13984. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13985. // <openssl/base.h>, which is included transitively when
  13986. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13987. #if defined(OPENSSL_IS_BORINGSSL)
  13988. EXPECT_FALSE(verify_result_cn)
  13989. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13990. #else
  13991. EXPECT_TRUE(verify_result_cn)
  13992. << "verify_hostname should match 'Common Name' (certificate CN)";
  13993. #endif
  13994. // Wrong hostname should not match
  13995. EXPECT_FALSE(verify_result_wrong)
  13996. << "verify_hostname should not match 'wronghost.example.com'";
  13997. }
  13998. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13999. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14000. // X509_check_ip behavior and must hold for every backend.
  14001. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14002. using namespace httplib::tls;
  14003. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14004. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14005. ASSERT_TRUE(svr.is_valid());
  14006. svr.Get("/test", [](const Request &, Response &res) {
  14007. res.set_content("ok", "text/plain");
  14008. });
  14009. thread t([&]() { svr.listen(HOST, PORT); });
  14010. auto se = detail::scope_exit([&] {
  14011. svr.stop();
  14012. t.join();
  14013. });
  14014. svr.wait_until_ready();
  14015. bool verify_callback_called = false;
  14016. bool ip_matched_via_cn = true;
  14017. SSLClient cli(HOST, PORT);
  14018. cli.enable_server_certificate_verification(true);
  14019. cli.set_ca_cert_path(CA_CERT_FILE);
  14020. cli.set_connection_timeout(5);
  14021. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14022. verify_callback_called = true;
  14023. if (!ctx.cert) return false;
  14024. // The IP appears only in the CN, so it must NOT be accepted.
  14025. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14026. return true; // Accept for the purpose of this test
  14027. });
  14028. cli.Get("/test");
  14029. ASSERT_TRUE(verify_callback_called)
  14030. << "Verify callback should have been called";
  14031. EXPECT_FALSE(ip_matched_via_cn)
  14032. << "An IP host must not be authenticated via the certificate CN";
  14033. }
  14034. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14035. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14036. using namespace httplib::tls;
  14037. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14038. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14039. ASSERT_TRUE(svr.is_valid());
  14040. svr.Get("/test", [](const Request &, Response &res) {
  14041. res.set_content("ok", "text/plain");
  14042. });
  14043. thread t([&]() { svr.listen(HOST, PORT); });
  14044. auto se = detail::scope_exit([&] {
  14045. svr.stop();
  14046. t.join();
  14047. });
  14048. svr.wait_until_ready();
  14049. bool verify_callback_called = false;
  14050. bool san_matched = false;
  14051. bool wrong_ipv6_matched = true;
  14052. bool cn_ipv6_matched = true;
  14053. SSLClient cli(HOST, PORT);
  14054. cli.enable_server_certificate_verification(true);
  14055. cli.set_ca_cert_path(CA_CERT_FILE);
  14056. cli.set_connection_timeout(5);
  14057. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14058. verify_callback_called = true;
  14059. if (!ctx.cert) return false;
  14060. // Matches the IPv6 iPAddress SAN.
  14061. san_matched = ctx.check_hostname("2001:db8::1");
  14062. // A different IPv6 address must not match.
  14063. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14064. // "::1" lives only in the CN, so it must not be accepted.
  14065. cn_ipv6_matched = ctx.check_hostname("::1");
  14066. return true; // Accept for the purpose of this test
  14067. });
  14068. cli.Get("/test");
  14069. ASSERT_TRUE(verify_callback_called)
  14070. << "Verify callback should have been called";
  14071. EXPECT_TRUE(san_matched)
  14072. << "verify_hostname should match an IPv6 iPAddress SAN";
  14073. EXPECT_FALSE(wrong_ipv6_matched)
  14074. << "verify_hostname should not match a non-matching IPv6 address";
  14075. EXPECT_FALSE(cn_ipv6_matched)
  14076. << "An IPv6 host must not be authenticated via the certificate CN";
  14077. }
  14078. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14079. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14080. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14081. using namespace httplib::tls;
  14082. // SANs: DNS:a.zz, IP:42.46.122.122
  14083. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14084. ASSERT_TRUE(svr.is_valid());
  14085. svr.Get("/test", [](const Request &, Response &res) {
  14086. res.set_content("ok", "text/plain");
  14087. });
  14088. auto port = svr.bind_to_any_port(HOST);
  14089. thread t([&]() { svr.listen_after_bind(); });
  14090. auto se = detail::scope_exit([&] {
  14091. svr.stop();
  14092. t.join();
  14093. });
  14094. svr.wait_until_ready();
  14095. bool verify_callback_called = false;
  14096. bool dns_san_matched = false;
  14097. bool ip_san_matched = false;
  14098. bool ip_matched_via_dns_san = true;
  14099. bool dns_matched_via_ip_san = true;
  14100. bool cn_matched_next_to_dns_san = true;
  14101. SSLClient cli(HOST, port);
  14102. cli.enable_server_certificate_verification(true);
  14103. cli.set_ca_cert_path(CA_CERT_FILE);
  14104. cli.set_connection_timeout(5);
  14105. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14106. verify_callback_called = true;
  14107. if (!ctx.cert) return false;
  14108. dns_san_matched = ctx.check_hostname("a.zz");
  14109. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14110. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14111. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14112. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14113. return true; // Accept for the purpose of this test
  14114. });
  14115. cli.Get("/test");
  14116. ASSERT_TRUE(verify_callback_called)
  14117. << "Verify callback should have been called";
  14118. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14119. EXPECT_TRUE(ip_san_matched)
  14120. << "verify_hostname should match an iPAddress SAN";
  14121. EXPECT_FALSE(ip_matched_via_dns_san)
  14122. << "An IP host must not be authenticated via a dNSName SAN";
  14123. EXPECT_FALSE(dns_matched_via_ip_san)
  14124. << "A DNS host must not be authenticated via an iPAddress SAN";
  14125. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14126. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14127. }
  14128. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14129. // "www.*.example.test" names one host and not every host under example.test.
  14130. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14131. using namespace httplib::tls;
  14132. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14133. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14134. ASSERT_TRUE(svr.is_valid());
  14135. svr.Get("/test", [](const Request &, Response &res) {
  14136. res.set_content("ok", "text/plain");
  14137. });
  14138. auto port = svr.bind_to_any_port(HOST);
  14139. thread t([&]() { svr.listen_after_bind(); });
  14140. auto se = detail::scope_exit([&] {
  14141. svr.stop();
  14142. t.join();
  14143. });
  14144. svr.wait_until_ready();
  14145. bool verify_callback_called = false;
  14146. bool leftmost_wildcard_matched = false;
  14147. bool wildcard_spanned_labels = true;
  14148. bool inner_wildcard_matched = true;
  14149. SSLClient cli(HOST, port);
  14150. cli.enable_server_certificate_verification(true);
  14151. cli.set_ca_cert_path(CA_CERT_FILE);
  14152. cli.set_connection_timeout(5);
  14153. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14154. verify_callback_called = true;
  14155. if (!ctx.cert) return false;
  14156. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14157. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14158. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14159. return true; // Accept for the purpose of this test
  14160. });
  14161. cli.Get("/test");
  14162. ASSERT_TRUE(verify_callback_called)
  14163. << "Verify callback should have been called";
  14164. EXPECT_TRUE(leftmost_wildcard_matched)
  14165. << "A leftmost wildcard should match a single label";
  14166. EXPECT_FALSE(wildcard_spanned_labels)
  14167. << "A wildcard label must not match more than one label";
  14168. EXPECT_FALSE(inner_wildcard_matched)
  14169. << "A wildcard outside the leftmost label must not be honoured";
  14170. }
  14171. // sans() must report each SAN entry under its own type.
  14172. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14173. using namespace httplib::tls;
  14174. // SANs: DNS:a.zz, IP:42.46.122.122
  14175. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14176. ASSERT_TRUE(svr.is_valid());
  14177. svr.Get("/test", [](const Request &, Response &res) {
  14178. res.set_content("ok", "text/plain");
  14179. });
  14180. auto port = svr.bind_to_any_port(HOST);
  14181. thread t([&]() { svr.listen_after_bind(); });
  14182. auto se = detail::scope_exit([&] {
  14183. svr.stop();
  14184. t.join();
  14185. });
  14186. svr.wait_until_ready();
  14187. bool verify_callback_called = false;
  14188. std::vector<SanEntry> sans;
  14189. SSLClient cli(HOST, port);
  14190. cli.enable_server_certificate_verification(true);
  14191. cli.set_ca_cert_path(CA_CERT_FILE);
  14192. cli.set_connection_timeout(5);
  14193. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14194. verify_callback_called = true;
  14195. if (!ctx.cert) return false;
  14196. sans = ctx.sans();
  14197. return true; // Accept for the purpose of this test
  14198. });
  14199. cli.Get("/test");
  14200. ASSERT_TRUE(verify_callback_called)
  14201. << "Verify callback should have been called";
  14202. auto has_san = [&](SanType type, const std::string &value) {
  14203. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14204. return san.type == type && san.value == value;
  14205. });
  14206. };
  14207. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14208. << "sans() should report the dNSName SAN";
  14209. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14210. << "sans() should report the iPAddress SAN";
  14211. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14212. << "sans() must not report the dNSName SAN as an address";
  14213. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14214. << "sans() must not report the iPAddress SAN as a DNS name";
  14215. }
  14216. #endif
  14217. // mbedTLS-specific callback constructor test
  14218. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14219. #ifdef CPPHTTPLIB_SSL_ENABLED
  14220. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14222. ASSERT_TRUE(svr.is_valid());
  14223. // Set up a handler to verify client certificate is present
  14224. bool client_cert_verified = false;
  14225. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14226. // Verify that client certificate was provided
  14227. client_cert_verified = true;
  14228. res.set_content("success", "text/plain");
  14229. });
  14230. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14231. auto se = detail::scope_exit([&] {
  14232. svr.stop();
  14233. t.join();
  14234. ASSERT_FALSE(svr.is_running());
  14235. });
  14236. svr.wait_until_ready();
  14237. // Client with certificate
  14238. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14239. cli.enable_server_certificate_verification(false);
  14240. cli.set_connection_timeout(30);
  14241. auto res = cli.Get("/test");
  14242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14243. ASSERT_EQ(StatusCode::OK_200, res->status);
  14244. ASSERT_TRUE(client_cert_verified);
  14245. EXPECT_EQ("success", res->body);
  14246. }
  14247. #endif
  14248. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14249. // backends
  14250. #ifdef CPPHTTPLIB_SSL_ENABLED
  14251. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14252. using namespace httplib::tls;
  14253. // Test that when client CA cert file is provided,
  14254. // the server properly requests and validates client certificates
  14255. // Create a server with client authentication
  14256. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14257. ASSERT_TRUE(svr.is_valid());
  14258. bool handler_called = false;
  14259. svr.Get("/test", [&](const Request &req, Response &res) {
  14260. handler_called = true;
  14261. // Verify that a client certificate was provided
  14262. auto cert = req.peer_cert();
  14263. ASSERT_TRUE(static_cast<bool>(cert));
  14264. // Get the issuer name
  14265. std::string issuer_str = cert.issuer_name();
  14266. ASSERT_FALSE(issuer_str.empty());
  14267. // The client certificate should be issued by our test CA
  14268. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14269. res.set_content("authenticated", "text/plain");
  14270. });
  14271. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14272. auto se = detail::scope_exit([&] {
  14273. svr.stop();
  14274. t.join();
  14275. ASSERT_FALSE(svr.is_running());
  14276. });
  14277. svr.wait_until_ready();
  14278. // Connect with a client certificate issued by the CA
  14279. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14280. cli.enable_server_certificate_verification(false);
  14281. cli.set_connection_timeout(30);
  14282. auto res = cli.Get("/test");
  14283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14284. ASSERT_EQ(StatusCode::OK_200, res->status);
  14285. ASSERT_TRUE(handler_called);
  14286. EXPECT_EQ("authenticated", res->body);
  14287. }
  14288. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14289. using namespace httplib::tls;
  14290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14291. ASSERT_TRUE(svr.is_valid());
  14292. svr.Get("/test", [](const Request &, Response &res) {
  14293. res.set_content("ok", "text/plain");
  14294. });
  14295. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14296. auto se = detail::scope_exit([&] {
  14297. svr.stop();
  14298. t.join();
  14299. });
  14300. svr.wait_until_ready();
  14301. SSLClient cli(HOST, PORT);
  14302. cli.enable_server_certificate_verification(false);
  14303. cli.set_connection_timeout(30);
  14304. bool cert_checked = false;
  14305. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14306. if (ctx.cert) {
  14307. auto sans = ctx.sans();
  14308. // Test certificate may or may not have SANs - just verify the API
  14309. // works If SANs exist, verify the types are valid
  14310. for (const auto &san : sans) {
  14311. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14312. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14313. san.type == SanType::OTHER);
  14314. EXPECT_FALSE(san.value.empty());
  14315. }
  14316. cert_checked = true;
  14317. }
  14318. return true;
  14319. });
  14320. auto res = cli.Get("/test");
  14321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14322. EXPECT_TRUE(cert_checked);
  14323. }
  14324. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14325. using namespace httplib::tls;
  14326. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14327. ASSERT_TRUE(svr.is_valid());
  14328. svr.Get("/test", [](const Request &, Response &res) {
  14329. res.set_content("ok", "text/plain");
  14330. });
  14331. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14332. auto se = detail::scope_exit([&] {
  14333. svr.stop();
  14334. t.join();
  14335. });
  14336. svr.wait_until_ready();
  14337. SSLClient cli(HOST, PORT);
  14338. cli.enable_server_certificate_verification(false);
  14339. cli.set_connection_timeout(30);
  14340. bool validity_checked = false;
  14341. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14342. if (ctx.cert) {
  14343. time_t not_before = 0, not_after = 0;
  14344. bool result = ctx.validity(not_before, not_after);
  14345. EXPECT_TRUE(result);
  14346. // Verify that not_before < now < not_after for a valid cert
  14347. time_t now = time(nullptr);
  14348. EXPECT_LT(not_before, now);
  14349. EXPECT_GT(not_after, now);
  14350. validity_checked = true;
  14351. }
  14352. return true;
  14353. });
  14354. auto res = cli.Get("/test");
  14355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14356. EXPECT_TRUE(validity_checked);
  14357. }
  14358. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14359. using namespace httplib::tls;
  14360. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14361. ASSERT_TRUE(svr.is_valid());
  14362. svr.Get("/test", [](const Request &, Response &res) {
  14363. res.set_content("ok", "text/plain");
  14364. });
  14365. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14366. auto se = detail::scope_exit([&] {
  14367. svr.stop();
  14368. t.join();
  14369. });
  14370. svr.wait_until_ready();
  14371. SSLClient cli(HOST, PORT);
  14372. cli.enable_server_certificate_verification(false);
  14373. cli.set_connection_timeout(30);
  14374. bool serial_checked = false;
  14375. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14376. if (ctx.cert) {
  14377. std::string serial = ctx.serial();
  14378. EXPECT_FALSE(serial.empty());
  14379. // Serial should be a hex string
  14380. for (char c : serial) {
  14381. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14382. (c >= 'a' && c <= 'f'));
  14383. }
  14384. serial_checked = true;
  14385. }
  14386. return true;
  14387. });
  14388. auto res = cli.Get("/test");
  14389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14390. EXPECT_TRUE(serial_checked);
  14391. }
  14392. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14393. // Test 1: Valid CA file - no error should be recorded
  14394. {
  14395. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14396. CLIENT_CA_CERT_FILE);
  14397. ASSERT_TRUE(svr.is_valid());
  14398. // With valid setup, last_ssl_error should be 0
  14399. EXPECT_EQ(0, svr.ssl_last_error());
  14400. }
  14401. // Test 2: Invalid CA file content
  14402. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14403. {
  14404. // Create a temporary file with completely invalid content
  14405. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14406. {
  14407. std::ofstream ofs(temp_invalid_ca);
  14408. ofs << "This is not a certificate file at all\n";
  14409. ofs << "Just plain text content\n";
  14410. }
  14411. // Create server with invalid CA file
  14412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14413. // Clean up temporary file
  14414. std::remove(temp_invalid_ca);
  14415. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14416. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14417. // Note: SSL_CTX_load_verify_locations typically fails first,
  14418. // but our error handling code path is still exercised
  14419. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14420. }
  14421. }
  14422. TEST(VerifyCallbackTest, VerifyContextFields) {
  14423. using namespace httplib::tls;
  14424. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14425. ASSERT_TRUE(svr.is_valid());
  14426. svr.Get("/test", [](const Request &, Response &res) {
  14427. res.set_content("ok", "text/plain");
  14428. });
  14429. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14430. auto se = detail::scope_exit([&] {
  14431. svr.stop();
  14432. t.join();
  14433. });
  14434. svr.wait_until_ready();
  14435. SSLClient cli(HOST, PORT);
  14436. cli.enable_server_certificate_verification(false);
  14437. cli.set_connection_timeout(30);
  14438. int callback_count = 0;
  14439. bool saw_leaf_cert = false;
  14440. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14441. if (ctx.cert) {
  14442. callback_count++;
  14443. // We should see at least one certificate (the leaf)
  14444. std::string cn = ctx.subject_cn();
  14445. if (!cn.empty()) { saw_leaf_cert = true; }
  14446. // Verify context fields are populated
  14447. EXPECT_NE(ctx.session, nullptr);
  14448. EXPECT_GE(ctx.depth, 0);
  14449. }
  14450. return true;
  14451. });
  14452. auto res = cli.Get("/test");
  14453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14454. EXPECT_GT(callback_count, 0);
  14455. EXPECT_TRUE(saw_leaf_cert);
  14456. }
  14457. // A verifier that accepts runs alongside the built-in verification, and is the
  14458. // only check once that is turned off.
  14459. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14460. using namespace httplib::tls;
  14461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14462. ASSERT_TRUE(svr.is_valid());
  14463. svr.Get("/test", [](const Request &, Response &res) {
  14464. res.set_content("ok", "text/plain");
  14465. });
  14466. auto port = svr.bind_to_any_port(HOST);
  14467. thread t([&]() { svr.listen_after_bind(); });
  14468. auto se = detail::scope_exit([&] {
  14469. svr.stop();
  14470. t.join();
  14471. });
  14472. svr.wait_until_ready();
  14473. SSLClient cli(HOST, port);
  14474. cli.enable_server_hostname_verification(false);
  14475. auto calls = 0;
  14476. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14477. calls++;
  14478. return true;
  14479. });
  14480. // cert.pem is not trusted
  14481. auto res = cli.Get("/test");
  14482. ASSERT_FALSE(res);
  14483. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14484. EXPECT_GT(calls, 0);
  14485. cli.enable_server_certificate_verification(false);
  14486. res = cli.Get("/test");
  14487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14488. EXPECT_EQ("ok", res->body);
  14489. }
  14490. // A verifier belongs to the client that set it, not to the thread that set it.
  14491. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14492. using namespace httplib::tls;
  14493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14494. ASSERT_TRUE(svr.is_valid());
  14495. svr.Get("/test", [](const Request &, Response &res) {
  14496. res.set_content("ok", "text/plain");
  14497. });
  14498. auto port = svr.bind_to_any_port(HOST);
  14499. thread t([&]() { svr.listen_after_bind(); });
  14500. auto se = detail::scope_exit([&] {
  14501. svr.stop();
  14502. t.join();
  14503. });
  14504. svr.wait_until_ready();
  14505. auto rejecting_calls = 0;
  14506. SSLClient rejecting(HOST, port);
  14507. rejecting.enable_server_certificate_verification(false);
  14508. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14509. rejecting_calls++;
  14510. return false;
  14511. });
  14512. auto accepting_calls = 0;
  14513. SSLClient accepting(HOST, port);
  14514. accepting.enable_server_certificate_verification(false);
  14515. // Set on another thread than the requests below.
  14516. thread([&]() {
  14517. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14518. accepting_calls++;
  14519. return true;
  14520. });
  14521. }).join();
  14522. // Requested on another thread than the verifier was set on.
  14523. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14524. EXPECT_GT(rejecting_calls, 0);
  14525. auto res = accepting.Get("/test");
  14526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14527. EXPECT_GT(accepting_calls, 0);
  14528. }
  14529. // A verifier replaced while a handshake runs it lives until it returns.
  14530. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14531. using namespace httplib::tls;
  14532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14533. ASSERT_TRUE(svr.is_valid());
  14534. svr.Get("/test", [](const Request &, Response &res) {
  14535. res.set_content("ok", "text/plain");
  14536. });
  14537. auto port = svr.bind_to_any_port(HOST);
  14538. thread t([&]() { svr.listen_after_bind(); });
  14539. auto se = detail::scope_exit([&] {
  14540. svr.stop();
  14541. t.join();
  14542. });
  14543. svr.wait_until_ready();
  14544. SSLClient cli(HOST, port);
  14545. cli.enable_server_certificate_verification(false);
  14546. std::promise<void> entered;
  14547. std::promise<void> replaced;
  14548. auto replaced_future = replaced.get_future();
  14549. auto first_call = true;
  14550. // Long enough to live on the heap
  14551. std::string expected(64, 'v');
  14552. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14553. if (first_call) {
  14554. first_call = false;
  14555. entered.set_value();
  14556. replaced_future.wait();
  14557. }
  14558. return expected == std::string(64, 'v');
  14559. });
  14560. thread request([&]() {
  14561. auto res = cli.Get("/test");
  14562. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14563. });
  14564. entered.get_future().wait();
  14565. cli.set_server_certificate_verifier(
  14566. [](const VerifyContext &) { return true; });
  14567. replaced.set_value();
  14568. request.join();
  14569. }
  14570. // VerifyContext::session is the same handle the other tls:: functions take.
  14571. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14572. using namespace httplib::tls;
  14573. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14574. ASSERT_TRUE(svr.is_valid());
  14575. svr.Get("/test", [](const Request &, Response &res) {
  14576. res.set_content("ok", "text/plain");
  14577. });
  14578. auto port = svr.bind_to_any_port(HOST);
  14579. thread t([&]() { svr.listen_after_bind(); });
  14580. auto se = detail::scope_exit([&] {
  14581. svr.stop();
  14582. t.join();
  14583. });
  14584. svr.wait_until_ready();
  14585. SSLClient cli(HOST, port);
  14586. cli.enable_server_certificate_verification(false);
  14587. session_t verifier_session = nullptr;
  14588. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14589. verifier_session = ctx.session;
  14590. return true;
  14591. });
  14592. session_t session_verifier_session = nullptr;
  14593. cli.set_session_verifier([&](session_t session) {
  14594. session_verifier_session = session;
  14595. return SSLVerifierResponse::NoDecisionMade;
  14596. });
  14597. auto res = cli.Get("/test");
  14598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14599. EXPECT_NE(nullptr, verifier_session);
  14600. EXPECT_EQ(session_verifier_session, verifier_session);
  14601. }
  14602. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14603. using httplib::tls::TlsError;
  14604. // Test that verify_error_to_string returns empty for success
  14605. std::string success_str = TlsError::verify_error_to_string(0);
  14606. EXPECT_TRUE(success_str.empty());
  14607. // Test that verify_error_to_string returns non-empty for error codes
  14608. // Using a common error code (certificate expired)
  14609. std::string error_str =
  14610. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14611. EXPECT_FALSE(error_str.empty());
  14612. }
  14613. TEST(SessionVerifierTest, CertificateAccepted) {
  14614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14615. ASSERT_TRUE(svr.is_valid());
  14616. svr.Get("/test", [](const Request &, Response &res) {
  14617. res.set_content("ok", "text/plain");
  14618. });
  14619. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14620. auto se = detail::scope_exit([&] {
  14621. svr.stop();
  14622. t.join();
  14623. });
  14624. svr.wait_until_ready();
  14625. SSLClient cli(HOST, PORT);
  14626. cli.enable_server_certificate_verification(false);
  14627. cli.set_connection_timeout(30);
  14628. bool callback_called = false;
  14629. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14630. EXPECT_NE(session, nullptr);
  14631. callback_called = true;
  14632. return SSLVerifierResponse::CertificateAccepted;
  14633. });
  14634. auto res = cli.Get("/test");
  14635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14636. EXPECT_EQ(200, res->status);
  14637. EXPECT_TRUE(callback_called);
  14638. }
  14639. TEST(SessionVerifierTest, CertificateRejected) {
  14640. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14641. ASSERT_TRUE(svr.is_valid());
  14642. svr.Get("/test", [](const Request &, Response &res) {
  14643. res.set_content("ok", "text/plain");
  14644. });
  14645. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14646. auto se = detail::scope_exit([&] {
  14647. svr.stop();
  14648. t.join();
  14649. });
  14650. svr.wait_until_ready();
  14651. SSLClient cli(HOST, PORT);
  14652. cli.enable_server_certificate_verification(false);
  14653. cli.set_connection_timeout(30);
  14654. bool callback_called = false;
  14655. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14656. EXPECT_NE(session, nullptr);
  14657. callback_called = true;
  14658. return SSLVerifierResponse::CertificateRejected;
  14659. });
  14660. auto res = cli.Get("/test");
  14661. EXPECT_FALSE(res);
  14662. EXPECT_TRUE(callback_called);
  14663. }
  14664. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14666. ASSERT_TRUE(svr.is_valid());
  14667. svr.Get("/test", [](const Request &, Response &res) {
  14668. res.set_content("ok", "text/plain");
  14669. });
  14670. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14671. auto se = detail::scope_exit([&] {
  14672. svr.stop();
  14673. t.join();
  14674. });
  14675. svr.wait_until_ready();
  14676. // NoDecisionMade with verification disabled should succeed (no default check)
  14677. SSLClient cli(HOST, PORT);
  14678. cli.enable_server_certificate_verification(false);
  14679. cli.set_connection_timeout(30);
  14680. bool callback_called = false;
  14681. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14682. EXPECT_NE(session, nullptr);
  14683. callback_called = true;
  14684. return SSLVerifierResponse::NoDecisionMade;
  14685. });
  14686. auto res = cli.Get("/test");
  14687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14688. EXPECT_EQ(200, res->status);
  14689. EXPECT_TRUE(callback_called);
  14690. }
  14691. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14692. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14693. ASSERT_TRUE(svr.is_valid());
  14694. svr.Get("/test", [](const Request &, Response &res) {
  14695. res.set_content("ok", "text/plain");
  14696. });
  14697. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14698. auto se = detail::scope_exit([&] {
  14699. svr.stop();
  14700. t.join();
  14701. });
  14702. svr.wait_until_ready();
  14703. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14704. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14705. // so we only check that the request fails, not whether the callback was
  14706. // called.
  14707. SSLClient cli(HOST, PORT);
  14708. cli.enable_server_certificate_verification(true);
  14709. cli.set_connection_timeout(30);
  14710. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14711. EXPECT_NE(session, nullptr);
  14712. return SSLVerifierResponse::NoDecisionMade;
  14713. });
  14714. auto res = cli.Get("/test");
  14715. EXPECT_FALSE(res);
  14716. }
  14717. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14718. // Test SSL server using PemMemory constructor with client CA certificates
  14719. // Read PEM files
  14720. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14721. read_file(SERVER_CERT_FILE, server_cert_pem);
  14722. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14723. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14724. // Create SSLServer with PemMemory constructor including client CA
  14725. SSLServer::PemMemory server_pem = {
  14726. server_cert_pem.c_str(),
  14727. server_cert_pem.size(),
  14728. server_key_pem.c_str(),
  14729. server_key_pem.size(),
  14730. client_ca_pem.c_str(),
  14731. client_ca_pem.size(),
  14732. nullptr // no password for server key
  14733. };
  14734. SSLServer svr(server_pem);
  14735. ASSERT_TRUE(svr.is_valid());
  14736. // No SSL error should be recorded for valid setup
  14737. EXPECT_EQ(0, svr.ssl_last_error());
  14738. // Set up server endpoints
  14739. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14740. res.set_content("ok", "text/plain");
  14741. });
  14742. // Start server in a thread
  14743. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14744. svr.wait_until_ready();
  14745. // Connect with client certificate (using constructor with paths)
  14746. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14747. cli.enable_server_certificate_verification(false);
  14748. auto res = cli.Get("/test-pem-ca");
  14749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14750. EXPECT_EQ(200, res->status);
  14751. EXPECT_EQ("ok", res->body);
  14752. svr.stop();
  14753. server_thread.join();
  14754. }
  14755. #endif
  14756. #ifdef _WIN32
  14757. TEST(CleanupTest, WSACleanup) {
  14758. int ret = WSACleanup();
  14759. ASSERT_EQ(0, ret);
  14760. }
  14761. #endif
  14762. #ifndef CPPHTTPLIB_SSL_ENABLED
  14763. TEST(NoSSLSupport, SimpleInterface) {
  14764. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14765. }
  14766. #endif
  14767. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14768. TEST(InvalidScheme, SimpleInterface) {
  14769. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14770. }
  14771. #endif
  14772. TEST(NoScheme, SimpleInterface) {
  14773. Client cli("yahoo.com:80");
  14774. ASSERT_TRUE(cli.is_valid());
  14775. }
  14776. TEST(SendAPI, SimpleInterface_Online) {
  14777. Client cli("http://yahoo.com");
  14778. Request req;
  14779. req.method = "GET";
  14780. req.path = "/";
  14781. auto res = cli.send(req);
  14782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14783. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14784. }
  14785. TEST(SendAPI, WithParamsInRequest) {
  14786. Server svr;
  14787. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14788. EXPECT_TRUE(req.has_param("test"));
  14789. EXPECT_EQ("test_value", req.get_param_value("test"));
  14790. });
  14791. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14792. auto se = detail::scope_exit([&] {
  14793. svr.stop();
  14794. t.join();
  14795. ASSERT_FALSE(svr.is_running());
  14796. });
  14797. svr.wait_until_ready();
  14798. Client cli(HOST, PORT);
  14799. {
  14800. Request req;
  14801. req.method = "GET";
  14802. req.path = "/";
  14803. req.params.emplace("test", "test_value");
  14804. auto res = cli.send(req);
  14805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14806. }
  14807. {
  14808. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14810. }
  14811. }
  14812. TEST(ClientImplMethods, GetSocketTest) {
  14813. httplib::Server svr;
  14814. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14815. res.status = StatusCode::OK_200;
  14816. });
  14817. auto port = svr.bind_to_any_port("127.0.0.1");
  14818. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14819. auto se = detail::scope_exit([&] {
  14820. svr.stop();
  14821. thread.join();
  14822. ASSERT_FALSE(svr.is_running());
  14823. });
  14824. svr.wait_until_ready();
  14825. {
  14826. httplib::Client cli("127.0.0.1", port);
  14827. cli.set_keep_alive(true);
  14828. // Use the behavior of cpp-httplib of opening the connection
  14829. // only when the first request happens. If that changes,
  14830. // this test would be obsolete.
  14831. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14832. // This also implicitly tests the server. But other tests would fail much
  14833. // earlier than this one to be considered.
  14834. auto res = cli.Get("/");
  14835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14836. EXPECT_EQ(StatusCode::OK_200, res->status);
  14837. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14838. }
  14839. }
  14840. #ifdef CPPHTTPLIB_SSL_ENABLED
  14841. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14842. Client cli("http://yahoo.com");
  14843. auto res = cli.Get("/");
  14844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14845. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14846. cli.set_follow_location(true);
  14847. res = cli.Get("/");
  14848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14849. EXPECT_EQ(StatusCode::OK_200, res->status);
  14850. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14851. }
  14852. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14853. Client cli("https://yahoo.com");
  14854. auto res = cli.Get("/");
  14855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14856. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14857. cli.set_follow_location(true);
  14858. res = cli.Get("/");
  14859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14860. EXPECT_EQ(StatusCode::OK_200, res->status);
  14861. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14862. }
  14863. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14864. Client cli("https://yahoo.com");
  14865. auto res = cli.Get("/");
  14866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14867. ASSERT_FALSE(!res);
  14868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14869. ASSERT_FALSE(res == nullptr);
  14870. ASSERT_TRUE(res != nullptr);
  14871. EXPECT_EQ(Error::Success, res.error());
  14872. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14873. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14874. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14875. cli.set_follow_location(true);
  14876. res = cli.Get("/");
  14877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14878. EXPECT_EQ(Error::Success, res.error());
  14879. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14880. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14881. EXPECT_EQ(StatusCode::OK_200, res->status);
  14882. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14883. }
  14884. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14885. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14886. Client cli("https://cdnjs.cloudflare.com");
  14887. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14888. Headers{{"Accept-Encoding", "br"}});
  14889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14890. EXPECT_EQ(StatusCode::OK_200, res->status);
  14891. EXPECT_EQ(287630U, res->body.size());
  14892. EXPECT_EQ("application/javascript; charset=utf-8",
  14893. res->get_header_value("Content-Type"));
  14894. }
  14895. #endif
  14896. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14897. #undef REDIR_HOST // Silence compiler warning
  14898. #define REDIR_HOST "https://httpbingo.org"
  14899. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14900. Client cli(REDIR_HOST);
  14901. cli.set_follow_location(true);
  14902. auto res =
  14903. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14905. EXPECT_EQ(StatusCode::OK_200, res->status);
  14906. }
  14907. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14908. Client cli(REDIR_HOST);
  14909. cli.set_follow_location(true);
  14910. Params params;
  14911. params.emplace("url", "http://example.com");
  14912. params.emplace("status_code", "302");
  14913. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14915. EXPECT_EQ(StatusCode::OK_200, res->status);
  14916. }
  14917. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14918. Client cli(REDIR_HOST);
  14919. cli.set_follow_location(true);
  14920. Params params;
  14921. params.emplace("url", "http://example.com");
  14922. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14924. EXPECT_EQ(StatusCode::OK_200, res->status);
  14925. }
  14926. TEST(HttpToHttpsRedirectTest, CertFile) {
  14927. auto ssl_port = PORT + 1;
  14928. Server svr;
  14929. ASSERT_TRUE(svr.is_valid());
  14930. svr.Get("/index", [&](const Request &, Response &res) {
  14931. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14932. "/index");
  14933. svr.stop();
  14934. });
  14935. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14936. ASSERT_TRUE(ssl_svr.is_valid());
  14937. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14938. res.set_content("test", "text/plain");
  14939. ssl_svr.stop();
  14940. });
  14941. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14942. thread t2 =
  14943. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14944. auto se = detail::scope_exit([&] {
  14945. t2.join();
  14946. t.join();
  14947. ASSERT_FALSE(svr.is_running());
  14948. });
  14949. svr.wait_until_ready();
  14950. ssl_svr.wait_until_ready();
  14951. Client cli("127.0.0.1", PORT);
  14952. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14953. cli.enable_server_certificate_verification(true);
  14954. cli.set_follow_location(true);
  14955. cli.set_connection_timeout(30);
  14956. auto res = cli.Get("/index");
  14957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14958. ASSERT_EQ(StatusCode::OK_200, res->status);
  14959. }
  14960. TEST(SSLClientRedirectTest, CertFile) {
  14961. auto ssl_port = PORT + 1;
  14962. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14963. ASSERT_TRUE(ssl_svr1.is_valid());
  14964. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14965. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14966. "/index");
  14967. ssl_svr1.stop();
  14968. });
  14969. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14970. ASSERT_TRUE(ssl_svr2.is_valid());
  14971. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14972. res.set_content("test", "text/plain");
  14973. ssl_svr2.stop();
  14974. });
  14975. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14976. thread t2 =
  14977. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14978. auto se = detail::scope_exit([&] {
  14979. t2.join();
  14980. t.join();
  14981. ASSERT_FALSE(ssl_svr1.is_running());
  14982. });
  14983. ssl_svr1.wait_until_ready();
  14984. ssl_svr2.wait_until_ready();
  14985. SSLClient cli("127.0.0.1", PORT);
  14986. std::string cert;
  14987. read_file(SERVER_CERT2_FILE, cert);
  14988. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14989. cli.enable_server_certificate_verification(true);
  14990. cli.set_follow_location(true);
  14991. cli.set_connection_timeout(30);
  14992. auto res = cli.Get("/index");
  14993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14994. ASSERT_EQ(StatusCode::OK_200, res->status);
  14995. }
  14996. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14997. // another port, so the client follows it with a new client.
  14998. static Result GetThroughTlsRedirectToDifferentPort(
  14999. const std::function<void(SSLClient &)> &setup,
  15000. const char *target_cert = SERVER_CERT2_FILE,
  15001. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15002. auto ssl_port = PORT + 1;
  15003. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15004. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15005. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15006. "/index");
  15007. });
  15008. SSLServer ssl_svr2(target_cert, target_key);
  15009. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15010. res.set_content("test", "text/plain");
  15011. });
  15012. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15013. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15014. auto se = detail::scope_exit([&] {
  15015. ssl_svr2.stop();
  15016. ssl_svr1.stop();
  15017. t2.join();
  15018. t.join();
  15019. });
  15020. ssl_svr1.wait_until_ready();
  15021. ssl_svr2.wait_until_ready();
  15022. SSLClient cli("127.0.0.1", PORT);
  15023. cli.set_follow_location(true);
  15024. cli.set_connection_timeout(30);
  15025. setup(cli);
  15026. return cli.Get("/index");
  15027. }
  15028. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15029. auto calls = 0;
  15030. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15031. cli.enable_server_certificate_verification(false);
  15032. // Accept the first server only.
  15033. cli.set_session_verifier([&](tls::session_t) {
  15034. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15035. : SSLVerifierResponse::CertificateRejected;
  15036. });
  15037. });
  15038. ASSERT_FALSE(res);
  15039. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15040. EXPECT_EQ(2, calls);
  15041. }
  15042. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15043. std::string pinned;
  15044. auto res = GetThroughTlsRedirectToDifferentPort(
  15045. [&](SSLClient &cli) {
  15046. cli.enable_server_certificate_verification(false);
  15047. // Pin the first certificate seen.
  15048. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15049. if (pinned.empty()) { pinned = ctx.serial(); }
  15050. return ctx.serial() == pinned;
  15051. });
  15052. },
  15053. // A certificate other than the first server's.
  15054. SERVER_CERT_FILE);
  15055. EXPECT_FALSE(res);
  15056. EXPECT_FALSE(pinned.empty());
  15057. }
  15058. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15059. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15060. std::string cert;
  15061. read_file(SERVER_CERT2_FILE, cert);
  15062. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15063. });
  15064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15065. EXPECT_EQ(StatusCode::OK_200, res->status);
  15066. }
  15067. // The target's certificate is signed by the root CA, which the first server's
  15068. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15069. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15070. auto res = GetThroughTlsRedirectToDifferentPort(
  15071. [](SSLClient &cli) {
  15072. std::string root_ca, cert;
  15073. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15074. read_file(SERVER_CERT2_FILE, cert);
  15075. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15076. cli.load_ca_cert_store(cert.data(), cert.size());
  15077. cli.enable_server_hostname_verification(false);
  15078. },
  15079. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15081. EXPECT_EQ(StatusCode::OK_200, res->status);
  15082. }
  15083. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15084. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15085. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15086. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15087. auto res = GetThroughTlsRedirectToDifferentPort(
  15088. [](SSLClient &cli) {
  15089. std::string root_ca, cert;
  15090. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15091. read_file(SERVER_CERT2_FILE, cert);
  15092. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15093. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15094. cli.enable_server_hostname_verification(false);
  15095. },
  15096. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15097. ASSERT_FALSE(res);
  15098. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15099. }
  15100. #endif
  15101. #endif
  15102. #ifdef CPPHTTPLIB_SSL_ENABLED
  15103. // Test that set_ca_cert_store() skips system certs (consistent with
  15104. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15105. // should be trusted - system certs should NOT be loaded.
  15106. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15107. // Load a specific cert that is NOT a system CA cert
  15108. std::string cert;
  15109. read_file(SERVER_CERT2_FILE, cert);
  15110. SSLClient cli("google.com");
  15111. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15112. cli.enable_server_certificate_verification(true);
  15113. // This should FAIL because:
  15114. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15115. // 2. System certs should NOT be loaded when custom store is set
  15116. // If system certs WERE loaded, this would succeed
  15117. auto res = cli.Get("/");
  15118. ASSERT_FALSE(res);
  15119. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15120. }
  15121. // Same as above, but through the native store handle path. Regression test:
  15122. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15123. // merged system certs into the user-provided store.
  15124. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15125. std::string cert;
  15126. read_file(SERVER_CERT2_FILE, cert);
  15127. SSLClient cli("google.com");
  15128. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15129. cli.enable_server_certificate_verification(true);
  15130. auto res = cli.Get("/");
  15131. ASSERT_FALSE(res);
  15132. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15133. }
  15134. // A custom store set via the native handle must still verify a server whose
  15135. // cert it does contain.
  15136. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15137. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15138. ASSERT_TRUE(svr.is_valid());
  15139. svr.Get("/test", [&](const Request &, Response &res) {
  15140. res.set_content("test", "text/plain");
  15141. });
  15142. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15143. auto se = detail::scope_exit([&] {
  15144. svr.stop();
  15145. t.join();
  15146. ASSERT_FALSE(svr.is_running());
  15147. });
  15148. svr.wait_until_ready();
  15149. SSLClient cli("127.0.0.1", PORT);
  15150. std::string cert;
  15151. read_file(SERVER_CERT2_FILE, cert);
  15152. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15153. cli.enable_server_certificate_verification(true);
  15154. cli.set_connection_timeout(30);
  15155. auto res = cli.Get("/test");
  15156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15157. ASSERT_EQ(StatusCode::OK_200, res->status);
  15158. }
  15159. // CA certs loaded through the universal Client must be transferred to the
  15160. // client created internally for following an HTTPS redirect. Regression test:
  15161. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15162. // the CA data for redirect transfer.
  15163. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15164. auto ssl_port = PORT + 1;
  15165. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15166. ASSERT_TRUE(ssl_svr1.is_valid());
  15167. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15168. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15169. "/index");
  15170. });
  15171. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15172. ASSERT_TRUE(ssl_svr2.is_valid());
  15173. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15174. res.set_content("test", "text/plain");
  15175. });
  15176. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15177. thread t2 =
  15178. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15179. auto se = detail::scope_exit([&] {
  15180. ssl_svr2.stop();
  15181. ssl_svr1.stop();
  15182. t2.join();
  15183. t.join();
  15184. ASSERT_FALSE(ssl_svr1.is_running());
  15185. });
  15186. ssl_svr1.wait_until_ready();
  15187. ssl_svr2.wait_until_ready();
  15188. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15189. std::string cert;
  15190. read_file(SERVER_CERT2_FILE, cert);
  15191. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15192. cli.enable_server_certificate_verification(true);
  15193. cli.set_follow_location(true);
  15194. cli.set_connection_timeout(30);
  15195. auto res = cli.Get("/index");
  15196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15197. ASSERT_EQ(StatusCode::OK_200, res->status);
  15198. }
  15199. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15200. // so a host signed by a system CA verifies even though a custom CA is set
  15201. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15202. std::string cert;
  15203. read_file(SERVER_CERT2_FILE, cert);
  15204. SSLClient cli("google.com");
  15205. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15206. cli.enable_system_ca(true);
  15207. cli.enable_server_certificate_verification(true);
  15208. auto res = cli.Get("/");
  15209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15210. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15211. }
  15212. // The custom CA remains effective when combined with the system CA
  15213. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15214. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15215. ASSERT_TRUE(svr.is_valid());
  15216. svr.Get("/test", [&](const Request &, Response &res) {
  15217. res.set_content("test", "text/plain");
  15218. });
  15219. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15220. auto se = detail::scope_exit([&] {
  15221. svr.stop();
  15222. t.join();
  15223. ASSERT_FALSE(svr.is_running());
  15224. });
  15225. svr.wait_until_ready();
  15226. SSLClient cli("127.0.0.1", PORT);
  15227. std::string cert;
  15228. read_file(SERVER_CERT2_FILE, cert);
  15229. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15230. cli.enable_system_ca(true);
  15231. cli.enable_server_certificate_verification(true);
  15232. cli.set_connection_timeout(30);
  15233. auto res = cli.Get("/test");
  15234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15235. ASSERT_EQ(StatusCode::OK_200, res->status);
  15236. }
  15237. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15238. // skip chain verification entirely (only the certificate identity was
  15239. // checked), so a server presenting an untrusted certificate with a matching
  15240. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15241. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15242. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15243. ASSERT_TRUE(svr.is_valid());
  15244. svr.Get("/test", [&](const Request &, Response &res) {
  15245. res.set_content("test", "text/plain");
  15246. });
  15247. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15248. auto se = detail::scope_exit([&] {
  15249. svr.stop();
  15250. t.join();
  15251. ASSERT_FALSE(svr.is_running());
  15252. });
  15253. svr.wait_until_ready();
  15254. SSLClient cli("127.0.0.1", PORT);
  15255. std::string cert;
  15256. // A trusted CA that did not sign the server certificate. The server cert
  15257. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15258. // this connection.
  15259. read_file(CLIENT_CA_CERT_FILE, cert);
  15260. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15261. cli.enable_server_certificate_verification(true);
  15262. cli.set_connection_timeout(30);
  15263. auto res = cli.Get("/test");
  15264. ASSERT_FALSE(res);
  15265. }
  15266. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15267. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15268. // CA that failed to come through fails verification instead of trusting them.
  15269. // (wolfSSL does not list the system CAs it loaded.)
  15270. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15271. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15272. ASSERT_TRUE(svr.is_valid());
  15273. auto port = svr.bind_to_any_port("127.0.0.1");
  15274. ASSERT_LT(0, port);
  15275. thread t = thread([&] { svr.listen_after_bind(); });
  15276. auto se = detail::scope_exit([&] {
  15277. svr.stop();
  15278. t.join();
  15279. ASSERT_FALSE(svr.is_running());
  15280. });
  15281. svr.wait_until_ready();
  15282. // The CAs a client trusts once its first request has loaded them
  15283. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15284. Client cli("https://127.0.0.1:" + std::to_string(port));
  15285. setup(cli);
  15286. cli.Get("/");
  15287. return tls::get_ca_names(cli.tls_context()).size();
  15288. };
  15289. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15290. EXPECT_EQ(0u,
  15291. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15292. }
  15293. #endif
  15294. // A TLS setting changed between requests applies to the next one, not just to
  15295. // the next connection
  15296. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15297. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15298. ASSERT_TRUE(svr.is_valid());
  15299. svr.Get("/", [](const Request &req, Response &res) {
  15300. res.set_content(std::to_string(req.remote_port), "text/plain");
  15301. });
  15302. auto port = svr.bind_to_any_port("127.0.0.1");
  15303. ASSERT_LT(0, port);
  15304. thread t = thread([&] { svr.listen_after_bind(); });
  15305. auto se = detail::scope_exit([&] {
  15306. svr.stop();
  15307. t.join();
  15308. ASSERT_FALSE(svr.is_running());
  15309. });
  15310. svr.wait_until_ready();
  15311. SSLClient cli("127.0.0.1", port);
  15312. cli.set_keep_alive(true);
  15313. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15314. cli.enable_server_certificate_verification(false);
  15315. // The port the request went out from, so a new one means a new connection
  15316. auto client_port = [&] {
  15317. auto res = cli.Get("/");
  15318. return res ? res->body : std::string();
  15319. };
  15320. auto last = client_port();
  15321. ASSERT_FALSE(last.empty());
  15322. // Setting a value it already has keeps the connection
  15323. cli.enable_server_certificate_verification(false);
  15324. cli.enable_server_hostname_verification(true);
  15325. EXPECT_EQ(last, client_port());
  15326. cli.enable_server_certificate_verification(true);
  15327. auto res = cli.Get("/");
  15328. EXPECT_FALSE(res);
  15329. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15330. std::string ca;
  15331. read_file(SERVER_CERT2_FILE, ca);
  15332. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15333. last = client_port();
  15334. ASSERT_FALSE(last.empty());
  15335. std::vector<std::function<void()>> setters = {
  15336. [&] { cli.enable_server_hostname_verification(false); },
  15337. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15338. [&] {
  15339. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15340. },
  15341. [&] {
  15342. cli.set_server_certificate_verifier(
  15343. [](const tls::VerifyContext &) { return true; });
  15344. },
  15345. [&] {
  15346. cli.set_session_verifier(
  15347. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15348. },
  15349. };
  15350. for (const auto &setter : setters) {
  15351. setter();
  15352. auto next = client_port();
  15353. ASSERT_FALSE(next.empty());
  15354. EXPECT_NE(last, next);
  15355. last = next;
  15356. }
  15357. cli.set_session_verifier(
  15358. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15359. auto handle = cli.open_stream("GET", "/");
  15360. EXPECT_FALSE(handle.is_valid());
  15361. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15362. }
  15363. // A PEM given to create_ca_store() needs no NUL after it
  15364. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15365. std::string pem;
  15366. read_file(SERVER_CERT2_FILE, pem);
  15367. auto buf = pem + "X";
  15368. auto store = tls::create_ca_store(buf.data(), pem.size());
  15369. EXPECT_TRUE(store != nullptr);
  15370. SSLClient cli("localhost");
  15371. cli.set_ca_cert_store(store);
  15372. }
  15373. // enable_system_ca(false) prevents system CA loading entirely
  15374. TEST(SSLClientTest, DisableSystemCa_Online) {
  15375. SSLClient cli("google.com");
  15376. cli.enable_system_ca(false);
  15377. cli.enable_server_certificate_verification(true);
  15378. auto res = cli.Get("/");
  15379. ASSERT_FALSE(res);
  15380. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15381. // itself when the CA chain is empty
  15382. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15383. res.error() == Error::SSLConnection);
  15384. }
  15385. // The universal Client forwards enable_system_ca()
  15386. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15387. std::string cert;
  15388. read_file(SERVER_CERT2_FILE, cert);
  15389. Client cli("https://google.com");
  15390. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15391. cli.enable_system_ca(true);
  15392. cli.enable_server_certificate_verification(true);
  15393. auto res = cli.Get("/");
  15394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15395. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15396. }
  15397. // The system CA policy must carry over to the client created internally for
  15398. // following a cross-host HTTPS redirect
  15399. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15400. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15401. ASSERT_TRUE(svr.is_valid());
  15402. svr.Get("/index", [&](const Request &, Response &res) {
  15403. res.set_redirect("https://www.google.com/");
  15404. });
  15405. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15406. auto se = detail::scope_exit([&] {
  15407. svr.stop();
  15408. t.join();
  15409. ASSERT_FALSE(svr.is_running());
  15410. });
  15411. svr.wait_until_ready();
  15412. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15413. std::string cert;
  15414. read_file(SERVER_CERT2_FILE, cert);
  15415. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15416. cli.enable_system_ca(true);
  15417. cli.enable_server_certificate_verification(true);
  15418. cli.set_follow_location(true);
  15419. cli.set_connection_timeout(30);
  15420. // Receiving any response proves the redirect client completed the TLS
  15421. // handshake with a system-CA-signed host
  15422. auto res = cli.Get("/index");
  15423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15424. }
  15425. TEST(MultipartFormDataTest, LargeData) {
  15426. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15427. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15428. const ContentReader &content_reader) {
  15429. if (req.is_multipart_form_data()) {
  15430. std::vector<FormData> items;
  15431. content_reader(
  15432. [&](const FormData &file) {
  15433. items.push_back(file);
  15434. return true;
  15435. },
  15436. [&](const char *data, size_t data_length) {
  15437. items.back().content.append(data, data_length);
  15438. return true;
  15439. });
  15440. EXPECT_TRUE(std::string(items[0].name) == "document");
  15441. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15442. EXPECT_TRUE(items[0].filename == "2MB_data");
  15443. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15444. EXPECT_TRUE(items[1].name == "hello");
  15445. EXPECT_TRUE(items[1].content == "world");
  15446. EXPECT_TRUE(items[1].filename == "");
  15447. EXPECT_TRUE(items[1].content_type == "");
  15448. } else {
  15449. std::string body;
  15450. content_reader([&](const char *data, size_t data_length) {
  15451. body.append(data, data_length);
  15452. return true;
  15453. });
  15454. }
  15455. });
  15456. auto port = svr.bind_to_any_port(HOST);
  15457. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15458. auto se = detail::scope_exit([&] {
  15459. svr.stop();
  15460. t.join();
  15461. ASSERT_FALSE(svr.is_running());
  15462. });
  15463. svr.wait_until_ready();
  15464. {
  15465. std::string data(1024 * 1024 * 2, '.');
  15466. std::stringstream buffer;
  15467. buffer << data;
  15468. SSLClient cli(HOST, port);
  15469. cli.enable_server_certificate_verification(false);
  15470. UploadFormDataItems items{
  15471. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15472. {"hello", "world", "", ""},
  15473. };
  15474. auto res = cli.Post("/post", items);
  15475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15476. ASSERT_EQ(StatusCode::OK_200, res->status);
  15477. }
  15478. }
  15479. TEST(MultipartFormDataTest, DataProviderItems) {
  15480. std::random_device seed_gen;
  15481. std::mt19937 random(seed_gen());
  15482. std::string rand1;
  15483. rand1.resize(1000);
  15484. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15485. std::string rand2;
  15486. rand2.resize(3000);
  15487. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15489. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15490. const ContentReader &content_reader) {
  15491. ASSERT_FALSE(req.is_multipart_form_data());
  15492. std::string body;
  15493. content_reader([&](const char *data, size_t data_length) {
  15494. body.append(data, data_length);
  15495. return true;
  15496. });
  15497. EXPECT_EQ(body, "");
  15498. });
  15499. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15500. const ContentReader &content_reader) {
  15501. ASSERT_TRUE(req.is_multipart_form_data());
  15502. std::vector<FormData> items;
  15503. content_reader(
  15504. [&](const FormData &file) {
  15505. items.push_back(file);
  15506. return true;
  15507. },
  15508. [&](const char *data, size_t data_length) {
  15509. items.back().content.append(data, data_length);
  15510. return true;
  15511. });
  15512. ASSERT_TRUE(items.size() == 2);
  15513. EXPECT_EQ(std::string(items[0].name), "name1");
  15514. EXPECT_EQ(items[0].content, "Testing123");
  15515. EXPECT_EQ(items[0].filename, "filename1");
  15516. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15517. EXPECT_EQ(items[1].name, "name2");
  15518. EXPECT_EQ(items[1].content, "Testing456");
  15519. EXPECT_EQ(items[1].filename, "");
  15520. EXPECT_EQ(items[1].content_type, "");
  15521. });
  15522. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15523. const ContentReader &content_reader) {
  15524. ASSERT_TRUE(req.is_multipart_form_data());
  15525. std::vector<FormData> items;
  15526. content_reader(
  15527. [&](const FormData &file) {
  15528. items.push_back(file);
  15529. return true;
  15530. },
  15531. [&](const char *data, size_t data_length) {
  15532. items.back().content.append(data, data_length);
  15533. return true;
  15534. });
  15535. ASSERT_TRUE(items.size() == 2);
  15536. EXPECT_EQ(items[0].name, "name3");
  15537. EXPECT_EQ(items[0].content, rand1);
  15538. EXPECT_EQ(items[0].filename, "filename3");
  15539. EXPECT_EQ(items[0].content_type, "");
  15540. EXPECT_EQ(items[1].name, "name4");
  15541. EXPECT_EQ(items[1].content, rand2);
  15542. EXPECT_EQ(items[1].filename, "filename4");
  15543. EXPECT_EQ(items[1].content_type, "");
  15544. });
  15545. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15546. const ContentReader &content_reader) {
  15547. ASSERT_TRUE(req.is_multipart_form_data());
  15548. std::vector<FormData> items;
  15549. content_reader(
  15550. [&](const FormData &file) {
  15551. items.push_back(file);
  15552. return true;
  15553. },
  15554. [&](const char *data, size_t data_length) {
  15555. items.back().content.append(data, data_length);
  15556. return true;
  15557. });
  15558. ASSERT_TRUE(items.size() == 4);
  15559. EXPECT_EQ(std::string(items[0].name), "name1");
  15560. EXPECT_EQ(items[0].content, "Testing123");
  15561. EXPECT_EQ(items[0].filename, "filename1");
  15562. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15563. EXPECT_EQ(items[1].name, "name2");
  15564. EXPECT_EQ(items[1].content, "Testing456");
  15565. EXPECT_EQ(items[1].filename, "");
  15566. EXPECT_EQ(items[1].content_type, "");
  15567. EXPECT_EQ(items[2].name, "name3");
  15568. EXPECT_EQ(items[2].content, rand1);
  15569. EXPECT_EQ(items[2].filename, "filename3");
  15570. EXPECT_EQ(items[2].content_type, "");
  15571. EXPECT_EQ(items[3].name, "name4");
  15572. EXPECT_EQ(items[3].content, rand2);
  15573. EXPECT_EQ(items[3].filename, "filename4");
  15574. EXPECT_EQ(items[3].content_type, "");
  15575. });
  15576. auto port = svr.bind_to_any_port("localhost");
  15577. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15578. auto se = detail::scope_exit([&] {
  15579. svr.stop();
  15580. t.join();
  15581. ASSERT_FALSE(svr.is_running());
  15582. });
  15583. svr.wait_until_ready();
  15584. {
  15585. SSLClient cli("localhost", port);
  15586. cli.enable_server_certificate_verification(false);
  15587. UploadFormDataItems items{
  15588. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15589. {"name2", "Testing456", "", ""}, // not a file
  15590. };
  15591. {
  15592. auto res = cli.Post("/post-none", {}, {}, {});
  15593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15594. ASSERT_EQ(StatusCode::OK_200, res->status);
  15595. }
  15596. FormDataProviderItems providers;
  15597. {
  15598. auto res =
  15599. cli.Post("/post-items", {}, items, providers); // empty providers
  15600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15601. ASSERT_EQ(StatusCode::OK_200, res->status);
  15602. }
  15603. providers.push_back({"name3",
  15604. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15605. // test the offset is given correctly at each step
  15606. if (!offset)
  15607. sink.os.write(rand1.data(), 30);
  15608. else if (offset == 30)
  15609. sink.os.write(rand1.data() + 30, 300);
  15610. else if (offset == 330)
  15611. sink.os.write(rand1.data() + 330, 670);
  15612. else if (offset == rand1.size())
  15613. sink.done();
  15614. return true;
  15615. },
  15616. "filename3",
  15617. {}});
  15618. providers.push_back({"name4",
  15619. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15620. // test the offset is given correctly at each step
  15621. if (!offset)
  15622. sink.os.write(rand2.data(), 2000);
  15623. else if (offset == 2000)
  15624. sink.os.write(rand2.data() + 2000, 1);
  15625. else if (offset == 2001)
  15626. sink.os.write(rand2.data() + 2001, 999);
  15627. else if (offset == rand2.size())
  15628. sink.done();
  15629. return true;
  15630. },
  15631. "filename4",
  15632. {}});
  15633. {
  15634. auto res = cli.Post("/post-providers", {}, {}, providers);
  15635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15636. ASSERT_EQ(StatusCode::OK_200, res->status);
  15637. }
  15638. {
  15639. auto res = cli.Post("/post-both", {}, items, providers);
  15640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15641. ASSERT_EQ(StatusCode::OK_200, res->status);
  15642. }
  15643. }
  15644. }
  15645. TEST(MultipartFormDataTest, BadHeader) {
  15646. Server svr;
  15647. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15648. res.set_content("ok", "text/plain");
  15649. });
  15650. thread t = thread([&] { svr.listen(HOST, PORT); });
  15651. auto se = detail::scope_exit([&] {
  15652. svr.stop();
  15653. t.join();
  15654. ASSERT_FALSE(svr.is_running());
  15655. });
  15656. svr.wait_until_ready();
  15657. const std::string body =
  15658. "This is the preamble. It is to be ignored, though it\r\n"
  15659. "is a handy place for composition agents to include an\r\n"
  15660. "explanatory note to non-MIME conformant readers.\r\n"
  15661. "\r\n"
  15662. "\r\n"
  15663. "--simple boundary\r\n"
  15664. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15665. ": BAD...\r\n"
  15666. "\r\n"
  15667. "value1\r\n"
  15668. "--simple boundary\r\n"
  15669. "Content-Disposition: form-data; name=\"field2\"; "
  15670. "filename=\"example.txt\"\r\n"
  15671. "\r\n"
  15672. "value2\r\n"
  15673. "--simple boundary--\r\n"
  15674. "This is the epilogue. It is also to be ignored.\r\n";
  15675. std::string content_type =
  15676. R"(multipart/form-data; boundary="simple boundary")";
  15677. Client cli(HOST, PORT);
  15678. auto res = cli.Post("/post", body, content_type.c_str());
  15679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15680. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15681. }
  15682. TEST(MultipartFormDataTest, WithPreamble) {
  15683. Server svr;
  15684. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15685. res.set_content("ok", "text/plain");
  15686. });
  15687. thread t = thread([&] { svr.listen(HOST, PORT); });
  15688. auto se = detail::scope_exit([&] {
  15689. svr.stop();
  15690. t.join();
  15691. ASSERT_FALSE(svr.is_running());
  15692. });
  15693. svr.wait_until_ready();
  15694. const std::string body =
  15695. "This is the preamble. It is to be ignored, though it\r\n"
  15696. "is a handy place for composition agents to include an\r\n"
  15697. "explanatory note to non-MIME conformant readers.\r\n"
  15698. "\r\n"
  15699. "\r\n"
  15700. "--simple boundary\r\n"
  15701. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15702. "\r\n"
  15703. "value1\r\n"
  15704. "--simple boundary\r\n"
  15705. "Content-Disposition: form-data; name=\"field2\"; "
  15706. "filename=\"example.txt\"\r\n"
  15707. "\r\n"
  15708. "value2\r\n"
  15709. "--simple boundary--\r\n"
  15710. "This is the epilogue. It is also to be ignored.\r\n";
  15711. std::string content_type =
  15712. R"(multipart/form-data; boundary="simple boundary")";
  15713. Client cli(HOST, PORT);
  15714. auto res = cli.Post("/post", body, content_type.c_str());
  15715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15716. EXPECT_EQ(StatusCode::OK_200, res->status);
  15717. }
  15718. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15720. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15721. const ContentReader &content_reader) {
  15722. if (req.is_multipart_form_data()) {
  15723. std::vector<FormData> items;
  15724. content_reader(
  15725. [&](const FormData &file) {
  15726. items.push_back(file);
  15727. return true;
  15728. },
  15729. [&](const char *data, size_t data_length) {
  15730. items.back().content.append(data, data_length);
  15731. return true;
  15732. });
  15733. EXPECT_TRUE(std::string(items[0].name) == "document");
  15734. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15735. EXPECT_TRUE(items[0].filename == "2MB_data");
  15736. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15737. EXPECT_TRUE(items[1].name == "hello");
  15738. EXPECT_TRUE(items[1].content == "world");
  15739. EXPECT_TRUE(items[1].filename == "");
  15740. EXPECT_TRUE(items[1].content_type == "");
  15741. } else {
  15742. std::string body;
  15743. content_reader([&](const char *data, size_t data_length) {
  15744. body.append(data, data_length);
  15745. return true;
  15746. });
  15747. }
  15748. });
  15749. auto port = svr.bind_to_any_port("localhost");
  15750. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15751. auto se = detail::scope_exit([&] {
  15752. svr.stop();
  15753. t.join();
  15754. ASSERT_FALSE(svr.is_running());
  15755. });
  15756. svr.wait_until_ready();
  15757. {
  15758. std::string data(1024 * 1024 * 2, '.');
  15759. std::stringstream buffer;
  15760. buffer << data;
  15761. SSLClient cli("localhost", port);
  15762. cli.enable_server_certificate_verification(false);
  15763. UploadFormDataItems items{
  15764. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15765. {"hello", "world", "", ""},
  15766. };
  15767. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15769. ASSERT_EQ(StatusCode::OK_200, res->status);
  15770. }
  15771. }
  15772. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15773. std::string data(1024 * 1024 * 2, '&');
  15774. std::stringstream buffer;
  15775. buffer << data;
  15776. Client cli("https://localhost:8080");
  15777. UploadFormDataItems items{
  15778. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15779. {"hello", "world", "", ""},
  15780. };
  15781. for (const char &c : " \t\r\n") {
  15782. auto res =
  15783. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15784. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15785. ASSERT_FALSE(res);
  15786. }
  15787. }
  15788. TEST(MultipartFormDataTest, PutFormData) {
  15789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15790. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15791. const ContentReader &content_reader) {
  15792. if (req.is_multipart_form_data()) {
  15793. std::vector<FormData> items;
  15794. content_reader(
  15795. [&](const FormData &file) {
  15796. items.push_back(file);
  15797. return true;
  15798. },
  15799. [&](const char *data, size_t data_length) {
  15800. items.back().content.append(data, data_length);
  15801. return true;
  15802. });
  15803. EXPECT_TRUE(std::string(items[0].name) == "document");
  15804. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15805. EXPECT_TRUE(items[0].filename == "2MB_data");
  15806. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15807. EXPECT_TRUE(items[1].name == "hello");
  15808. EXPECT_TRUE(items[1].content == "world");
  15809. EXPECT_TRUE(items[1].filename == "");
  15810. EXPECT_TRUE(items[1].content_type == "");
  15811. } else {
  15812. std::string body;
  15813. content_reader([&](const char *data, size_t data_length) {
  15814. body.append(data, data_length);
  15815. return true;
  15816. });
  15817. }
  15818. });
  15819. auto port = svr.bind_to_any_port("localhost");
  15820. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15821. auto se = detail::scope_exit([&] {
  15822. svr.stop();
  15823. t.join();
  15824. ASSERT_FALSE(svr.is_running());
  15825. });
  15826. svr.wait_until_ready();
  15827. {
  15828. std::string data(1024 * 1024 * 2, '&');
  15829. std::stringstream buffer;
  15830. buffer << data;
  15831. SSLClient cli("localhost", port);
  15832. cli.enable_server_certificate_verification(false);
  15833. UploadFormDataItems items{
  15834. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15835. {"hello", "world", "", ""},
  15836. };
  15837. auto res = cli.Put("/put", items);
  15838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15839. ASSERT_EQ(StatusCode::OK_200, res->status);
  15840. }
  15841. }
  15842. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15844. svr.Put("/put_customboundary",
  15845. [&](const Request &req, const Response & /*res*/,
  15846. const ContentReader &content_reader) {
  15847. if (req.is_multipart_form_data()) {
  15848. std::vector<FormData> items;
  15849. content_reader(
  15850. [&](const FormData &file) {
  15851. items.push_back(file);
  15852. return true;
  15853. },
  15854. [&](const char *data, size_t data_length) {
  15855. items.back().content.append(data, data_length);
  15856. return true;
  15857. });
  15858. EXPECT_TRUE(std::string(items[0].name) == "document");
  15859. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15860. EXPECT_TRUE(items[0].filename == "2MB_data");
  15861. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15862. EXPECT_TRUE(items[1].name == "hello");
  15863. EXPECT_TRUE(items[1].content == "world");
  15864. EXPECT_TRUE(items[1].filename == "");
  15865. EXPECT_TRUE(items[1].content_type == "");
  15866. } else {
  15867. std::string body;
  15868. content_reader([&](const char *data, size_t data_length) {
  15869. body.append(data, data_length);
  15870. return true;
  15871. });
  15872. }
  15873. });
  15874. auto port = svr.bind_to_any_port("localhost");
  15875. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15876. auto se = detail::scope_exit([&] {
  15877. svr.stop();
  15878. t.join();
  15879. ASSERT_FALSE(svr.is_running());
  15880. });
  15881. svr.wait_until_ready();
  15882. {
  15883. std::string data(1024 * 1024 * 2, '&');
  15884. std::stringstream buffer;
  15885. buffer << data;
  15886. SSLClient cli("localhost", port);
  15887. cli.enable_server_certificate_verification(false);
  15888. UploadFormDataItems items{
  15889. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15890. {"hello", "world", "", ""},
  15891. };
  15892. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15894. ASSERT_EQ(StatusCode::OK_200, res->status);
  15895. }
  15896. }
  15897. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15898. std::string data(1024 * 1024 * 2, '&');
  15899. std::stringstream buffer;
  15900. buffer << data;
  15901. Client cli("https://localhost:8080");
  15902. cli.enable_server_certificate_verification(false);
  15903. UploadFormDataItems items{
  15904. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15905. {"hello", "world", "", ""},
  15906. };
  15907. for (const char &c : " \t\r\n") {
  15908. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15909. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15910. ASSERT_FALSE(res);
  15911. }
  15912. }
  15913. TEST(MultipartFormDataTest, AlternateFilename) {
  15914. auto handled = false;
  15915. Server svr;
  15916. svr.Post("/test", [&](const Request &req, Response &res) {
  15917. ASSERT_EQ(2u, req.form.files.size());
  15918. ASSERT_EQ(1u, req.form.fields.size());
  15919. // Test files
  15920. const auto &file1 = req.form.get_file("file1");
  15921. ASSERT_EQ("file1", file1.name);
  15922. ASSERT_EQ("A.txt", file1.filename);
  15923. ASSERT_EQ("text/plain", file1.content_type);
  15924. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15925. const auto &file2 = req.form.get_file("file2");
  15926. ASSERT_EQ("file2", file2.name);
  15927. ASSERT_EQ("a.html", file2.filename);
  15928. ASSERT_EQ("text/html", file2.content_type);
  15929. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15930. file2.content);
  15931. // Test text field
  15932. const auto &text = req.form.get_field("text");
  15933. ASSERT_EQ("text default", text);
  15934. res.set_content("ok", "text/plain");
  15935. handled = true;
  15936. });
  15937. thread t = thread([&] { svr.listen(HOST, PORT); });
  15938. auto se = detail::scope_exit([&] {
  15939. svr.stop();
  15940. t.join();
  15941. ASSERT_FALSE(svr.is_running());
  15942. ASSERT_TRUE(handled);
  15943. });
  15944. svr.wait_until_ready();
  15945. auto req = "POST /test HTTP/1.1\r\n"
  15946. "Host: localhost\r\n"
  15947. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15948. "Content-Length: 399\r\n"
  15949. "\r\n"
  15950. "----------\r\n"
  15951. "Content-Disposition: form-data; name=\"text\"\r\n"
  15952. "\r\n"
  15953. "text default\r\n"
  15954. "----------\r\n"
  15955. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15956. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15957. "Content-Type: text/plain\r\n"
  15958. "\r\n"
  15959. "Content of a.txt.\r\n"
  15960. "\r\n"
  15961. "----------\r\n"
  15962. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15963. "\"a.html\"\r\n"
  15964. "Content-Type: text/html\r\n"
  15965. "\r\n"
  15966. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15967. "\r\n"
  15968. "------------\r\n";
  15969. ASSERT_TRUE(send_request(1, req));
  15970. }
  15971. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15972. auto handled = false;
  15973. Server svr;
  15974. svr.Post("/test", [&](const Request &req, Response &res) {
  15975. // Case-insensitive "utf-8''" prefix with a long value
  15976. const auto &file = req.form.get_file("file1");
  15977. ASSERT_EQ("file1", file.name);
  15978. // 8000 chars exercises both the Content-Disposition parser and the
  15979. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15980. // Prior to the fix, std::regex_match on this header would cause O(N)
  15981. // stack recursion in libstdc++, leading to SIGSEGV.
  15982. std::string expected_filename(8000, 'A');
  15983. ASSERT_EQ(expected_filename, file.filename);
  15984. res.set_content("ok", "text/plain");
  15985. handled = true;
  15986. });
  15987. thread t = thread([&] { svr.listen(HOST, PORT); });
  15988. auto se = detail::scope_exit([&] {
  15989. svr.stop();
  15990. t.join();
  15991. ASSERT_FALSE(svr.is_running());
  15992. ASSERT_TRUE(handled);
  15993. });
  15994. svr.wait_until_ready();
  15995. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15996. // Regression test for GHSA-qq6v-r583-3h69
  15997. std::string long_filename(8000, 'A');
  15998. std::string body = "----------\r\n"
  15999. "Content-Disposition: form-data; name=\"file1\"; "
  16000. "filename*=\"Utf-8''" +
  16001. long_filename +
  16002. "\"\r\n"
  16003. "\r\n"
  16004. "hello\r\n"
  16005. "------------\r\n";
  16006. auto req = "POST /test HTTP/1.1\r\n"
  16007. "Host: localhost\r\n"
  16008. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16009. "Content-Length: " +
  16010. std::to_string(body.size()) + "\r\n\r\n" + body;
  16011. ASSERT_TRUE(send_request(1, req));
  16012. }
  16013. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16014. auto handled = false;
  16015. Server svr;
  16016. svr.Post("/test", [&](const Request &req, Response &) {
  16017. ASSERT_EQ(2u, req.form.fields.size());
  16018. const auto &text1 = req.form.get_field("text1");
  16019. ASSERT_EQ("text1", text1);
  16020. const auto &text2 = req.form.get_field("text2");
  16021. ASSERT_EQ("text2", text2);
  16022. handled = true;
  16023. });
  16024. thread t = thread([&] { svr.listen(HOST, PORT); });
  16025. auto se = detail::scope_exit([&] {
  16026. svr.stop();
  16027. t.join();
  16028. ASSERT_FALSE(svr.is_running());
  16029. ASSERT_TRUE(handled);
  16030. });
  16031. svr.wait_until_ready();
  16032. auto req = "POST /test HTTP/1.1\r\n"
  16033. "Host: localhost\r\n"
  16034. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16035. "Content-Length: 146\r\n"
  16036. "\r\n----------\r\n"
  16037. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16038. "\r\n"
  16039. "text1"
  16040. "\r\n----------\r\n"
  16041. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16042. "\r\n"
  16043. "text2"
  16044. "\r\n------------";
  16045. std::string response;
  16046. ASSERT_TRUE(send_request(1, req, &response));
  16047. ASSERT_EQ("200", response.substr(9, 3));
  16048. }
  16049. TEST(MultipartFormDataTest, ContentLength) {
  16050. auto handled = false;
  16051. Server svr;
  16052. svr.Post("/test", [&](const Request &req, Response &) {
  16053. ASSERT_EQ(2u, req.form.fields.size());
  16054. const auto &text1 = req.form.get_field("text1");
  16055. ASSERT_EQ("text1", text1);
  16056. const auto &text2 = req.form.get_field("text2");
  16057. ASSERT_EQ("text2", text2);
  16058. handled = true;
  16059. });
  16060. thread t = thread([&] { svr.listen(HOST, PORT); });
  16061. auto se = detail::scope_exit([&] {
  16062. svr.stop();
  16063. t.join();
  16064. ASSERT_FALSE(svr.is_running());
  16065. ASSERT_TRUE(handled);
  16066. });
  16067. svr.wait_until_ready();
  16068. auto req = "POST /test HTTP/1.1\r\n"
  16069. "Host: localhost\r\n"
  16070. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16071. "Content-Length: 167\r\n"
  16072. "\r\n----------\r\n"
  16073. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16074. "Content-Length: 5\r\n"
  16075. "\r\n"
  16076. "text1"
  16077. "\r\n----------\r\n"
  16078. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16079. "\r\n"
  16080. "text2"
  16081. "\r\n------------\r\n";
  16082. std::string response;
  16083. ASSERT_TRUE(send_request(1, req, &response));
  16084. ASSERT_EQ("200", response.substr(9, 3));
  16085. }
  16086. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16087. auto handled = false;
  16088. Server svr;
  16089. svr.Post("/test", [&](const Request &req, Response &) {
  16090. ASSERT_EQ(2u, req.form.fields.size());
  16091. const auto &text1 = req.form.get_field("text1");
  16092. ASSERT_EQ("text1", text1);
  16093. // TODO: Add header access for text fields if needed
  16094. const auto &text2 = req.form.get_field("text2");
  16095. ASSERT_EQ("text2", text2);
  16096. // TODO: Header access for text fields needs to be implemented
  16097. // auto &headers = it->second.headers;
  16098. // ASSERT_EQ(3U, headers.size());
  16099. // auto custom_header = headers.find("x-whatever");
  16100. // ASSERT_TRUE(custom_header != headers.end());
  16101. // ASSERT_NE("customvalue", custom_header->second);
  16102. // ASSERT_EQ("CustomValue", custom_header->second);
  16103. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16104. handled = true;
  16105. });
  16106. thread t = thread([&] { svr.listen(HOST, PORT); });
  16107. auto se = detail::scope_exit([&] {
  16108. svr.stop();
  16109. t.join();
  16110. ASSERT_FALSE(svr.is_running());
  16111. ASSERT_TRUE(handled);
  16112. });
  16113. svr.wait_until_ready();
  16114. auto req = "POST /test HTTP/1.1\r\n"
  16115. "Host: localhost\r\n"
  16116. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16117. "Content-Length: 232\r\n"
  16118. "\r\n----------\r\n"
  16119. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16120. "Content-Length: 5\r\n"
  16121. "X-Test: 1\r\n"
  16122. "\r\n"
  16123. "text1"
  16124. "\r\n----------\r\n"
  16125. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16126. "Content-Type: text/plain\r\n"
  16127. "X-Whatever: CustomValue\r\n"
  16128. "\r\n"
  16129. "text2"
  16130. "\r\n------------\r\n"
  16131. "That should be disregarded. Not even read";
  16132. std::string response;
  16133. ASSERT_TRUE(send_request(1, req, &response));
  16134. ASSERT_EQ("200", response.substr(9, 3));
  16135. }
  16136. TEST(MultipartFormDataTest, LargeHeader) {
  16137. auto handled = false;
  16138. Server svr;
  16139. svr.Post("/test", [&](const Request &req, Response &) {
  16140. ASSERT_EQ(1u, req.form.fields.size());
  16141. const auto &text = req.form.get_field("name1");
  16142. ASSERT_EQ("text1", text);
  16143. handled = true;
  16144. });
  16145. thread t = thread([&] { svr.listen(HOST, PORT); });
  16146. auto se = detail::scope_exit([&] {
  16147. svr.stop();
  16148. t.join();
  16149. ASSERT_FALSE(svr.is_running());
  16150. ASSERT_TRUE(handled);
  16151. });
  16152. svr.wait_until_ready();
  16153. auto boundary = std::string("cpp-httplib-multipart-data");
  16154. std::string content = "--" + boundary +
  16155. "\r\n"
  16156. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16157. "\r\n"
  16158. "text1\r\n"
  16159. "--" +
  16160. boundary + "--\r\n";
  16161. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16162. "Host: localhost\r\n"
  16163. "Content-Type: multipart/form-data;boundary=" +
  16164. boundary +
  16165. "\r\n"
  16166. "Content-Length: " +
  16167. std::to_string(content.size()) +
  16168. "\r\n"
  16169. "Dummy-Header: ";
  16170. std::string header_suffix = "\r\n"
  16171. "\r\n";
  16172. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16173. size_t header_dummy_size =
  16174. read_buff_size -
  16175. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16176. auto header_dummy = std::string(header_dummy_size, '@');
  16177. auto req = header_prefix + header_dummy + header_suffix + content;
  16178. std::string response;
  16179. ASSERT_TRUE(send_request(1, req, &response));
  16180. ASSERT_EQ("200", response.substr(9, 3));
  16181. }
  16182. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16183. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16184. // (not chunked Transfer-Encoding) after the streaming refactor.
  16185. auto handled = false;
  16186. Server svr;
  16187. svr.Post("/upload", [&](const Request &req, Response &res) {
  16188. auto cl_it = req.headers.find("Content-Length");
  16189. EXPECT_TRUE(cl_it != req.headers.end());
  16190. auto te_it = req.headers.find("Transfer-Encoding");
  16191. EXPECT_TRUE(te_it == req.headers.end());
  16192. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16193. res.set_content("ok", "text/plain");
  16194. handled = true;
  16195. });
  16196. auto port = svr.bind_to_any_port(HOST);
  16197. auto t = thread([&] { svr.listen_after_bind(); });
  16198. auto se = detail::scope_exit([&] {
  16199. svr.stop();
  16200. t.join();
  16201. ASSERT_FALSE(svr.is_running());
  16202. ASSERT_TRUE(handled);
  16203. });
  16204. svr.wait_until_ready();
  16205. UploadFormDataItems items = {
  16206. {"field1", "hello", "", "text/plain"},
  16207. {"file1", "world", "test.txt", "application/octet-stream"},
  16208. };
  16209. Client cli(HOST, port);
  16210. auto res = cli.Post("/upload", {}, items);
  16211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16212. EXPECT_EQ(StatusCode::OK_200, res->status);
  16213. }
  16214. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16215. // Verify that make_multipart_content_provider coalesces many small segments
  16216. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16217. constexpr size_t kItemCount = 1000;
  16218. UploadFormDataItems items;
  16219. items.reserve(kItemCount);
  16220. for (size_t i = 0; i < kItemCount; i++) {
  16221. items.push_back(
  16222. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16223. }
  16224. const std::string boundary = "----test-boundary";
  16225. auto content_length = detail::get_multipart_content_length(items, boundary);
  16226. auto provider = detail::make_multipart_content_provider(items, boundary);
  16227. // Drive the provider the same way write_content_with_progress does
  16228. size_t write_count = 0;
  16229. size_t total_bytes = 0;
  16230. DataSink sink;
  16231. size_t offset = 0;
  16232. sink.write = [&](const char *d, size_t l) -> bool {
  16233. (void)d;
  16234. write_count++;
  16235. total_bytes += l;
  16236. offset += l;
  16237. return true;
  16238. };
  16239. sink.is_writable = []() -> bool { return true; };
  16240. while (offset < content_length) {
  16241. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16242. }
  16243. EXPECT_EQ(content_length, total_bytes);
  16244. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16245. // With buffering into 64KB blocks, write_count should be much smaller.
  16246. auto segment_count = 3 * kItemCount + 1;
  16247. EXPECT_LT(write_count, segment_count / 10);
  16248. }
  16249. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16250. // Integration test: send many UploadFormDataItems and verify the server
  16251. // receives all of them correctly (#2410).
  16252. constexpr size_t kItemCount = 500;
  16253. auto handled = false;
  16254. Server svr;
  16255. svr.Post("/upload", [&](const Request &req, Response &res) {
  16256. EXPECT_EQ(kItemCount, req.form.fields.size());
  16257. for (size_t i = 0; i < kItemCount; i++) {
  16258. auto key = "field" + std::to_string(i);
  16259. auto val = "value" + std::to_string(i);
  16260. auto it = req.form.fields.find(key);
  16261. if (it != req.form.fields.end()) {
  16262. EXPECT_EQ(val, it->second.content);
  16263. } else {
  16264. ADD_FAILURE() << "Missing field: " << key;
  16265. }
  16266. }
  16267. res.set_content("ok", "text/plain");
  16268. handled = true;
  16269. });
  16270. auto port = svr.bind_to_any_port(HOST);
  16271. auto t = thread([&] { svr.listen_after_bind(); });
  16272. auto se = detail::scope_exit([&] {
  16273. svr.stop();
  16274. t.join();
  16275. ASSERT_FALSE(svr.is_running());
  16276. ASSERT_TRUE(handled);
  16277. });
  16278. svr.wait_until_ready();
  16279. UploadFormDataItems items;
  16280. items.reserve(kItemCount);
  16281. for (size_t i = 0; i < kItemCount; i++) {
  16282. items.push_back(
  16283. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16284. }
  16285. Client cli(HOST, port);
  16286. auto res = cli.Post("/upload", items);
  16287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16288. EXPECT_EQ(StatusCode::OK_200, res->status);
  16289. }
  16290. TEST(MultipartFormDataTest, MakeFileProvider) {
  16291. // Verify make_file_provider sends a file's contents correctly.
  16292. const std::string file_content(4096, 'Z');
  16293. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16294. {
  16295. std::ofstream ofs(tmp_path, std::ios::binary);
  16296. ofs.write(file_content.data(),
  16297. static_cast<std::streamsize>(file_content.size()));
  16298. }
  16299. auto handled = false;
  16300. Server svr;
  16301. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16302. const ContentReader &content_reader) {
  16303. ASSERT_TRUE(req.is_multipart_form_data());
  16304. std::vector<FormData> items;
  16305. content_reader(
  16306. [&](const FormData &file) {
  16307. items.push_back(file);
  16308. return true;
  16309. },
  16310. [&](const char *data, size_t data_length) {
  16311. items.back().content.append(data, data_length);
  16312. return true;
  16313. });
  16314. ASSERT_EQ(1u, items.size());
  16315. EXPECT_EQ("myfile", items[0].name);
  16316. EXPECT_EQ("data.bin", items[0].filename);
  16317. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16318. EXPECT_EQ(file_content, items[0].content);
  16319. handled = true;
  16320. });
  16321. auto port = svr.bind_to_any_port(HOST);
  16322. auto t = thread([&] { svr.listen_after_bind(); });
  16323. auto se = detail::scope_exit([&] {
  16324. svr.stop();
  16325. t.join();
  16326. ASSERT_FALSE(svr.is_running());
  16327. ASSERT_TRUE(handled);
  16328. std::remove(tmp_path.c_str());
  16329. });
  16330. svr.wait_until_ready();
  16331. FormDataProviderItems providers;
  16332. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16333. "application/octet-stream"));
  16334. Client cli(HOST, port);
  16335. auto res = cli.Post("/upload", {}, {}, providers);
  16336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16337. EXPECT_EQ(StatusCode::OK_200, res->status);
  16338. }
  16339. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16340. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16341. // (100) headers is rejected with a 400 Bad Request response.
  16342. Server svr;
  16343. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16344. res.set_content("ok", "text/plain");
  16345. });
  16346. thread t = thread([&] { svr.listen(HOST, PORT); });
  16347. auto se = detail::scope_exit([&] {
  16348. svr.stop();
  16349. t.join();
  16350. ASSERT_FALSE(svr.is_running());
  16351. });
  16352. svr.wait_until_ready();
  16353. // Build a multipart part with 101 custom headers (exceeding
  16354. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16355. std::stringstream body;
  16356. body << "--simpleboundary\r\n"
  16357. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16358. for (int i = 0; i < 101; i++) {
  16359. body << "X-Custom-Header-" << i << ": value\r\n";
  16360. }
  16361. body << "\r\n"
  16362. << "value1\r\n"
  16363. << "--simpleboundary--\r\n";
  16364. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16365. Client cli(HOST, PORT);
  16366. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16368. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16369. }
  16370. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16371. // A body that never contains the declared boundary must not be accumulated
  16372. // while the parser waits for it. Buffering it would also make every read
  16373. // rescan everything seen so far, which is quadratic in the body size.
  16374. Server svr;
  16375. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16376. res.set_content("ok", "text/plain");
  16377. });
  16378. auto port = svr.bind_to_any_port(HOST);
  16379. thread t = thread([&] { svr.listen_after_bind(); });
  16380. auto se = detail::scope_exit([&] {
  16381. svr.stop();
  16382. t.join();
  16383. ASSERT_FALSE(svr.is_running());
  16384. });
  16385. svr.wait_until_ready();
  16386. Client cli(HOST, port);
  16387. cli.set_read_timeout(60, 0);
  16388. cli.set_write_timeout(60, 0);
  16389. // '-' is the worst case: it matches the first character of the boundary, so
  16390. // every position has to be checked against it.
  16391. auto post_dashes = [&](size_t size) {
  16392. const std::string body(size, '-');
  16393. auto start = std::chrono::steady_clock::now();
  16394. auto res =
  16395. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16396. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16397. std::chrono::steady_clock::now() - start)
  16398. .count();
  16399. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16400. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16401. return ms;
  16402. };
  16403. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16404. // Windows.
  16405. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16406. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16407. // Comparing the two sizes rather than checking an absolute duration keeps
  16408. // this meaningful across build types and CI load, both of which move the
  16409. // absolute numbers by more than an order of magnitude. Four times the bytes
  16410. // costs about four times the time when parsing is linear, and about sixteen
  16411. // times when the body is buffered and rescanned.
  16412. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16413. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16414. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16415. << "ms, which suggests the body is being buffered and rescanned";
  16416. }
  16417. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16418. // A boundary can only be followed by CRLF or by "--", so anything else is
  16419. // malformed no matter what comes next. The parser must say so right away
  16420. // instead of buffering the rest of the declared body.
  16421. Server svr;
  16422. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16423. res.set_content("ok", "text/plain");
  16424. });
  16425. auto port = svr.bind_to_any_port(HOST);
  16426. thread t = thread([&] { svr.listen_after_bind(); });
  16427. auto se = detail::scope_exit([&] {
  16428. svr.stop();
  16429. t.join();
  16430. ASSERT_FALSE(svr.is_running());
  16431. });
  16432. svr.wait_until_ready();
  16433. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16434. // buffers instead of failing would still be waiting for the remaining bytes.
  16435. const std::string body = "--zzzz\r\n"
  16436. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16437. "\r\n"
  16438. "text1"
  16439. "\r\n--zzzzXX";
  16440. const std::string req = "POST /post HTTP/1.1\r\n"
  16441. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16442. "Content-Length: 1048576\r\n"
  16443. "\r\n" +
  16444. body;
  16445. std::string response;
  16446. ASSERT_TRUE(send_request(3, req, &response, port));
  16447. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16448. EXPECT_EQ("400", response.substr(9, 3));
  16449. }
  16450. // Posts a multipart body split into two writes, so that the server sees the
  16451. // split at whatever offset the caller chose, and expects the single "text1"
  16452. // field to come through.
  16453. static void expect_split_multipart_ok(const std::string &body1,
  16454. const std::string &body2) {
  16455. auto handled = false;
  16456. Server svr;
  16457. svr.Post("/post", [&](const Request &req, Response &) {
  16458. EXPECT_EQ(1u, req.form.fields.size());
  16459. EXPECT_EQ("text1", req.form.get_field("text1"));
  16460. handled = true;
  16461. });
  16462. auto port = svr.bind_to_any_port(HOST);
  16463. thread t = thread([&] { svr.listen_after_bind(); });
  16464. auto se = detail::scope_exit([&] {
  16465. svr.stop();
  16466. t.join();
  16467. ASSERT_FALSE(svr.is_running());
  16468. ASSERT_TRUE(handled);
  16469. });
  16470. svr.wait_until_ready();
  16471. // "Connection: close" makes the server close once it has answered, so the
  16472. // response drain ends immediately instead of idling until the read timeout.
  16473. const std::string head =
  16474. "POST /post HTTP/1.1\r\n"
  16475. "Host: localhost\r\n"
  16476. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16477. "Connection: close\r\n"
  16478. "Content-Length: " +
  16479. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16480. std::string response;
  16481. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16482. ASSERT_GE(response.size(), 12u) << "no response";
  16483. EXPECT_EQ("200", response.substr(9, 3));
  16484. }
  16485. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16486. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16487. // ignored, including when it does not arrive in the same read as the
  16488. // close-delimiter itself.
  16489. expect_split_multipart_ok("--zzzz\r\n"
  16490. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16491. "\r\n"
  16492. "text1"
  16493. "\r\n--zzzz--",
  16494. "\r\nthis epilogue must be ignored\r\n");
  16495. }
  16496. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16497. // The initial boundary may be preceded by a preamble of any length and may
  16498. // straddle a read boundary. Discarding data while waiting for it must not
  16499. // throw away a partial boundary sitting at the end of the buffer.
  16500. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16501. "zz\r\n"
  16502. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16503. "\r\n"
  16504. "text1"
  16505. "\r\n--zzzz--\r\n");
  16506. }
  16507. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16508. // The received boundary was only checked for being non-empty, so it could be
  16509. // as long as a header is allowed to be. The parser scans the body for
  16510. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16511. // costs a nearly full comparison at nearly every position, making the
  16512. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16513. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16514. Server svr;
  16515. svr.Post("/post", [](const Request &req, Response &res) {
  16516. EXPECT_EQ(1u, req.form.fields.size());
  16517. EXPECT_EQ("text1", req.form.get_field("text1"));
  16518. res.set_content("ok", "text/plain");
  16519. });
  16520. auto port = svr.bind_to_any_port(HOST);
  16521. thread t = thread([&] { svr.listen_after_bind(); });
  16522. auto se = detail::scope_exit([&] {
  16523. svr.stop();
  16524. t.join();
  16525. ASSERT_FALSE(svr.is_running());
  16526. });
  16527. svr.wait_until_ready();
  16528. Client cli(HOST, port);
  16529. auto post_with_boundary_of_length = [&](size_t len) {
  16530. const std::string boundary(len, 'a');
  16531. const std::string body =
  16532. "--" + boundary +
  16533. "\r\n"
  16534. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16535. "\r\n"
  16536. "text1"
  16537. "\r\n--" +
  16538. boundary + "--\r\n";
  16539. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16540. };
  16541. auto res = post_with_boundary_of_length(70);
  16542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16543. EXPECT_EQ(StatusCode::OK_200, res->status);
  16544. res = post_with_boundary_of_length(71);
  16545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16546. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16547. }
  16548. TEST(MakeFileBodyTest, Basic) {
  16549. const std::string file_content(4096, 'Z');
  16550. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16551. {
  16552. std::ofstream ofs(tmp_path, std::ios::binary);
  16553. ofs.write(file_content.data(),
  16554. static_cast<std::streamsize>(file_content.size()));
  16555. }
  16556. auto handled = false;
  16557. Server svr;
  16558. svr.Post("/upload", [&](const Request &req, Response &res) {
  16559. EXPECT_EQ(file_content, req.body);
  16560. handled = true;
  16561. res.status = StatusCode::OK_200;
  16562. });
  16563. auto port = svr.bind_to_any_port(HOST);
  16564. auto t = thread([&] { svr.listen_after_bind(); });
  16565. auto se = detail::scope_exit([&] {
  16566. svr.stop();
  16567. t.join();
  16568. ASSERT_FALSE(svr.is_running());
  16569. ASSERT_TRUE(handled);
  16570. std::remove(tmp_path.c_str());
  16571. });
  16572. svr.wait_until_ready();
  16573. auto fb = make_file_body(tmp_path);
  16574. ASSERT_GT(fb.first, 0u);
  16575. Client cli(HOST, port);
  16576. auto res =
  16577. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16579. EXPECT_EQ(StatusCode::OK_200, res->status);
  16580. }
  16581. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16582. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16583. {
  16584. std::ofstream ofs(path, std::ios::binary);
  16585. const std::string content(100, 'A');
  16586. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16587. }
  16588. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16589. auto body = make_file_body(path);
  16590. ASSERT_EQ(100u, body.first);
  16591. ASSERT_TRUE(static_cast<bool>(body.second));
  16592. // Rewritten shorter after its length was measured - and, on a server, after
  16593. // that length has already gone out as Content-Length.
  16594. {
  16595. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16596. const std::string content(10, 'A');
  16597. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16598. }
  16599. std::string written;
  16600. DataSink sink;
  16601. sink.write = [&](const char *d, size_t l) {
  16602. written.append(d, l);
  16603. return true;
  16604. };
  16605. // The provider has to report failure. write_content_with_progress() advances
  16606. // its offset only by what was written, so a provider that returns true
  16607. // without completing the length it promised is called again straight away,
  16608. // and again.
  16609. EXPECT_FALSE(body.second(0, body.first, sink));
  16610. EXPECT_EQ(std::string(10, 'A'), written);
  16611. }
  16612. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16613. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16614. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16615. {
  16616. std::ofstream ofs(path, std::ios::binary);
  16617. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16618. }
  16619. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16620. auto body = make_file_body(path);
  16621. ASSERT_EQ(content.size(), body.first);
  16622. ASSERT_TRUE(static_cast<bool>(body.second));
  16623. std::string written;
  16624. DataSink sink;
  16625. sink.write = [&](const char *d, size_t l) {
  16626. written.append(d, l);
  16627. return true;
  16628. };
  16629. EXPECT_TRUE(body.second(0, body.first, sink));
  16630. EXPECT_EQ(content, written);
  16631. }
  16632. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16633. static constexpr unsigned int number_of_tasks{1000000};
  16634. std::atomic_uint count{0};
  16635. std::unique_ptr<TaskQueue> task_queue{
  16636. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16637. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16638. auto queued = task_queue->enqueue(
  16639. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16640. EXPECT_TRUE(queued);
  16641. }
  16642. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16643. task_queue->shutdown();
  16644. #else
  16645. EXPECT_NO_THROW(task_queue->shutdown());
  16646. #endif
  16647. EXPECT_EQ(number_of_tasks, count.load());
  16648. }
  16649. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16650. static constexpr unsigned int number_of_tasks{1000000};
  16651. static constexpr unsigned int qlimit{2};
  16652. unsigned int queued_count{0};
  16653. std::atomic_uint count{0};
  16654. std::unique_ptr<TaskQueue> task_queue{
  16655. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16656. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16657. if (task_queue->enqueue(
  16658. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16659. queued_count++;
  16660. }
  16661. }
  16662. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16663. task_queue->shutdown();
  16664. #else
  16665. EXPECT_NO_THROW(task_queue->shutdown());
  16666. #endif
  16667. EXPECT_EQ(queued_count, count.load());
  16668. EXPECT_TRUE(queued_count <= number_of_tasks);
  16669. EXPECT_TRUE(queued_count >= qlimit);
  16670. }
  16671. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16672. // Use a short idle timeout so a dynamic thread spawns, times out and
  16673. // exits during the test, and the pool keeps working afterwards.
  16674. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16675. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16676. /*idle_timeout_sec=*/1}};
  16677. std::atomic_uint count{0};
  16678. std::condition_variable cv;
  16679. std::mutex mtx;
  16680. bool release = false;
  16681. // Block the base thread so the second task spawns a dynamic thread.
  16682. EXPECT_TRUE(task_queue->enqueue([&] {
  16683. std::unique_lock<std::mutex> lock(mtx);
  16684. while (!release) {
  16685. cv.wait(lock);
  16686. }
  16687. count++;
  16688. }));
  16689. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16690. // Let the dynamic thread finish its task and exceed the idle timeout.
  16691. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16692. {
  16693. std::unique_lock<std::mutex> lock(mtx);
  16694. release = true;
  16695. }
  16696. cv.notify_all();
  16697. // The pool must still accept and run tasks after the dynamic thread exited.
  16698. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16699. task_queue->shutdown();
  16700. EXPECT_EQ(3u, count.load());
  16701. }
  16702. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16703. static constexpr size_t number_of_tasks{32};
  16704. std::unique_ptr<TaskQueue> task_queue{
  16705. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16706. // Let the base threads go idle so the burst below finds them waiting.
  16707. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16708. std::mutex mtx;
  16709. std::condition_variable cv;
  16710. size_t running = 0;
  16711. bool release = false;
  16712. for (size_t i = 0; i < number_of_tasks; i++) {
  16713. EXPECT_TRUE(task_queue->enqueue([&] {
  16714. std::unique_lock<std::mutex> lock(mtx);
  16715. running++;
  16716. cv.notify_all();
  16717. cv.wait(lock, [&] { return release; });
  16718. }));
  16719. }
  16720. {
  16721. std::unique_lock<std::mutex> lock(mtx);
  16722. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16723. [&] { return running == number_of_tasks; }));
  16724. release = true;
  16725. }
  16726. cv.notify_all();
  16727. task_queue->shutdown();
  16728. }
  16729. TEST(TaskQueueTest, MaxQueuedRequests) {
  16730. static constexpr unsigned int qlimit{3};
  16731. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16732. std::condition_variable sem_cv;
  16733. std::mutex sem_mtx;
  16734. int credits = 0;
  16735. bool queued;
  16736. /* Fill up the queue with tasks that will block until we give them credits to
  16737. * complete. */
  16738. for (unsigned int n = 0; n <= qlimit;) {
  16739. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16740. std::unique_lock<std::mutex> lock(sem_mtx);
  16741. while (credits <= 0) {
  16742. sem_cv.wait(lock);
  16743. }
  16744. /* Consume the credit and signal the test code if they are all gone. */
  16745. if (--credits == 0) { sem_cv.notify_one(); }
  16746. });
  16747. if (n < qlimit) {
  16748. /* The first qlimit enqueues must succeed. */
  16749. EXPECT_TRUE(queued);
  16750. } else {
  16751. /* The last one will succeed only when the worker thread
  16752. * starts and dequeues the first blocking task. Although
  16753. * not necessary for the correctness of this test, we sleep for
  16754. * a short while to avoid busy waiting. */
  16755. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16756. }
  16757. if (queued) { n++; }
  16758. }
  16759. /* Further enqueues must fail since the queue is full. */
  16760. for (auto i = 0; i < 4; i++) {
  16761. queued = task_queue->enqueue([] {});
  16762. EXPECT_FALSE(queued);
  16763. }
  16764. /* Give the credits to allow the previous tasks to complete. */
  16765. {
  16766. std::unique_lock<std::mutex> lock(sem_mtx);
  16767. credits += qlimit + 1;
  16768. }
  16769. sem_cv.notify_all();
  16770. /* Wait for all the credits to be consumed. */
  16771. {
  16772. std::unique_lock<std::mutex> lock(sem_mtx);
  16773. while (credits > 0) {
  16774. sem_cv.wait(lock);
  16775. }
  16776. }
  16777. /* Check that we are able again to enqueue at least qlimit tasks. */
  16778. for (unsigned int i = 0; i < qlimit; i++) {
  16779. queued = task_queue->enqueue([] {});
  16780. EXPECT_TRUE(queued);
  16781. }
  16782. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16783. task_queue->shutdown();
  16784. #else
  16785. EXPECT_NO_THROW(task_queue->shutdown());
  16786. #endif
  16787. }
  16788. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16789. Server svr;
  16790. std::string method;
  16791. std::string body;
  16792. auto has_content_length = false;
  16793. auto has_transfer_encoding = false;
  16794. std::atomic<int> bad_requests{0};
  16795. // Leftover body bytes get parsed as a malformed request and answered with
  16796. // 400
  16797. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16798. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16799. });
  16800. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16801. res.set_redirect("/down", StatusCode::SeeOther_303);
  16802. });
  16803. svr.Get("/down", [&](const Request &req, Response &res) {
  16804. method = req.method;
  16805. body = req.body;
  16806. has_content_length = req.has_header("Content-Length");
  16807. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16808. res.set_content("ok", "text/plain");
  16809. });
  16810. auto port = svr.bind_to_any_port(HOST);
  16811. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16812. auto se = detail::scope_exit([&] {
  16813. svr.stop();
  16814. thread.join();
  16815. ASSERT_FALSE(svr.is_running());
  16816. });
  16817. svr.wait_until_ready();
  16818. const std::string payload = "SECRET-BODY";
  16819. auto check = [&](Client &cli, const Result &res) {
  16820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16821. EXPECT_EQ(StatusCode::OK_200, res->status);
  16822. EXPECT_EQ("ok", res->body);
  16823. EXPECT_EQ("GET", method);
  16824. EXPECT_TRUE(body.empty());
  16825. EXPECT_FALSE(has_content_length);
  16826. EXPECT_FALSE(has_transfer_encoding);
  16827. // Nothing of the original body may be left on the connection
  16828. auto res2 = cli.Get("/down");
  16829. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16830. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16831. EXPECT_EQ("ok", res2->body);
  16832. EXPECT_EQ(0, bad_requests);
  16833. };
  16834. // With content length
  16835. {
  16836. Client cli(HOST, port);
  16837. cli.set_keep_alive(true);
  16838. cli.set_follow_location(true);
  16839. auto res = cli.Post(
  16840. "/up", payload.size(),
  16841. [&](size_t offset, size_t length, DataSink &sink) {
  16842. return sink.write(payload.data() + offset, length);
  16843. },
  16844. "text/plain");
  16845. check(cli, res);
  16846. }
  16847. // Without content length (chunked)
  16848. {
  16849. Client cli(HOST, port);
  16850. cli.set_keep_alive(true);
  16851. cli.set_follow_location(true);
  16852. auto res = cli.Post(
  16853. "/up",
  16854. [&](size_t /*offset*/, DataSink &sink) {
  16855. sink.write(payload.data(), payload.size());
  16856. sink.done();
  16857. return true;
  16858. },
  16859. "text/plain");
  16860. check(cli, res);
  16861. }
  16862. }
  16863. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16864. Server svr;
  16865. std::string target;
  16866. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16867. // Echo the still-encoded name back in the Location
  16868. const std::string prefix = "/start/";
  16869. res.status = StatusCode::Found_302;
  16870. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16871. });
  16872. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16873. target = req.target;
  16874. res.set_content("ok", "text/plain");
  16875. });
  16876. auto port = svr.bind_to_any_port(HOST);
  16877. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16878. auto se = detail::scope_exit([&] {
  16879. svr.stop();
  16880. thread.join();
  16881. ASSERT_FALSE(svr.is_running());
  16882. });
  16883. svr.wait_until_ready();
  16884. // Decoding the Location path would turn the first four into a path
  16885. // separator, a query delimiter, a fragment delimiter and a different
  16886. // percent-encoded octet. The rest must keep reaching the server as they are.
  16887. const std::vector<std::string> names = {
  16888. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16889. };
  16890. for (auto path_encode : {true, false}) {
  16891. Client cli(HOST, port);
  16892. cli.set_follow_location(true);
  16893. cli.set_path_encode(path_encode);
  16894. for (const auto &name : names) {
  16895. target.clear();
  16896. auto res = cli.Get("/start/" + name);
  16897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16898. EXPECT_EQ(StatusCode::OK_200, res->status);
  16899. EXPECT_EQ("/dest/" + name, target);
  16900. }
  16901. }
  16902. }
  16903. TEST(RedirectTest, NotModifiedIsReturned) {
  16904. Server svr;
  16905. svr.Get("/cached", [](const Request &, Response &res) {
  16906. res.status = StatusCode::NotModified_304;
  16907. });
  16908. auto port = svr.bind_to_any_port(HOST);
  16909. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16910. auto se = detail::scope_exit([&] {
  16911. svr.stop();
  16912. thread.join();
  16913. ASSERT_FALSE(svr.is_running());
  16914. });
  16915. svr.wait_until_ready();
  16916. Client cli(HOST, port);
  16917. cli.set_follow_location(true);
  16918. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16920. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16921. }
  16922. TEST(RedirectTest, NoLocationIsReturned) {
  16923. Server svr;
  16924. svr.Get("/no-location", [](const Request &, Response &res) {
  16925. res.status = StatusCode::Found_302;
  16926. res.set_content("no location", "text/plain");
  16927. });
  16928. auto port = svr.bind_to_any_port(HOST);
  16929. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16930. auto se = detail::scope_exit([&] {
  16931. svr.stop();
  16932. thread.join();
  16933. ASSERT_FALSE(svr.is_running());
  16934. });
  16935. svr.wait_until_ready();
  16936. Client cli(HOST, port);
  16937. cli.set_follow_location(true);
  16938. auto res = cli.Get("/no-location");
  16939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16940. EXPECT_EQ(StatusCode::Found_302, res->status);
  16941. EXPECT_EQ("no location", res->body);
  16942. // The callbacks see the body of the response that is returned
  16943. auto handler_called = false;
  16944. auto progress_called = false;
  16945. std::string body;
  16946. auto res2 = cli.Get(
  16947. "/no-location",
  16948. [&](const Response &) {
  16949. handler_called = true;
  16950. return true;
  16951. },
  16952. [&](const char *data, size_t data_length) {
  16953. body.append(data, data_length);
  16954. return true;
  16955. },
  16956. [&](size_t, size_t) {
  16957. progress_called = true;
  16958. return true;
  16959. });
  16960. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16961. EXPECT_EQ(StatusCode::Found_302, res2->status);
  16962. EXPECT_TRUE(handler_called);
  16963. EXPECT_TRUE(progress_called);
  16964. EXPECT_EQ("no location", body);
  16965. }
  16966. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16967. Server svr;
  16968. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16969. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16970. });
  16971. svr.Get("/hello", [](const Request &req, Response &res) {
  16972. res.set_content(req.get_param_value("key"), "text/plain");
  16973. });
  16974. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16975. auto se = detail::scope_exit([&] {
  16976. svr.stop();
  16977. thread.join();
  16978. ASSERT_FALSE(svr.is_running());
  16979. });
  16980. svr.wait_until_ready();
  16981. {
  16982. Client cli(HOST, PORT);
  16983. cli.set_follow_location(true);
  16984. auto res = cli.Get("/");
  16985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16986. EXPECT_EQ(StatusCode::OK_200, res->status);
  16987. EXPECT_EQ("val&key2=val2", res->body);
  16988. }
  16989. }
  16990. #endif
  16991. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16992. Server svr;
  16993. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16994. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16995. });
  16996. svr.Get("/hello", [](const Request &req, Response &res) {
  16997. res.set_content(req.get_param_value("key"), "text/plain");
  16998. });
  16999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17000. auto se = detail::scope_exit([&] {
  17001. svr.stop();
  17002. thread.join();
  17003. ASSERT_FALSE(svr.is_running());
  17004. });
  17005. svr.wait_until_ready();
  17006. {
  17007. Client cli(HOST, PORT);
  17008. cli.set_follow_location(true);
  17009. auto res = cli.Get("/");
  17010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17011. EXPECT_EQ(StatusCode::OK_200, res->status);
  17012. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17013. }
  17014. }
  17015. TEST(RedirectTest, RedirectWithPlusInPath) {
  17016. Server svr;
  17017. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17018. res.set_redirect("/a+b");
  17019. });
  17020. // Route pattern uses regex; escape + as \\+
  17021. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17022. res.set_content(req.path, "text/plain");
  17023. });
  17024. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17025. auto se = detail::scope_exit([&] {
  17026. svr.stop();
  17027. thread.join();
  17028. ASSERT_FALSE(svr.is_running());
  17029. });
  17030. svr.wait_until_ready();
  17031. {
  17032. Client cli(HOST, PORT);
  17033. cli.set_follow_location(true);
  17034. auto res = cli.Get("/");
  17035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17036. EXPECT_EQ(StatusCode::OK_200, res->status);
  17037. EXPECT_EQ("/a+b", res->body);
  17038. }
  17039. }
  17040. TEST(RedirectTest, ResolveRelativeLocation) {
  17041. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17042. const std::vector<std::pair<std::string, std::string>> cases = {
  17043. {"g", "/b/c/g"},
  17044. {"./g", "/b/c/g"},
  17045. {"g/", "/b/c/g/"},
  17046. {"?y", "/b/c/d;p?y"},
  17047. {"g?y", "/b/c/g?y"},
  17048. {"#s", "/b/c/d;p?q#s"},
  17049. {"g#s", "/b/c/g#s"},
  17050. {"g?y#s", "/b/c/g?y#s"},
  17051. {";x", "/b/c/;x"},
  17052. {"g;x", "/b/c/g;x"},
  17053. {".", "/b/c/"},
  17054. {"./", "/b/c/"},
  17055. {"..", "/b/"},
  17056. {"../", "/b/"},
  17057. {"../g", "/b/g"},
  17058. {"../..", "/"},
  17059. {"../../", "/"},
  17060. {"../../g", "/g"},
  17061. {"../../../g", "/g"},
  17062. {"g.", "/b/c/g."},
  17063. {".g", "/b/c/.g"},
  17064. {"g..", "/b/c/g.."},
  17065. {"..g", "/b/c/..g"},
  17066. {"./../g", "/b/g"},
  17067. {"./g/.", "/b/c/g/"},
  17068. {"g/./h", "/b/c/g/h"},
  17069. {"g/../h", "/b/c/h"},
  17070. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17071. {"g;x=1/../y", "/b/c/y"},
  17072. {"g?y/./x", "/b/c/g?y/./x"},
  17073. {"g#s/../x", "/b/c/g#s/../x"},
  17074. // Not relative-path references, so left for parse_url.
  17075. {"/g", "/g"},
  17076. {"//g", "//g"},
  17077. {"http://g/x", "http://g/x"},
  17078. {"g:h", "g:h"},
  17079. };
  17080. for (const auto &c : cases) {
  17081. EXPECT_EQ(c.second,
  17082. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17083. << c.first;
  17084. }
  17085. }
  17086. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17087. Server svr;
  17088. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17089. res.set_redirect(req.get_param_value("to"));
  17090. });
  17091. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17092. res.set_content(req.target, "text/plain");
  17093. });
  17094. svr.Get("/other", [](const Request &req, Response &res) {
  17095. res.set_content(req.target, "text/plain");
  17096. });
  17097. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17098. auto se = detail::scope_exit([&] {
  17099. svr.stop();
  17100. thread.join();
  17101. ASSERT_FALSE(svr.is_running());
  17102. });
  17103. svr.wait_until_ready();
  17104. const std::vector<std::pair<std::string, std::string>> cases = {
  17105. {"next", "/dir/next"},
  17106. {"./next?x=1", "/dir/next?x=1"},
  17107. {"../other", "/other"},
  17108. };
  17109. for (const auto &c : cases) {
  17110. Client cli(HOST, PORT);
  17111. cli.set_follow_location(true);
  17112. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17113. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17114. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17115. EXPECT_EQ(c.second, res->body) << c.first;
  17116. }
  17117. }
  17118. #ifdef CPPHTTPLIB_SSL_ENABLED
  17119. TEST(RedirectTest, Issue2185_Online) {
  17120. SSLClient client("github.com");
  17121. client.set_follow_location(true);
  17122. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17123. "Coollab-Windows.zip");
  17124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17125. EXPECT_EQ(StatusCode::OK_200, res->status);
  17126. EXPECT_EQ(9920427U, res->body.size());
  17127. }
  17128. #endif
  17129. TEST(VulnerabilityTest, CRLFInjection) {
  17130. Server svr;
  17131. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17132. res.set_content("Hello 1", "text/plain");
  17133. });
  17134. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17135. res.set_content("Hello 2", "text/plain");
  17136. });
  17137. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17138. res.set_content("Hello 3", "text/plain");
  17139. });
  17140. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17141. res.set_content("Hello 4", "text/plain");
  17142. });
  17143. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17144. for (const auto &x : req.headers) {
  17145. auto key = x.first;
  17146. EXPECT_STRNE("evil", key.c_str());
  17147. }
  17148. });
  17149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17150. auto se = detail::scope_exit([&] {
  17151. svr.stop();
  17152. thread.join();
  17153. ASSERT_FALSE(svr.is_running());
  17154. });
  17155. svr.wait_until_ready();
  17156. {
  17157. Client cli(HOST, PORT);
  17158. cli.Post("/test1", "A=B",
  17159. "application/x-www-form-urlencoded\r\nevil: hello1");
  17160. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17161. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17162. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17163. }
  17164. }
  17165. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17166. auto server_thread = std::thread([] {
  17167. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17168. default_socket_options(srv);
  17169. sockaddr_in addr{};
  17170. addr.sin_family = AF_INET;
  17171. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17172. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17173. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17174. ::listen(srv, 1);
  17175. sockaddr_in cli_addr{};
  17176. socklen_t cli_len = sizeof(cli_addr);
  17177. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17178. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17179. std::string buf_all;
  17180. char buf[2048];
  17181. ssize_t n;
  17182. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17183. buf_all.append(buf, static_cast<size_t>(n));
  17184. size_t pos;
  17185. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17186. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17187. auto e = request_block.find("\r\n");
  17188. if (e != std::string::npos) {
  17189. auto request_line = request_block.substr(0, e);
  17190. std::string msg =
  17191. "CRLF injection detected in request line: '" + request_line + "'";
  17192. EXPECT_FALSE(true) << msg;
  17193. }
  17194. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17195. ::send(cli,
  17196. #ifdef _WIN32
  17197. static_cast<const char *>(resp.c_str()),
  17198. static_cast<int>(resp.size()),
  17199. #else
  17200. resp.c_str(), resp.size(),
  17201. #endif
  17202. 0);
  17203. buf_all.erase(0, pos + 4);
  17204. }
  17205. }
  17206. detail::close_socket(cli);
  17207. detail::close_socket(srv);
  17208. });
  17209. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17210. auto cli = Client("127.0.0.1", PORT + 1);
  17211. auto headers = Headers{
  17212. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17213. {"Connection", "keep-alive"}};
  17214. auto res = cli.Get("/hi", headers);
  17215. EXPECT_FALSE(res);
  17216. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17217. server_thread.join();
  17218. }
  17219. // A request rejected before any byte reaches the socket must fail right away
  17220. // instead of waiting for a response the server will never send.
  17221. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17222. // The kernel completes the TCP handshake from the listen backlog, so the
  17223. // client connects, but nothing ever reads, responds or closes.
  17224. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17225. default_socket_options(srv);
  17226. sockaddr_in addr{};
  17227. addr.sin_family = AF_INET;
  17228. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17229. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17230. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17231. ASSERT_EQ(0, ::listen(srv, 8));
  17232. auto cli = Client("127.0.0.1", PORT + 1);
  17233. cli.set_read_timeout(10, 0);
  17234. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17235. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17236. std::chrono::steady_clock::now() - start)
  17237. .count();
  17238. };
  17239. {
  17240. Request req;
  17241. req.method = "GE T";
  17242. req.path = "/";
  17243. auto start = std::chrono::steady_clock::now();
  17244. auto res = cli.send(req);
  17245. EXPECT_FALSE(res);
  17246. EXPECT_EQ(Error::Write, res.error());
  17247. EXPECT_LT(elapsed_ms(start), 1000);
  17248. }
  17249. {
  17250. auto start = std::chrono::steady_clock::now();
  17251. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17252. EXPECT_FALSE(res);
  17253. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17254. EXPECT_LT(elapsed_ms(start), 1000);
  17255. }
  17256. EXPECT_FALSE(cli.is_socket_open());
  17257. detail::close_socket(srv);
  17258. }
  17259. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17260. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17261. default_socket_options(srv);
  17262. sockaddr_in addr{};
  17263. addr.sin_family = AF_INET;
  17264. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17265. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17266. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17267. ASSERT_EQ(0, ::listen(srv, 1));
  17268. std::string received;
  17269. auto server_thread = std::thread([&] {
  17270. auto sock = ::accept(srv, nullptr, nullptr);
  17271. if (sock == INVALID_SOCKET) { return; }
  17272. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17273. char buf[2048];
  17274. ssize_t n;
  17275. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17276. received.append(buf, static_cast<size_t>(n));
  17277. }
  17278. detail::close_socket(sock);
  17279. });
  17280. {
  17281. auto cli = Client("127.0.0.1", PORT + 1);
  17282. // "Z" sorts after the default headers, so writing straight to the socket
  17283. // would have sent the request line and those headers before the rejection.
  17284. auto handle =
  17285. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17286. EXPECT_FALSE(handle.is_valid());
  17287. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17288. }
  17289. server_thread.join();
  17290. detail::close_socket(srv);
  17291. EXPECT_TRUE(received.empty()) << received;
  17292. }
  17293. TEST(PathParamsTest, StaticMatch) {
  17294. const auto pattern = "/users/all";
  17295. detail::PathParamsMatcher matcher(pattern);
  17296. Request request;
  17297. request.path = "/users/all";
  17298. ASSERT_TRUE(matcher.match(request));
  17299. std::unordered_map<std::string, std::string> expected_params = {};
  17300. EXPECT_EQ(request.path_params, expected_params);
  17301. }
  17302. TEST(PathParamsTest, StaticMismatch) {
  17303. const auto pattern = "/users/all";
  17304. detail::PathParamsMatcher matcher(pattern);
  17305. Request request;
  17306. request.path = "/users/1";
  17307. ASSERT_FALSE(matcher.match(request));
  17308. }
  17309. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17310. const auto pattern = "/users/:id/subscriptions";
  17311. detail::PathParamsMatcher matcher(pattern);
  17312. Request request;
  17313. request.path = "/users/42/subscriptions";
  17314. ASSERT_TRUE(matcher.match(request));
  17315. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17316. EXPECT_EQ(request.path_params, expected_params);
  17317. }
  17318. TEST(PathParamsTest, SingleParamInTheEnd) {
  17319. const auto pattern = "/users/:id";
  17320. detail::PathParamsMatcher matcher(pattern);
  17321. Request request;
  17322. request.path = "/users/24";
  17323. ASSERT_TRUE(matcher.match(request));
  17324. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17325. EXPECT_EQ(request.path_params, expected_params);
  17326. }
  17327. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17328. const auto pattern = "/users/:id/";
  17329. detail::PathParamsMatcher matcher(pattern);
  17330. Request request;
  17331. request.path = "/users/42/";
  17332. ASSERT_TRUE(matcher.match(request));
  17333. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17334. EXPECT_EQ(request.path_params, expected_params);
  17335. }
  17336. TEST(PathParamsTest, EmptyParam) {
  17337. const auto pattern = "/users/:id/";
  17338. detail::PathParamsMatcher matcher(pattern);
  17339. Request request;
  17340. request.path = "/users//";
  17341. ASSERT_TRUE(matcher.match(request));
  17342. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17343. EXPECT_EQ(request.path_params, expected_params);
  17344. }
  17345. TEST(PathParamsTest, FragmentMismatch) {
  17346. const auto pattern = "/users/:id/";
  17347. detail::PathParamsMatcher matcher(pattern);
  17348. Request request;
  17349. request.path = "/admins/24/";
  17350. ASSERT_FALSE(matcher.match(request));
  17351. }
  17352. TEST(PathParamsTest, ExtraFragments) {
  17353. const auto pattern = "/users/:id";
  17354. detail::PathParamsMatcher matcher(pattern);
  17355. Request request;
  17356. request.path = "/users/42/subscriptions";
  17357. ASSERT_FALSE(matcher.match(request));
  17358. }
  17359. TEST(PathParamsTest, MissingTrailingParam) {
  17360. const auto pattern = "/users/:id";
  17361. detail::PathParamsMatcher matcher(pattern);
  17362. Request request;
  17363. request.path = "/users";
  17364. ASSERT_FALSE(matcher.match(request));
  17365. }
  17366. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17367. const auto pattern = "/users/:id/subscriptions";
  17368. detail::PathParamsMatcher matcher(pattern);
  17369. Request request;
  17370. request.path = "/users/subscriptions";
  17371. ASSERT_FALSE(matcher.match(request));
  17372. }
  17373. TEST(PathParamsTest, MultipleParams) {
  17374. const auto pattern = "/users/:userid/subscriptions/:subid";
  17375. detail::PathParamsMatcher matcher(pattern);
  17376. Request request;
  17377. request.path = "/users/42/subscriptions/2";
  17378. ASSERT_TRUE(matcher.match(request));
  17379. std::unordered_map<std::string, std::string> expected_params = {
  17380. {"userid", "42"}, {"subid", "2"}};
  17381. EXPECT_EQ(request.path_params, expected_params);
  17382. }
  17383. TEST(PathParamsTest, SequenceOfParams) {
  17384. const auto pattern = "/values/:x/:y/:z";
  17385. detail::PathParamsMatcher matcher(pattern);
  17386. Request request;
  17387. request.path = "/values/1/2/3";
  17388. ASSERT_TRUE(matcher.match(request));
  17389. std::unordered_map<std::string, std::string> expected_params = {
  17390. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17391. EXPECT_EQ(request.path_params, expected_params);
  17392. }
  17393. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17394. const auto pattern = "/prefix:suffix";
  17395. detail::PathParamsMatcher matcher(pattern);
  17396. Request request;
  17397. request.path = "/prefix:suffix";
  17398. ASSERT_TRUE(matcher.match(request));
  17399. const std::unordered_map<std::string, std::string> expected_params = {};
  17400. EXPECT_EQ(request.path_params, expected_params);
  17401. }
  17402. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17403. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17404. // calling thread's stack on a long enough path for a quantified pattern;
  17405. // RegexMatcher must refuse to run regex matching on paths beyond
  17406. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17407. detail::RegexMatcher matcher("/files/(.*)");
  17408. Request within_limit;
  17409. within_limit.path = "/files/" + std::string(10, 'A');
  17410. EXPECT_TRUE(matcher.match(within_limit));
  17411. Request over_limit;
  17412. over_limit.path =
  17413. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17414. EXPECT_FALSE(matcher.match(over_limit));
  17415. }
  17416. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17417. Server svr;
  17418. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17419. res.set_content("ok", "text/plain");
  17420. });
  17421. auto port = svr.bind_to_any_port(HOST);
  17422. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17423. auto se = detail::scope_exit([&] {
  17424. svr.stop();
  17425. thread.join();
  17426. ASSERT_FALSE(svr.is_running());
  17427. });
  17428. svr.wait_until_ready();
  17429. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17430. // request URI limit; this used to be able to crash the process.
  17431. std::string path =
  17432. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17433. std::string req = "GET " + path +
  17434. " HTTP/1.1\r\n"
  17435. "Host: " +
  17436. std::string(HOST) + ":" + std::to_string(port) +
  17437. "\r\n"
  17438. "Connection: close\r\n"
  17439. "\r\n";
  17440. std::string response;
  17441. ASSERT_TRUE(send_request(5, req, &response, port));
  17442. EXPECT_NE(std::string::npos, response.find("404"));
  17443. }
  17444. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17445. Server svr;
  17446. auto handler = [](const Request & /*req*/, Response &res) {
  17447. res.set_content("hit", "text/plain");
  17448. };
  17449. // No regex metacharacter, so this one is compared literally
  17450. svr.Get("/literal/route", handler);
  17451. // '.' is a regex metacharacter, so this one must keep regex semantics
  17452. svr.Get("/a.c", handler);
  17453. auto port = svr.bind_to_any_port(HOST);
  17454. std::thread t([&]() { svr.listen_after_bind(); });
  17455. auto se = detail::scope_exit([&] {
  17456. svr.stop();
  17457. t.join();
  17458. ASSERT_FALSE(svr.is_running());
  17459. });
  17460. svr.wait_until_ready();
  17461. Client cli(HOST, port);
  17462. struct {
  17463. const char *path;
  17464. int status;
  17465. } cases[] = {
  17466. {"/literal/route", StatusCode::OK_200},
  17467. {"/literal/routes", StatusCode::NotFound_404},
  17468. {"/literal/rout", StatusCode::NotFound_404},
  17469. {"/abc", StatusCode::OK_200},
  17470. {"/a.c", StatusCode::OK_200},
  17471. };
  17472. for (const auto &x : cases) {
  17473. auto res = cli.Get(x.path);
  17474. ASSERT_TRUE(res) << x.path;
  17475. EXPECT_EQ(x.status, res->status) << x.path;
  17476. }
  17477. }
  17478. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17479. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17480. // from exhausting the stack, so it must only constrain routes that actually
  17481. // run a regular expression. A literal route is matched by comparison and
  17482. // stays usable at any length.
  17483. Server svr;
  17484. const std::string pattern =
  17485. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17486. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17487. res.set_content("hit", "text/plain");
  17488. });
  17489. auto port = svr.bind_to_any_port(HOST);
  17490. std::thread t([&]() { svr.listen_after_bind(); });
  17491. auto se = detail::scope_exit([&] {
  17492. svr.stop();
  17493. t.join();
  17494. ASSERT_FALSE(svr.is_running());
  17495. });
  17496. svr.wait_until_ready();
  17497. Client cli(HOST, port);
  17498. auto res = cli.Get(pattern);
  17499. ASSERT_TRUE(res);
  17500. EXPECT_EQ(StatusCode::OK_200, res->status);
  17501. }
  17502. TEST(ParseUrlTest, VariousPatterns) {
  17503. {
  17504. detail::UrlComponents uc;
  17505. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17506. EXPECT_EQ("http", uc.scheme);
  17507. EXPECT_EQ("example.com", uc.host);
  17508. EXPECT_EQ("8080", uc.port);
  17509. EXPECT_EQ("/path", uc.path);
  17510. EXPECT_EQ("?q=1", uc.query);
  17511. }
  17512. {
  17513. detail::UrlComponents uc;
  17514. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17515. EXPECT_EQ("https", uc.scheme);
  17516. EXPECT_EQ("example.com", uc.host);
  17517. EXPECT_TRUE(uc.port.empty());
  17518. EXPECT_EQ("/path", uc.path);
  17519. }
  17520. {
  17521. detail::UrlComponents uc;
  17522. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17523. EXPECT_EQ("::1", uc.host);
  17524. EXPECT_EQ("8080", uc.port);
  17525. EXPECT_EQ("/path", uc.path);
  17526. }
  17527. {
  17528. detail::UrlComponents uc;
  17529. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17530. }
  17531. {
  17532. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17533. // the path while the connection still targets the bracketed host.
  17534. detail::UrlComponents uc;
  17535. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17536. }
  17537. {
  17538. detail::UrlComponents uc;
  17539. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17540. }
  17541. {
  17542. detail::UrlComponents uc;
  17543. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17544. EXPECT_EQ("::1", uc.host);
  17545. EXPECT_TRUE(uc.port.empty());
  17546. EXPECT_EQ("/path", uc.path);
  17547. }
  17548. {
  17549. detail::UrlComponents uc;
  17550. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17551. EXPECT_TRUE(uc.scheme.empty());
  17552. EXPECT_EQ("example.com", uc.host);
  17553. EXPECT_EQ("/path", uc.path);
  17554. EXPECT_EQ("?q=1", uc.query);
  17555. }
  17556. {
  17557. detail::UrlComponents uc;
  17558. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17559. EXPECT_TRUE(uc.host.empty());
  17560. EXPECT_EQ("/path", uc.path);
  17561. EXPECT_EQ("?q=1", uc.query);
  17562. }
  17563. {
  17564. detail::UrlComponents uc;
  17565. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17566. EXPECT_EQ("example.com", uc.host);
  17567. EXPECT_EQ("8080", uc.port);
  17568. }
  17569. {
  17570. // Unix socket path — must not be parsed as host
  17571. detail::UrlComponents uc;
  17572. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17573. EXPECT_TRUE(uc.host.empty());
  17574. }
  17575. {
  17576. detail::UrlComponents uc;
  17577. ASSERT_TRUE(detail::parse_url("", uc));
  17578. EXPECT_TRUE(uc.host.empty());
  17579. EXPECT_TRUE(uc.path.empty());
  17580. }
  17581. {
  17582. detail::UrlComponents uc;
  17583. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17584. }
  17585. {
  17586. detail::UrlComponents uc;
  17587. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17588. }
  17589. {
  17590. // Accepted by parse_url; callers restrict to http/https
  17591. detail::UrlComponents uc;
  17592. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17593. EXPECT_EQ("ftp", uc.scheme);
  17594. }
  17595. {
  17596. detail::UrlComponents uc;
  17597. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17598. }
  17599. {
  17600. detail::UrlComponents uc;
  17601. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17602. }
  17603. }
  17604. TEST(ParseUrlTest, FragmentHandling) {
  17605. {
  17606. detail::UrlComponents uc;
  17607. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17608. EXPECT_EQ("/path", uc.path);
  17609. EXPECT_TRUE(uc.query.empty());
  17610. }
  17611. {
  17612. detail::UrlComponents uc;
  17613. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17614. EXPECT_TRUE(uc.path.empty());
  17615. EXPECT_TRUE(uc.query.empty());
  17616. }
  17617. }
  17618. TEST(ParseUrlTest, UserinfoHandling) {
  17619. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17620. // parsers would see evil.com as the host.
  17621. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17622. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17623. for (auto url : urls) {
  17624. detail::UrlComponents uc;
  17625. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17626. }
  17627. }
  17628. TEST(ParseUrlTest, IPv6EdgeCases) {
  17629. {
  17630. detail::UrlComponents uc;
  17631. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17632. EXPECT_TRUE(uc.scheme.empty());
  17633. EXPECT_EQ("::1", uc.host);
  17634. EXPECT_EQ("8080", uc.port);
  17635. }
  17636. {
  17637. // Zone ID '%25' is not in [a-fA-F0-9:]
  17638. detail::UrlComponents uc;
  17639. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17640. }
  17641. }
  17642. TEST(ParseUrlTest, SchemeEdgeCases) {
  17643. {
  17644. detail::UrlComponents uc;
  17645. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17646. }
  17647. {
  17648. detail::UrlComponents uc;
  17649. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17650. }
  17651. {
  17652. detail::UrlComponents uc;
  17653. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17654. }
  17655. }
  17656. TEST(ParseUrlTest, PortEdgeCases) {
  17657. {
  17658. detail::UrlComponents uc;
  17659. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17660. EXPECT_TRUE(uc.port.empty());
  17661. EXPECT_EQ("/path", uc.path);
  17662. }
  17663. {
  17664. // parse_url accepts any port string; validation is done by parse_port
  17665. detail::UrlComponents uc;
  17666. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17667. EXPECT_EQ("abc", uc.port);
  17668. }
  17669. }
  17670. TEST(ParseUrlTest, WebSocketPatterns) {
  17671. {
  17672. detail::UrlComponents uc;
  17673. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17674. EXPECT_EQ("ws", uc.scheme);
  17675. EXPECT_EQ("echo.example.com", uc.host);
  17676. EXPECT_EQ("8080", uc.port);
  17677. EXPECT_EQ("/ws", uc.path);
  17678. }
  17679. {
  17680. detail::UrlComponents uc;
  17681. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17682. EXPECT_EQ("wss", uc.scheme);
  17683. EXPECT_EQ("echo.example.com", uc.host);
  17684. EXPECT_TRUE(uc.port.empty());
  17685. EXPECT_EQ("/ws", uc.path);
  17686. }
  17687. }
  17688. TEST(ParseUrlTest, QueryOnly) {
  17689. detail::UrlComponents uc;
  17690. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17691. EXPECT_TRUE(uc.host.empty());
  17692. EXPECT_TRUE(uc.path.empty());
  17693. EXPECT_EQ("?q=1&r=2", uc.query);
  17694. }
  17695. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17696. detail::UrlComponents uc;
  17697. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17698. EXPECT_TRUE(uc.scheme.empty());
  17699. EXPECT_EQ("example.com", uc.host);
  17700. EXPECT_EQ("443", uc.port);
  17701. EXPECT_EQ("/path", uc.path);
  17702. }
  17703. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17704. // If ipv6 regex working, regex match codepath is taken.
  17705. // else port will default to 80 in Client impl
  17706. int clientImplMagicPort = 80;
  17707. int port = 4321;
  17708. // above ports must be different to avoid false negative
  17709. EXPECT_NE(clientImplMagicPort, port);
  17710. std::string ipV6TestURL = "http://[ff06::c3]";
  17711. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17712. CLIENT_PRIVATE_KEY_FILE);
  17713. EXPECT_EQ(cli.port(), port);
  17714. }
  17715. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17716. auto file_path = "./www/dir/index.html";
  17717. auto dir_path = "./www/dir";
  17718. detail::FileStat stat_file(file_path);
  17719. EXPECT_TRUE(stat_file.is_file());
  17720. EXPECT_FALSE(stat_file.is_dir());
  17721. detail::FileStat stat_dir(dir_path);
  17722. EXPECT_FALSE(stat_dir.is_file());
  17723. EXPECT_TRUE(stat_dir.is_dir());
  17724. }
  17725. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17726. // IPv4 with default HTTP port (80)
  17727. EXPECT_EQ("example.com",
  17728. detail::make_host_and_port_string("example.com", 80, false));
  17729. // IPv4 with default HTTPS port (443)
  17730. EXPECT_EQ("example.com",
  17731. detail::make_host_and_port_string("example.com", 443, true));
  17732. // IPv4 with non-default HTTP port
  17733. EXPECT_EQ("example.com:8080",
  17734. detail::make_host_and_port_string("example.com", 8080, false));
  17735. // IPv4 with non-default HTTPS port
  17736. EXPECT_EQ("example.com:8443",
  17737. detail::make_host_and_port_string("example.com", 8443, true));
  17738. // IPv6 with default HTTP port (80)
  17739. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17740. // IPv6 with default HTTPS port (443)
  17741. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17742. // IPv6 with non-default HTTP port
  17743. EXPECT_EQ("[::1]:8080",
  17744. detail::make_host_and_port_string("::1", 8080, false));
  17745. // IPv6 with non-default HTTPS port
  17746. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17747. // IPv6 full address with default port
  17748. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17749. detail::make_host_and_port_string(
  17750. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17751. // IPv6 full address with non-default port
  17752. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17753. detail::make_host_and_port_string(
  17754. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17755. // IPv6 localhost with non-default port
  17756. EXPECT_EQ("[::1]:3000",
  17757. detail::make_host_and_port_string("::1", 3000, false));
  17758. // IPv6 with zone ID (link-local address) with default port
  17759. EXPECT_EQ("[fe80::1%eth0]",
  17760. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17761. // IPv6 with zone ID (link-local address) with non-default port
  17762. EXPECT_EQ("[fe80::1%eth0]:8080",
  17763. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17764. // Edge case: Port 443 with is_ssl=false (should add port)
  17765. EXPECT_EQ("example.com:443",
  17766. detail::make_host_and_port_string("example.com", 443, false));
  17767. // Edge case: Port 80 with is_ssl=true (should add port)
  17768. EXPECT_EQ("example.com:80",
  17769. detail::make_host_and_port_string("example.com", 80, true));
  17770. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17771. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17772. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17773. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17774. // Security fix: Already bracketed IPv6 should not get double brackets
  17775. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17776. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17777. EXPECT_EQ("[::1]:8080",
  17778. detail::make_host_and_port_string("[::1]", 8080, false));
  17779. EXPECT_EQ("[2001:db8::1]:8080",
  17780. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17781. EXPECT_EQ("[fe80::1%eth0]",
  17782. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17783. EXPECT_EQ("[fe80::1%eth0]:8080",
  17784. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17785. // Edge case: Empty host (should return as-is)
  17786. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17787. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17788. // This is a known limitation but shouldn't crash
  17789. EXPECT_EQ("[host:name]",
  17790. detail::make_host_and_port_string("host:name", 80, false));
  17791. // Port number edge cases (no validation, but should not crash)
  17792. EXPECT_EQ("example.com:0",
  17793. detail::make_host_and_port_string("example.com", 0, false));
  17794. EXPECT_EQ("example.com:-1",
  17795. detail::make_host_and_port_string("example.com", -1, false));
  17796. EXPECT_EQ("example.com:65535",
  17797. detail::make_host_and_port_string("example.com", 65535, false));
  17798. EXPECT_EQ("example.com:65536",
  17799. detail::make_host_and_port_string("example.com", 65536, false));
  17800. }
  17801. #ifdef CPPHTTPLIB_SSL_ENABLED
  17802. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17803. httplib::SSLClient cli("roblox.com", 443);
  17804. cli.set_follow_location(true);
  17805. auto res = cli.Get("/");
  17806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17807. EXPECT_EQ(StatusCode::OK_200, res->status);
  17808. }
  17809. #endif
  17810. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17811. Server svr;
  17812. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17813. EXPECT_EQ(res.status, 400);
  17814. });
  17815. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17816. auto se = detail::scope_exit([&] {
  17817. svr.stop();
  17818. thread.join();
  17819. ASSERT_FALSE(svr.is_running());
  17820. });
  17821. svr.wait_until_ready();
  17822. Client cli(HOST, PORT);
  17823. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17824. }
  17825. TEST(InvalidHeaderCharsTest, is_field_name) {
  17826. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17827. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17828. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17829. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17830. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17831. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17832. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17833. EXPECT_FALSE(detail::fields::is_field_name(""));
  17834. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17835. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17836. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17837. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17838. }
  17839. TEST(InvalidHeaderCharsTest, is_field_value) {
  17840. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17841. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17842. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17843. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17844. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17845. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17846. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17847. EXPECT_TRUE(detail::fields::is_field_value(""));
  17848. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17849. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17850. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17851. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17852. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17853. }
  17854. TEST(InvalidHeaderCharsTest, OnServer) {
  17855. Server svr;
  17856. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17857. std::string header = "Not Set";
  17858. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17859. res.set_header(header, "value");
  17860. res.set_content("Page Content Page Content", "text/plain");
  17861. });
  17862. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17863. std::string header = "Not Set";
  17864. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17865. res.set_header("X-Test", header);
  17866. res.set_content("Page Content Page Content", "text/plain");
  17867. });
  17868. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17869. auto se = detail::scope_exit([&] {
  17870. svr.stop();
  17871. thread.join();
  17872. ASSERT_FALSE(svr.is_running());
  17873. });
  17874. svr.wait_until_ready();
  17875. Client cli(HOST, PORT);
  17876. {
  17877. auto res = cli.Get(
  17878. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17880. EXPECT_EQ("Page Content Page Content", res->body);
  17881. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17882. }
  17883. {
  17884. auto res = cli.Get(
  17885. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17887. EXPECT_EQ("Page Content Page Content", res->body);
  17888. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17889. }
  17890. }
  17891. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17892. auto handled = false;
  17893. Server svr;
  17894. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17895. thread t = thread([&] { svr.listen(HOST, PORT); });
  17896. auto se = detail::scope_exit([&] {
  17897. svr.stop();
  17898. t.join();
  17899. ASSERT_FALSE(svr.is_running());
  17900. ASSERT_FALSE(handled);
  17901. });
  17902. svr.wait_until_ready();
  17903. auto req = "POST /test HTTP/1.1\r\n"
  17904. "Content-Length: x\r\n"
  17905. "\r\n";
  17906. std::string response;
  17907. ASSERT_TRUE(send_request(1, req, &response));
  17908. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17909. response.substr(0, response.find("\r\n")));
  17910. }
  17911. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17912. // case-insensitive, and a server that receives a 100-continue expectation in
  17913. // an HTTP/1.0 request MUST ignore it.
  17914. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17915. std::string response;
  17916. ASSERT_TRUE(send_request(1, req, &response, port));
  17917. *got_100 = response.find("100 Continue") != std::string::npos;
  17918. }
  17919. class ExpectTokenTest : public ::testing::Test {
  17920. protected:
  17921. void SetUp() override {
  17922. svr_.Post("/p", [](const Request &, Response &res) {
  17923. res.set_content("ok", "text/plain");
  17924. });
  17925. port_ = svr_.bind_to_any_port(HOST);
  17926. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17927. svr_.wait_until_ready();
  17928. }
  17929. void TearDown() override {
  17930. svr_.stop();
  17931. if (thread_.joinable()) { thread_.join(); }
  17932. }
  17933. std::string request(const char *version, const char *expect_value) const {
  17934. return std::string("POST /p ") + version +
  17935. "\r\n"
  17936. "Host: localhost\r\n"
  17937. "Content-Length: 2\r\n"
  17938. "Connection: close\r\n"
  17939. "Expect: " +
  17940. expect_value +
  17941. "\r\n"
  17942. "\r\n"
  17943. "hi";
  17944. }
  17945. Server svr_;
  17946. int port_ = 0;
  17947. thread thread_;
  17948. };
  17949. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17950. bool got_100 = false;
  17951. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17952. EXPECT_TRUE(got_100);
  17953. }
  17954. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17955. bool got_100 = true;
  17956. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17957. EXPECT_FALSE(got_100);
  17958. }
  17959. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17960. bool got_100 = false;
  17961. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17962. EXPECT_TRUE(got_100);
  17963. }
  17964. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17965. bool got_100 = false;
  17966. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17967. EXPECT_TRUE(got_100);
  17968. }
  17969. // `100 Continue` is sent only when the server starts reading the body, so a
  17970. // request rejected before that never invites the client to send it. The
  17971. // requests below carry the expectation but withhold the body, as a client
  17972. // waiting for `100 Continue` would.
  17973. // A POST that expects `100 Continue` and withholds its two-byte body.
  17974. static std::string expect_headers_only(const std::string &path) {
  17975. return "POST " + path +
  17976. " HTTP/1.1\r\n"
  17977. "Host: localhost\r\n"
  17978. "Content-Length: 2\r\n"
  17979. "Expect: 100-continue\r\n"
  17980. "\r\n";
  17981. }
  17982. class ExpectLazyContinueTest : public ::testing::Test {
  17983. protected:
  17984. void SetUp() override {
  17985. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17986. if (req.path == "/pre-routing") {
  17987. res.status = StatusCode::Unauthorized_401;
  17988. return Server::HandlerResponse::Handled;
  17989. }
  17990. return Server::HandlerResponse::Unhandled;
  17991. });
  17992. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17993. if (req.matched_route == "/pre-request") {
  17994. res.status = StatusCode::Forbidden_403;
  17995. return Server::HandlerResponse::Handled;
  17996. }
  17997. return Server::HandlerResponse::Unhandled;
  17998. });
  17999. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18000. res.set_content("ok", "text/plain");
  18001. });
  18002. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18003. res.set_content("ok", "text/plain");
  18004. });
  18005. svr_.Post("/reader-used", [](const Request &, Response &res,
  18006. const ContentReader &content_reader) {
  18007. std::string body;
  18008. content_reader([&](const char *data, size_t len) {
  18009. body.append(data, len);
  18010. return true;
  18011. });
  18012. res.set_content(body, "text/plain");
  18013. });
  18014. svr_.Post("/reader-unused",
  18015. [](const Request &, Response &res, const ContentReader &) {
  18016. res.set_content("ignored", "text/plain");
  18017. });
  18018. port_ = svr_.bind_to_any_port(HOST);
  18019. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18020. svr_.wait_until_ready();
  18021. }
  18022. void TearDown() override {
  18023. svr_.stop();
  18024. if (thread_.joinable()) { thread_.join(); }
  18025. }
  18026. // Sends `req` and reads until the server closes the connection. Returns
  18027. // false if the read had to wait for the client-side timeout instead.
  18028. bool send_until_closed(const std::string &req, std::string *resp) const {
  18029. auto start = std::chrono::steady_clock::now();
  18030. if (!send_request(3, req, resp, port_)) { return false; }
  18031. auto elapsed = std::chrono::steady_clock::now() - start;
  18032. return elapsed < std::chrono::seconds(2);
  18033. }
  18034. // The final response comes without `100 Continue`, and the server closes
  18035. // the connection since the body may or may not follow.
  18036. void expect_final_without_interim(const std::string &path,
  18037. const char *status_line) const {
  18038. std::string resp;
  18039. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18040. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18041. EXPECT_EQ(0u, resp.find(status_line));
  18042. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18043. }
  18044. Server svr_;
  18045. int port_ = 0;
  18046. thread thread_;
  18047. };
  18048. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18049. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18050. }
  18051. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18052. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18053. }
  18054. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18055. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18056. }
  18057. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18058. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18059. }
  18060. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18061. // The body follows once `100 Continue` has had time to arrive.
  18062. auto req = expect_headers_only("/reader-used");
  18063. req.insert(req.size() - 2, "Connection: close\r\n");
  18064. std::string resp;
  18065. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18066. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18067. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18068. EXPECT_NE(std::string::npos, resp.find("hi"));
  18069. }
  18070. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18071. // Large enough for the client to add `Expect: 100-continue` itself.
  18072. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18073. std::atomic<bool> body_sent{false};
  18074. Client cli(HOST, port_);
  18075. auto res = cli.Post(
  18076. "/pre-request", length,
  18077. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18078. body_sent = true;
  18079. std::string chunk(len, 'x');
  18080. sink.write(chunk.data(), chunk.size());
  18081. return true;
  18082. },
  18083. "application/octet-stream");
  18084. ASSERT_TRUE(res);
  18085. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18086. EXPECT_FALSE(body_sent);
  18087. }
  18088. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18089. Server svr;
  18090. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18091. return StatusCode::ExpectationFailed_417;
  18092. });
  18093. svr.Post("/p", [](const Request &, Response &res) {
  18094. res.set_content("ok", "text/plain");
  18095. });
  18096. auto port = svr.bind_to_any_port(HOST);
  18097. thread t = thread([&] { svr.listen_after_bind(); });
  18098. auto se = detail::scope_exit([&] {
  18099. svr.stop();
  18100. t.join();
  18101. });
  18102. svr.wait_until_ready();
  18103. std::string resp;
  18104. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18105. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18106. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18107. // Exactly one response: the route handler must not run after the 417.
  18108. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18109. }
  18110. #ifndef _WIN32
  18111. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18112. static constexpr char reject[] = "Unauthorized";
  18113. static constexpr char accept[] = "Upload accepted";
  18114. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18115. Server svr;
  18116. svr.set_expect_100_continue_handler(
  18117. [](const Request & /*req*/, Response &res) {
  18118. res.status = StatusCode::Unauthorized_401;
  18119. res.set_content(reject, "text/plain");
  18120. return res.status;
  18121. });
  18122. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18123. res.set_content(accept, "text/plain");
  18124. });
  18125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18126. auto se = detail::scope_exit([&] {
  18127. svr.stop();
  18128. thread.join();
  18129. ASSERT_FALSE(svr.is_running());
  18130. });
  18131. svr.wait_until_ready();
  18132. {
  18133. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18134. curl_easy_init(), &curl_easy_cleanup};
  18135. ASSERT_NE(curl, nullptr);
  18136. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18137. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18138. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18139. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18140. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18141. &curl_slist_free_all};
  18142. ASSERT_NE(list, nullptr);
  18143. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18144. struct read_data {
  18145. uint64_t read_size;
  18146. uint64_t total_size;
  18147. } data = {0, total_size};
  18148. using read_callback_t =
  18149. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18150. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18151. void *userdata) -> size_t {
  18152. read_data *d = (read_data *)userdata;
  18153. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18154. std::fill_n(ptr, size * nmemb, 'A');
  18155. d->read_size += size * nmemb;
  18156. return size * nmemb;
  18157. };
  18158. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18159. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18160. std::vector<char> buffer;
  18161. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18162. using write_callback_t =
  18163. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18164. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18165. void *userdata) -> size_t {
  18166. std::vector<char> *buf = (std::vector<char> *)userdata;
  18167. buf->reserve(buf->size() + size * nmemb + 1);
  18168. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18169. return size * nmemb;
  18170. };
  18171. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18172. {
  18173. const auto res = curl_easy_perform(curl.get());
  18174. ASSERT_EQ(res, CURLE_OK);
  18175. }
  18176. {
  18177. auto response_code = long{};
  18178. const auto res =
  18179. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18180. ASSERT_EQ(res, CURLE_OK);
  18181. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18182. }
  18183. {
  18184. auto dl = curl_off_t{};
  18185. const auto res =
  18186. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18187. ASSERT_EQ(res, CURLE_OK);
  18188. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18189. }
  18190. {
  18191. buffer.push_back('\0');
  18192. ASSERT_STRCASEEQ(buffer.data(), reject);
  18193. }
  18194. }
  18195. }
  18196. #endif
  18197. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18198. // Regression test for #2458.
  18199. //
  18200. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18201. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18202. // ticket can make the client socket spuriously readable during the
  18203. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18204. // the client withholds the body and then blocks reading a response that never
  18205. // comes, failing with `Failed to read connection`.
  18206. //
  18207. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18208. // within the timeout. This raw OpenSSL server deliberately never sends
  18209. // `100 Continue`; the client must still deliver the body and receive 200.
  18210. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18211. signal(SIGPIPE, SIG_IGN);
  18212. const auto port = PORT + 4;
  18213. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18214. ASSERT_NE(srv, INVALID_SOCKET);
  18215. int opt = 1;
  18216. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18217. sockaddr_in addr{};
  18218. addr.sin_family = AF_INET;
  18219. addr.sin_port = htons(static_cast<uint16_t>(port));
  18220. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18221. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18222. ASSERT_EQ(0, ::listen(srv, 1));
  18223. std::atomic<size_t> server_body_bytes{0};
  18224. auto server_thread = std::thread([&] {
  18225. sockaddr_in cli_addr{};
  18226. socklen_t cli_len = sizeof(cli_addr);
  18227. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18228. if (cli == INVALID_SOCKET) { return; }
  18229. // Bound the lifetime of the server side so a buggy client (which never
  18230. // sends the body) cannot make this thread block forever on join.
  18231. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18232. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18233. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18234. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18235. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18236. SSL *ssl = SSL_new(ctx);
  18237. SSL_set_fd(ssl, static_cast<int>(cli));
  18238. if (SSL_accept(ssl) > 0) {
  18239. // Read the request headers. Reading here also flushes the TLS 1.3
  18240. // session tickets to the client. Deliberately do NOT send
  18241. // `100 Continue`.
  18242. std::string buf;
  18243. char tmp[1024];
  18244. while (buf.find("\r\n\r\n") == std::string::npos) {
  18245. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18246. if (n <= 0) { break; }
  18247. buf.append(tmp, static_cast<size_t>(n));
  18248. }
  18249. // A correct client sends the body now; count what arrives.
  18250. auto pos = buf.find("\r\n\r\n");
  18251. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18252. while (body < 4096) {
  18253. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18254. if (n <= 0) { break; }
  18255. body += static_cast<size_t>(n);
  18256. }
  18257. server_body_bytes = body;
  18258. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18259. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18260. SSL_shutdown(ssl);
  18261. }
  18262. SSL_free(ssl);
  18263. detail::close_socket(cli);
  18264. SSL_CTX_free(ctx);
  18265. });
  18266. auto se = detail::scope_exit([&] {
  18267. server_thread.join();
  18268. detail::close_socket(srv);
  18269. });
  18270. SSLClient cli("127.0.0.1", port);
  18271. cli.enable_server_certificate_verification(false);
  18272. cli.set_connection_timeout(5, 0);
  18273. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18274. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18275. std::string body(4096, 'A');
  18276. auto res = cli.Put("/api/test", body, "application/json");
  18277. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18278. EXPECT_EQ(StatusCode::OK_200, res->status);
  18279. EXPECT_EQ(body.size(), server_body_bytes.load());
  18280. }
  18281. #endif
  18282. template <typename S, typename C>
  18283. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18284. svr.Get("/stream", [&](const Request &, Response &res) {
  18285. auto data = new std::string("01234567890123456789");
  18286. res.set_content_provider(
  18287. data->size(), "text/plain",
  18288. [&, data](size_t offset, size_t length, DataSink &sink) {
  18289. const size_t DATA_CHUNK_SIZE = 4;
  18290. const auto &d = *data;
  18291. std::this_thread::sleep_for(std::chrono::seconds(1));
  18292. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18293. return true;
  18294. },
  18295. [data](bool success) {
  18296. EXPECT_FALSE(success);
  18297. delete data;
  18298. });
  18299. });
  18300. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18301. auto i = new size_t(0);
  18302. res.set_content_provider(
  18303. "text/plain",
  18304. [i](size_t, DataSink &sink) {
  18305. if (*i < 5) {
  18306. std::this_thread::sleep_for(std::chrono::seconds(1));
  18307. sink.write("abcd", 4);
  18308. (*i)++;
  18309. } else {
  18310. sink.done();
  18311. }
  18312. return true;
  18313. },
  18314. [i](bool success) {
  18315. EXPECT_FALSE(success);
  18316. delete i;
  18317. });
  18318. });
  18319. svr.Get("/chunked", [&](const Request &, Response &res) {
  18320. auto i = new size_t(0);
  18321. res.set_chunked_content_provider(
  18322. "text/plain",
  18323. [i](size_t, DataSink &sink) {
  18324. if (*i < 5) {
  18325. std::this_thread::sleep_for(std::chrono::seconds(1));
  18326. sink.os << "abcd";
  18327. (*i)++;
  18328. } else {
  18329. sink.done();
  18330. }
  18331. return true;
  18332. },
  18333. [i](bool success) {
  18334. EXPECT_FALSE(success);
  18335. delete i;
  18336. });
  18337. });
  18338. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18339. auto se = detail::scope_exit([&] {
  18340. svr.stop();
  18341. listen_thread.join();
  18342. ASSERT_FALSE(svr.is_running());
  18343. });
  18344. svr.wait_until_ready();
  18345. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18346. {
  18347. auto start = std::chrono::steady_clock::now();
  18348. auto res = cli.Get("/stream");
  18349. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18350. std::chrono::steady_clock::now() - start)
  18351. .count();
  18352. ASSERT_FALSE(res);
  18353. EXPECT_EQ(Error::Read, res.error());
  18354. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18355. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18356. }
  18357. {
  18358. auto start = std::chrono::steady_clock::now();
  18359. auto res = cli.Get("/stream_without_length");
  18360. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18361. std::chrono::steady_clock::now() - start)
  18362. .count();
  18363. ASSERT_FALSE(res);
  18364. EXPECT_EQ(Error::Read, res.error());
  18365. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18366. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18367. }
  18368. {
  18369. auto start = std::chrono::steady_clock::now();
  18370. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18371. EXPECT_EQ("abcd", string(data, data_length));
  18372. return true;
  18373. });
  18374. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18375. std::chrono::steady_clock::now() - start)
  18376. .count();
  18377. ASSERT_FALSE(res);
  18378. EXPECT_EQ(Error::Read, res.error());
  18379. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18380. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18381. }
  18382. }
  18383. TEST(MaxTimeoutTest, ContentStream) {
  18384. time_t timeout = 2000;
  18385. time_t threshold = 200;
  18386. Server svr;
  18387. Client cli("localhost", PORT);
  18388. max_timeout_test(svr, cli, timeout, threshold);
  18389. }
  18390. #ifdef CPPHTTPLIB_SSL_ENABLED
  18391. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18392. time_t timeout = 2000;
  18393. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18395. SSLClient cli("localhost", PORT);
  18396. cli.enable_server_certificate_verification(false);
  18397. max_timeout_test(svr, cli, timeout, threshold);
  18398. }
  18399. #endif
  18400. class EventDispatcher {
  18401. public:
  18402. EventDispatcher() {}
  18403. bool wait_event(DataSink *sink) {
  18404. unique_lock<mutex> lk(m_);
  18405. int id = id_;
  18406. // Wait with timeout to prevent hanging if client disconnects
  18407. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18408. [&] { return cid_ == id; })) {
  18409. return false; // Timeout occurred
  18410. }
  18411. sink->write(message_.data(), message_.size());
  18412. return true;
  18413. }
  18414. void send_event(const string &message) {
  18415. lock_guard<mutex> lk(m_);
  18416. cid_ = id_++;
  18417. message_ = message;
  18418. cv_.notify_all();
  18419. }
  18420. private:
  18421. mutex m_;
  18422. condition_variable cv_;
  18423. atomic_int id_{0};
  18424. atomic_int cid_{-1};
  18425. string message_;
  18426. };
  18427. TEST(ClientInThreadTest, Issue2068) {
  18428. EventDispatcher ed;
  18429. Server svr;
  18430. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18431. res.set_chunked_content_provider("text/event-stream",
  18432. [&](size_t /*offset*/, DataSink &sink) {
  18433. return ed.wait_event(&sink);
  18434. });
  18435. });
  18436. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18437. svr.wait_until_ready();
  18438. thread event_thread([&] {
  18439. int id = 0;
  18440. while (svr.is_running()) {
  18441. this_thread::sleep_for(chrono::milliseconds(500));
  18442. std::stringstream ss;
  18443. ss << "data: " << id << "\n\n";
  18444. ed.send_event(ss.str());
  18445. id++;
  18446. }
  18447. });
  18448. auto se = detail::scope_exit([&] {
  18449. svr.stop();
  18450. listen_thread.join();
  18451. event_thread.join();
  18452. ASSERT_FALSE(svr.is_running());
  18453. });
  18454. {
  18455. auto client = detail::make_unique<Client>(HOST, PORT);
  18456. client->set_read_timeout(std::chrono::minutes(10));
  18457. std::atomic<bool> stop{false};
  18458. std::thread t([&] {
  18459. client->Get("/event1",
  18460. [&](const char *, size_t) -> bool { return !stop; });
  18461. });
  18462. std::this_thread::sleep_for(std::chrono::seconds(2));
  18463. stop = true;
  18464. client->stop();
  18465. t.join();
  18466. // Reset client after thread has finished
  18467. client.reset();
  18468. }
  18469. }
  18470. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18471. auto handled = false;
  18472. Server svr;
  18473. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18474. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18475. auto se = detail::scope_exit([&] {
  18476. svr.stop();
  18477. t.join();
  18478. ASSERT_FALSE(svr.is_running());
  18479. ASSERT_FALSE(handled);
  18480. });
  18481. svr.wait_until_ready();
  18482. // Two Content-Length headers with different values — must be rejected
  18483. auto req = "POST /test HTTP/1.1\r\n"
  18484. "Content-Length: 5\r\n"
  18485. "Content-Length: 10\r\n"
  18486. "\r\n"
  18487. "hello";
  18488. std::string response;
  18489. ASSERT_TRUE(send_request(1, req, &response));
  18490. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18491. response.substr(0, response.find("\r\n")));
  18492. }
  18493. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18494. auto handled = false;
  18495. Server svr;
  18496. svr.Post("/test", [&](const Request &, Response &res) {
  18497. handled = true;
  18498. res.set_content("ok", "text/plain");
  18499. });
  18500. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18501. auto se = detail::scope_exit([&] {
  18502. svr.stop();
  18503. t.join();
  18504. ASSERT_FALSE(svr.is_running());
  18505. ASSERT_TRUE(handled);
  18506. });
  18507. svr.wait_until_ready();
  18508. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18509. auto req = "POST /test HTTP/1.1\r\n"
  18510. "Host: localhost\r\n"
  18511. "Content-Length: 5\r\n"
  18512. "Content-Length: 5\r\n"
  18513. "\r\n"
  18514. "hello";
  18515. std::string response;
  18516. ASSERT_TRUE(send_request(1, req, &response));
  18517. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18518. }
  18519. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18520. Server svr;
  18521. svr.Get("/test", [](const Request &, Response &res) {
  18522. res.set_content("ok", "text/plain");
  18523. });
  18524. auto port = svr.bind_to_any_port(HOST);
  18525. thread t = thread([&] { svr.listen_after_bind(); });
  18526. auto se = detail::scope_exit([&] {
  18527. svr.stop();
  18528. t.join();
  18529. ASSERT_FALSE(svr.is_running());
  18530. });
  18531. svr.wait_until_ready();
  18532. auto status_line = [&](const std::string &host_lines) {
  18533. std::string res;
  18534. send_request(
  18535. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18536. &res, port);
  18537. return res.substr(0, res.find("\r\n"));
  18538. };
  18539. const char *accepted[] = {
  18540. "Host: localhost\r\n",
  18541. "Host: a.example:8080\r\n",
  18542. "Host: my_service\r\n",
  18543. "Host: [::1]:8080\r\n",
  18544. "Host: [fe80::1%25eth0]\r\n",
  18545. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18546. };
  18547. for (auto host_lines : accepted) {
  18548. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18549. }
  18550. const char *rejected[] = {
  18551. "Host: a.example\r\nHost: b.example\r\n",
  18552. "Host: a.example\r\nHost: a.example\r\n",
  18553. "Host: a@b.example\r\n",
  18554. "Host: a.example/b\r\n",
  18555. "Host: a.example\\b\r\n",
  18556. "Host: a.example?b\r\n",
  18557. "Host: a.example#b\r\n",
  18558. "Host: a.example b.example\r\n",
  18559. };
  18560. for (auto host_lines : rejected) {
  18561. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18562. << host_lines;
  18563. }
  18564. }
  18565. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18566. Server svr;
  18567. svr.Get("/", [](const Request &req, Response &res) {
  18568. EXPECT_EQ(2U, req.trailers.size());
  18569. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18570. // Denied
  18571. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18572. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18573. // Accepted
  18574. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18575. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18576. EXPECT_TRUE(req.has_trailer("X-World"));
  18577. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18578. res.set_content("ok", "text/plain");
  18579. });
  18580. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18581. auto se = detail::scope_exit([&] {
  18582. svr.stop();
  18583. t.join();
  18584. ASSERT_FALSE(svr.is_running());
  18585. });
  18586. svr.wait_until_ready();
  18587. const std::string req = "GET / HTTP/1.1\r\n"
  18588. "Transfer-Encoding: chunked\r\n"
  18589. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18590. "\r\n"
  18591. "0\r\n"
  18592. "Content-Length: 10\r\n"
  18593. "Host: internal.local\r\n"
  18594. "Content-Type: malicious/content\r\n"
  18595. "Cookie: any\r\n"
  18596. "Set-Cookie: any\r\n"
  18597. "X-Forwarded-For: attacker.com\r\n"
  18598. "X-Real-Ip: 1.1.1.1\r\n"
  18599. "X-Hello: hello\r\n"
  18600. "X-World: world\r\n"
  18601. "\r\n";
  18602. std::string res;
  18603. ASSERT_TRUE(send_request(1, req, &res));
  18604. }
  18605. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18606. // several field lines, and the combined value is what has to be parsed. A
  18607. // Trailer field split across lines therefore declares every name it lists;
  18608. // reading only the first line silently drops the trailers the later lines
  18609. // declare. The prohibited-trailer filter still applies to every line.
  18610. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18611. Server svr;
  18612. size_t observed_trailer_count = 0;
  18613. std::string observed_hello;
  18614. std::string observed_world;
  18615. bool observed_content_length = true;
  18616. svr.Get("/", [&](const Request &req, Response &res) {
  18617. observed_trailer_count = req.trailers.size();
  18618. observed_hello = req.get_trailer_value("X-Hello");
  18619. observed_world = req.get_trailer_value("X-World");
  18620. observed_content_length = req.has_trailer("Content-Length");
  18621. res.set_content("ok", "text/plain");
  18622. });
  18623. auto port = svr.bind_to_any_port(HOST);
  18624. thread t = thread([&]() { svr.listen_after_bind(); });
  18625. auto se = detail::scope_exit([&] {
  18626. svr.stop();
  18627. t.join();
  18628. ASSERT_FALSE(svr.is_running());
  18629. });
  18630. svr.wait_until_ready();
  18631. const std::string req = "GET / HTTP/1.1\r\n"
  18632. "Host: localhost\r\n"
  18633. "Transfer-Encoding: chunked\r\n"
  18634. "Trailer: X-Hello\r\n"
  18635. "Trailer: X-World, Content-Length\r\n"
  18636. "\r\n"
  18637. "0\r\n"
  18638. "X-Hello: hello\r\n"
  18639. "X-World: world\r\n"
  18640. "Content-Length: 10\r\n"
  18641. "\r\n";
  18642. std::string res;
  18643. ASSERT_TRUE(send_request(1, req, &res, port));
  18644. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18645. // Accepted: both field lines contribute to the declared set
  18646. EXPECT_EQ(2U, observed_trailer_count);
  18647. EXPECT_EQ(observed_hello, "hello");
  18648. EXPECT_EQ(observed_world, "world");
  18649. // Denied: a prohibited name stays prohibited on a later field line
  18650. EXPECT_FALSE(observed_content_length);
  18651. }
  18652. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18653. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18654. // unbounded run of fields that are never declared, because the counter would
  18655. // only advance for declared fields.
  18656. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18657. Server svr;
  18658. bool handler_called = false;
  18659. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18660. handler_called = true;
  18661. res.set_content("ok", "text/plain");
  18662. });
  18663. auto port = svr.bind_to_any_port(HOST);
  18664. thread t = thread([&]() { svr.listen_after_bind(); });
  18665. auto se = detail::scope_exit([&] {
  18666. svr.stop();
  18667. t.join();
  18668. ASSERT_FALSE(svr.is_running());
  18669. });
  18670. svr.wait_until_ready();
  18671. // Declare nothing, then send far more undeclared trailer fields than the
  18672. // header-count limit. Parsing must stop and reject the request rather than
  18673. // read every line.
  18674. std::string req = "GET / HTTP/1.1\r\n"
  18675. "Transfer-Encoding: chunked\r\n"
  18676. "\r\n"
  18677. "0\r\n";
  18678. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18679. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18680. }
  18681. req += "\r\n";
  18682. std::string res;
  18683. ASSERT_TRUE(send_request(1, req, &res, port));
  18684. // The request is rejected before the handler runs.
  18685. EXPECT_FALSE(handler_called);
  18686. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18687. }
  18688. // The set of declared trailer names is capped so a peer cannot grow it without
  18689. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18690. // declared past the cap is not honored, even if the field is actually sent.
  18691. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18692. Server svr;
  18693. // One name inside the cap and one past it, so the test tracks the cap rather
  18694. // than a fixed count.
  18695. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18696. const std::string within_cap_name = "X-T-0";
  18697. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18698. bool observed_within_cap = false;
  18699. bool observed_past_cap = false;
  18700. svr.Get("/", [&](const Request &req, Response &res) {
  18701. observed_within_cap = req.has_trailer(within_cap_name);
  18702. observed_past_cap = req.has_trailer(past_cap_name);
  18703. res.set_content("ok", "text/plain");
  18704. });
  18705. auto port = svr.bind_to_any_port(HOST);
  18706. thread t = thread([&]() { svr.listen_after_bind(); });
  18707. auto se = detail::scope_exit([&] {
  18708. svr.stop();
  18709. t.join();
  18710. ASSERT_FALSE(svr.is_running());
  18711. });
  18712. svr.wait_until_ready();
  18713. // Declare more trailer names than the cap in a single Trailer field, then
  18714. // actually send the first (within the cap) and the last (past it).
  18715. std::string trailer_decl = "Trailer: ";
  18716. for (int i = 0; i < declared_count; i++) {
  18717. if (i != 0) { trailer_decl += ", "; }
  18718. trailer_decl += "X-T-" + std::to_string(i);
  18719. }
  18720. trailer_decl += "\r\n";
  18721. const std::string req = "GET / HTTP/1.1\r\n"
  18722. "Host: localhost\r\n"
  18723. "Transfer-Encoding: chunked\r\n" +
  18724. trailer_decl +
  18725. "\r\n"
  18726. "0\r\n" +
  18727. within_cap_name + ": a\r\n" + past_cap_name +
  18728. ": b\r\n"
  18729. "\r\n";
  18730. std::string res;
  18731. ASSERT_TRUE(send_request(1, req, &res, port));
  18732. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18733. // A name within the cap is honored; one declared past the cap is dropped.
  18734. EXPECT_TRUE(observed_within_cap);
  18735. EXPECT_FALSE(observed_past_cap);
  18736. }
  18737. // A direct client that is not listed in trusted_proxies must not be able to
  18738. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18739. // the peer address on the actual TCP connection determines whether the
  18740. // header is honored.
  18741. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18742. Server svr;
  18743. // Deliberately does NOT include the loopback address the test client
  18744. // actually connects from, so the direct connection is not a trusted proxy.
  18745. svr.set_trusted_proxies({"203.0.113.66"});
  18746. std::string observed_remote_addr;
  18747. svr.Get("/ip", [&](const Request &req, Response &res) {
  18748. observed_remote_addr = req.remote_addr;
  18749. res.set_content("ok", "text/plain");
  18750. });
  18751. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18752. auto se = detail::scope_exit([&] {
  18753. svr.stop();
  18754. t.join();
  18755. ASSERT_FALSE(svr.is_running());
  18756. });
  18757. svr.wait_until_ready();
  18758. Client cli(HOST, PORT);
  18759. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18761. EXPECT_EQ(StatusCode::OK_200, res->status);
  18762. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18763. // ignored entirely and the real connection-level address retained.
  18764. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18765. observed_remote_addr == "127.0.0.1");
  18766. }
  18767. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18768. Server svr;
  18769. std::string observed_remote_addr;
  18770. std::string observed_xff;
  18771. svr.Get("/ip", [&](const Request &req, Response &res) {
  18772. observed_remote_addr = req.remote_addr;
  18773. observed_xff = req.get_header_value("X-Forwarded-For");
  18774. res.set_content("ok", "text/plain");
  18775. });
  18776. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18777. auto se = detail::scope_exit([&] {
  18778. svr.stop();
  18779. t.join();
  18780. ASSERT_FALSE(svr.is_running());
  18781. });
  18782. svr.wait_until_ready();
  18783. Client cli(HOST, PORT);
  18784. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18786. EXPECT_EQ(StatusCode::OK_200, res->status);
  18787. EXPECT_EQ(observed_xff, "203.0.113.66");
  18788. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18789. observed_remote_addr == "127.0.0.1");
  18790. }
  18791. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18792. Server svr;
  18793. svr.set_trusted_proxies({"203.0.113.66"});
  18794. std::string observed_remote_addr;
  18795. std::string observed_xff;
  18796. svr.Get("/ip", [&](const Request &req, Response &res) {
  18797. observed_remote_addr = req.remote_addr;
  18798. observed_xff = req.get_header_value("X-Forwarded-For");
  18799. res.set_content("ok", "text/plain");
  18800. });
  18801. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18802. auto se = detail::scope_exit([&] {
  18803. svr.stop();
  18804. t.join();
  18805. ASSERT_FALSE(svr.is_running());
  18806. });
  18807. svr.wait_until_ready();
  18808. Client cli(HOST, PORT);
  18809. auto res = cli.Get("/ip");
  18810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18811. EXPECT_EQ(StatusCode::OK_200, res->status);
  18812. EXPECT_EQ(observed_xff, "");
  18813. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18814. observed_remote_addr == "127.0.0.1");
  18815. }
  18816. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  18817. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  18818. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  18819. Server svr;
  18820. svr.set_trusted_proxies({"127.0.0.1"});
  18821. svr.Get("/ip", [](const Request &req, Response &res) {
  18822. res.set_content(req.remote_addr, "text/plain");
  18823. });
  18824. auto port = svr.bind_to_any_port("::");
  18825. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  18826. thread t = thread([&] { svr.listen_after_bind(); });
  18827. auto se = detail::scope_exit([&] {
  18828. svr.stop();
  18829. t.join();
  18830. ASSERT_FALSE(svr.is_running());
  18831. });
  18832. svr.wait_until_ready();
  18833. Client cli("127.0.0.1", port);
  18834. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  18835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18836. EXPECT_EQ("198.51.100.23", res->body);
  18837. }
  18838. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  18839. Server svr;
  18840. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18841. svr.Get("/ip", [](const Request &req, Response &res) {
  18842. res.set_content(req.remote_addr, "text/plain");
  18843. });
  18844. auto port = svr.bind_to_any_port(HOST);
  18845. ASSERT_GT(port, 0);
  18846. thread t = thread([&] { svr.listen_after_bind(); });
  18847. auto se = detail::scope_exit([&] {
  18848. svr.stop();
  18849. t.join();
  18850. ASSERT_FALSE(svr.is_running());
  18851. });
  18852. svr.wait_until_ready();
  18853. Client cli(HOST, port);
  18854. auto res = cli.Get(
  18855. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  18856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18857. EXPECT_EQ("198.51.100.23", res->body);
  18858. }
  18859. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18860. Server svr;
  18861. // Include the loopback address the test client actually connects from, so
  18862. // the direct connection itself is recognized as the trusted proxy hop.
  18863. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18864. std::string observed_remote_addr;
  18865. std::string observed_xff;
  18866. svr.Get("/ip", [&](const Request &req, Response &res) {
  18867. observed_remote_addr = req.remote_addr;
  18868. observed_xff = req.get_header_value("X-Forwarded-For");
  18869. res.set_content("ok", "text/plain");
  18870. });
  18871. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18872. auto se = detail::scope_exit([&] {
  18873. svr.stop();
  18874. t.join();
  18875. ASSERT_FALSE(svr.is_running());
  18876. });
  18877. svr.wait_until_ready();
  18878. Client cli(HOST, PORT);
  18879. auto res = cli.Get(
  18880. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18882. EXPECT_EQ(StatusCode::OK_200, res->status);
  18883. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18884. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18885. }
  18886. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18887. Server svr;
  18888. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18889. std::string observed_remote_addr;
  18890. std::string observed_xff;
  18891. svr.Get("/ip", [&](const Request &req, Response &res) {
  18892. observed_remote_addr = req.remote_addr;
  18893. observed_xff = req.get_header_value("X-Forwarded-For");
  18894. res.set_content("ok", "text/plain");
  18895. });
  18896. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18897. auto se = detail::scope_exit([&] {
  18898. svr.stop();
  18899. t.join();
  18900. ASSERT_FALSE(svr.is_running());
  18901. });
  18902. svr.wait_until_ready();
  18903. Client cli(HOST, PORT);
  18904. auto res = cli.Get(
  18905. "/ip",
  18906. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18908. EXPECT_EQ(StatusCode::OK_200, res->status);
  18909. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18910. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18911. }
  18912. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18913. Server svr;
  18914. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18915. std::string observed_remote_addr;
  18916. std::string observed_xff;
  18917. svr.Get("/ip", [&](const Request &req, Response &res) {
  18918. observed_remote_addr = req.remote_addr;
  18919. observed_xff = req.get_header_value("X-Forwarded-For");
  18920. res.set_content("ok", "text/plain");
  18921. });
  18922. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18923. auto se = detail::scope_exit([&] {
  18924. svr.stop();
  18925. t.join();
  18926. ASSERT_FALSE(svr.is_running());
  18927. });
  18928. svr.wait_until_ready();
  18929. Client cli(HOST, PORT);
  18930. auto res = cli.Get(
  18931. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18933. EXPECT_EQ(StatusCode::OK_200, res->status);
  18934. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18935. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18936. // and must not be selected.
  18937. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18938. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18939. }
  18940. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18941. Server svr;
  18942. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18943. std::string observed_remote_addr;
  18944. svr.Get("/ip", [&](const Request &req, Response &res) {
  18945. observed_remote_addr = req.remote_addr;
  18946. res.set_content("ok", "text/plain");
  18947. });
  18948. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18949. auto se = detail::scope_exit([&] {
  18950. svr.stop();
  18951. t.join();
  18952. ASSERT_FALSE(svr.is_running());
  18953. });
  18954. svr.wait_until_ready();
  18955. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18956. // a forged address and the trusted proxy's own address; the forged value must
  18957. // not win over the address the trusted proxy actually recorded.
  18958. Client cli(HOST, PORT);
  18959. auto res = cli.Get(
  18960. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18962. EXPECT_EQ(StatusCode::OK_200, res->status);
  18963. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18964. }
  18965. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18966. Server svr;
  18967. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18968. std::string observed_remote_addr;
  18969. std::string observed_xff;
  18970. svr.Get("/ip", [&](const Request &req, Response &res) {
  18971. observed_remote_addr = req.remote_addr;
  18972. observed_xff = req.get_header_value("X-Forwarded-For");
  18973. res.set_content("ok", "text/plain");
  18974. });
  18975. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18976. auto se = detail::scope_exit([&] {
  18977. svr.stop();
  18978. t.join();
  18979. ASSERT_FALSE(svr.is_running());
  18980. });
  18981. svr.wait_until_ready();
  18982. Client cli(HOST, PORT);
  18983. auto res = cli.Get(
  18984. "/ip",
  18985. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18987. EXPECT_EQ(StatusCode::OK_200, res->status);
  18988. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18989. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18990. }
  18991. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18992. Server svr;
  18993. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18994. std::string observed_remote_addr;
  18995. std::string observed_xff;
  18996. svr.Get("/ip", [&](const Request &req, Response &res) {
  18997. observed_remote_addr = req.remote_addr;
  18998. observed_xff = req.get_header_value("X-Forwarded-For");
  18999. res.set_content("ok", "text/plain");
  19000. });
  19001. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19002. auto se = detail::scope_exit([&] {
  19003. svr.stop();
  19004. t.join();
  19005. ASSERT_FALSE(svr.is_running());
  19006. });
  19007. svr.wait_until_ready();
  19008. std::string raw_req =
  19009. "GET /ip HTTP/1.1\r\n"
  19010. "Host: localhost\r\n"
  19011. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19012. "Connection: close\r\n"
  19013. "\r\n";
  19014. std::string out;
  19015. ASSERT_TRUE(send_request(5, raw_req, &out));
  19016. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19017. // Header parser trims surrounding whitespace of the header value
  19018. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19019. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19020. }
  19021. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19022. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19023. // their own X-Forwarded-For as a separate field line rather than extending the
  19024. // one the client sent, so every occurrence has to be taken into account.
  19025. // Reading only the first one hands back the address the client chose.
  19026. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19027. Server svr;
  19028. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19029. std::string observed_remote_addr;
  19030. size_t observed_xff_count = 0;
  19031. svr.Get("/ip", [&](const Request &req, Response &res) {
  19032. observed_remote_addr = req.remote_addr;
  19033. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19034. res.set_content("ok", "text/plain");
  19035. });
  19036. auto port = svr.bind_to_any_port(HOST);
  19037. thread t = thread([&]() { svr.listen_after_bind(); });
  19038. auto se = detail::scope_exit([&] {
  19039. svr.stop();
  19040. t.join();
  19041. ASSERT_FALSE(svr.is_running());
  19042. });
  19043. svr.wait_until_ready();
  19044. // The client supplies the first field line; the trusted proxy appends the
  19045. // address it observed as a second one.
  19046. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19047. "Host: localhost\r\n"
  19048. "X-Forwarded-For: 1.2.3.4\r\n"
  19049. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19050. "Connection: close\r\n"
  19051. "\r\n";
  19052. std::string out;
  19053. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19054. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19055. EXPECT_EQ(observed_xff_count, 2U);
  19056. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19057. // The same chain spread over one field line per hop derives the same client
  19058. // address, i.e. the split and the comma-joined representations agree.
  19059. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19060. "Host: localhost\r\n"
  19061. "X-Forwarded-For: 1.2.3.4\r\n"
  19062. "X-Forwarded-For: 198.51.100.23\r\n"
  19063. "X-Forwarded-For: 192.0.2.45\r\n"
  19064. "Connection: close\r\n"
  19065. "\r\n";
  19066. out.clear();
  19067. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19068. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19069. EXPECT_EQ(observed_xff_count, 3U);
  19070. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19071. }
  19072. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19073. // crash the server (it used to call front() on an empty vector inside
  19074. // get_client_ip). The connection-level remote address must be retained instead.
  19075. static void run_malformed_xff_test(const std::string &xff_value) {
  19076. Server svr;
  19077. svr.set_trusted_proxies({"192.0.2.45"});
  19078. std::string observed_remote_addr;
  19079. svr.Get("/ip", [&](const Request &req, Response &res) {
  19080. observed_remote_addr = req.remote_addr;
  19081. res.set_content("ok", "text/plain");
  19082. });
  19083. int port = 0;
  19084. thread t = thread([&]() {
  19085. port = svr.bind_to_any_port(HOST);
  19086. svr.listen_after_bind();
  19087. });
  19088. auto se = detail::scope_exit([&] {
  19089. svr.stop();
  19090. t.join();
  19091. ASSERT_FALSE(svr.is_running());
  19092. });
  19093. svr.wait_until_ready();
  19094. Client cli(HOST, port);
  19095. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19097. EXPECT_EQ(StatusCode::OK_200, res->status);
  19098. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19099. observed_remote_addr == "127.0.0.1");
  19100. }
  19101. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19102. run_malformed_xff_test("");
  19103. }
  19104. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19105. run_malformed_xff_test(",");
  19106. }
  19107. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19108. run_malformed_xff_test(", , ,");
  19109. }
  19110. // The same rule applies to Accept: a request whose acceptable types are spread
  19111. // over several field lines must be negotiated against all of them.
  19112. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19113. // case-insensitive connection options. Comparing the whole field value against
  19114. // one option misses a client that sends several of them, and misses every
  19115. // casing but the one written in the comparison.
  19116. //
  19117. // Sends req, reads the response, then reuses the same socket for a second
  19118. // request to find out whether the server kept the connection.
  19119. static void probe_connection_reuse(int port, const std::string &req,
  19120. bool *announced_close, bool *reusable) {
  19121. auto error = Error::Success;
  19122. auto sock = detail::create_client_socket(
  19123. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19124. /*connection_timeout_sec=*/5, 0,
  19125. /*read_timeout_sec=*/1, 0,
  19126. /*write_timeout_sec=*/5, 0, std::string(), error);
  19127. ASSERT_NE(sock, INVALID_SOCKET);
  19128. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19129. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19130. "Host: localhost\r\n"
  19131. "Connection: close\r\n"
  19132. "\r\n";
  19133. std::string first_response;
  19134. std::string second_response;
  19135. detail::process_client_socket(
  19136. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19137. [&](Stream &strm) {
  19138. if (strm.write(req.data(), req.size()) !=
  19139. static_cast<ssize_t>(req.size())) {
  19140. return false;
  19141. }
  19142. char buf[512];
  19143. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19144. // Headers plus the two-byte body of the handler below
  19145. while (reader.getline()) {
  19146. first_response += reader.ptr();
  19147. if (first_response.find("ok") != std::string::npos) { break; }
  19148. }
  19149. if (strm.write(second.data(), second.size()) !=
  19150. static_cast<ssize_t>(second.size())) {
  19151. return true;
  19152. }
  19153. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19154. while (reader2.getline()) {
  19155. second_response += reader2.ptr();
  19156. if (second_response.find("ok") != std::string::npos) { break; }
  19157. }
  19158. return true;
  19159. });
  19160. *announced_close =
  19161. first_response.find("Connection: close") != std::string::npos;
  19162. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19163. }
  19164. class ConnectionTokenTest : public ::testing::Test {
  19165. protected:
  19166. void SetUp() override {
  19167. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19168. res.set_content("ok", "text/plain");
  19169. });
  19170. port_ = svr_.bind_to_any_port(HOST);
  19171. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19172. svr_.wait_until_ready();
  19173. }
  19174. void TearDown() override {
  19175. svr_.stop();
  19176. if (thread_.joinable()) { thread_.join(); }
  19177. }
  19178. Server svr_;
  19179. int port_ = 0;
  19180. thread thread_;
  19181. };
  19182. // "close" alongside another option still closes the connection, and the
  19183. // response says so rather than leaving the peer to discover it.
  19184. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19185. bool announced_close = false;
  19186. bool reusable = true;
  19187. probe_connection_reuse(port_,
  19188. "GET /keepalive HTTP/1.1\r\n"
  19189. "Host: localhost\r\n"
  19190. "Connection: keep-alive, close\r\n"
  19191. "\r\n",
  19192. &announced_close, &reusable);
  19193. EXPECT_TRUE(announced_close);
  19194. EXPECT_FALSE(reusable);
  19195. }
  19196. // "close" split over two field lines is the same list, so it is honored too.
  19197. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19198. bool announced_close = false;
  19199. bool reusable = true;
  19200. probe_connection_reuse(port_,
  19201. "GET /keepalive HTTP/1.1\r\n"
  19202. "Host: localhost\r\n"
  19203. "Connection: keep-alive\r\n"
  19204. "Connection: close\r\n"
  19205. "\r\n",
  19206. &announced_close, &reusable);
  19207. EXPECT_TRUE(announced_close);
  19208. EXPECT_FALSE(reusable);
  19209. }
  19210. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19211. // keep-alive in the spelling everyone actually sends keeps its connection.
  19212. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19213. bool announced_close = false;
  19214. bool reusable = false;
  19215. probe_connection_reuse(port_,
  19216. "GET /keepalive HTTP/1.0\r\n"
  19217. "Host: localhost\r\n"
  19218. "Connection: keep-alive\r\n"
  19219. "\r\n",
  19220. &announced_close, &reusable);
  19221. EXPECT_FALSE(announced_close);
  19222. EXPECT_TRUE(reusable);
  19223. }
  19224. // A token the value merely contains is not the token itself.
  19225. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19226. bool announced_close = false;
  19227. bool reusable = false;
  19228. probe_connection_reuse(port_,
  19229. "GET /keepalive HTTP/1.1\r\n"
  19230. "Host: localhost\r\n"
  19231. "Connection: notclose\r\n"
  19232. "\r\n",
  19233. &announced_close, &reusable);
  19234. EXPECT_FALSE(announced_close);
  19235. EXPECT_TRUE(reusable);
  19236. }
  19237. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19238. Server svr;
  19239. std::vector<std::string> observed_types;
  19240. svr.Get("/", [&](const Request &req, Response &res) {
  19241. observed_types = req.accept_content_types;
  19242. res.set_content("ok", "text/plain");
  19243. });
  19244. auto port = svr.bind_to_any_port(HOST);
  19245. thread t = thread([&]() { svr.listen_after_bind(); });
  19246. auto se = detail::scope_exit([&] {
  19247. svr.stop();
  19248. t.join();
  19249. ASSERT_FALSE(svr.is_running());
  19250. });
  19251. svr.wait_until_ready();
  19252. Client cli(HOST, port);
  19253. Headers headers;
  19254. headers.emplace("Accept", "text/plain;q=0.5");
  19255. headers.emplace("Accept", "application/json");
  19256. auto res = cli.Get("/", headers);
  19257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19258. EXPECT_EQ(StatusCode::OK_200, res->status);
  19259. // Sorted by q-value, so the second field line's type comes first
  19260. ASSERT_EQ(2U, observed_types.size());
  19261. EXPECT_EQ("application/json", observed_types[0]);
  19262. EXPECT_EQ("text/plain", observed_types[1]);
  19263. }
  19264. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19265. // empty field line must not contribute a bare comma to the combined value.
  19266. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19267. Server svr;
  19268. std::vector<std::string> observed_types;
  19269. svr.Get("/", [&](const Request &req, Response &res) {
  19270. observed_types = req.accept_content_types;
  19271. res.set_content("ok", "text/plain");
  19272. });
  19273. auto port = svr.bind_to_any_port(HOST);
  19274. thread t = thread([&]() { svr.listen_after_bind(); });
  19275. auto se = detail::scope_exit([&] {
  19276. svr.stop();
  19277. t.join();
  19278. ASSERT_FALSE(svr.is_running());
  19279. });
  19280. svr.wait_until_ready();
  19281. // Empty first field line, then a real one
  19282. std::string raw_req = "GET / HTTP/1.1\r\n"
  19283. "Host: localhost\r\n"
  19284. "Accept:\r\n"
  19285. "Accept: application/json\r\n"
  19286. "Connection: close\r\n"
  19287. "\r\n";
  19288. std::string out;
  19289. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19290. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19291. ASSERT_EQ(1U, observed_types.size());
  19292. EXPECT_EQ("application/json", observed_types[0]);
  19293. }
  19294. // The skip in get_combined_header_value() is what keeps an empty field line
  19295. // from contributing a bare comma. Only a trailing empty field line exercises
  19296. // it: a leading one is already covered by the "combined is still empty" check,
  19297. // and parse_accept_header() now ignores the empty element either way, so the
  19298. // request-level test above can no longer tell the two apart.
  19299. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19300. Headers headers;
  19301. headers.emplace("Accept", "text/html");
  19302. headers.emplace("Accept", "");
  19303. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19304. headers.clear();
  19305. headers.emplace("Accept", "");
  19306. headers.emplace("Accept", "application/json");
  19307. EXPECT_EQ("application/json",
  19308. detail::get_combined_header_value(headers, "Accept"));
  19309. }
  19310. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19311. // An encoding offered on a later Accept-Encoding field line is still offered.
  19312. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19313. Server svr;
  19314. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19315. res.set_content(std::string(1024, 'x'), "text/plain");
  19316. });
  19317. auto port = svr.bind_to_any_port(HOST);
  19318. thread t = thread([&]() { svr.listen_after_bind(); });
  19319. auto se = detail::scope_exit([&] {
  19320. svr.stop();
  19321. t.join();
  19322. ASSERT_FALSE(svr.is_running());
  19323. });
  19324. svr.wait_until_ready();
  19325. Client cli(HOST, port);
  19326. cli.set_decompress(false);
  19327. Headers headers;
  19328. headers.emplace("Accept-Encoding", "identity");
  19329. headers.emplace("Accept-Encoding", "gzip");
  19330. auto res = cli.Get("/", headers);
  19331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19332. EXPECT_EQ(StatusCode::OK_200, res->status);
  19333. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19334. }
  19335. #endif
  19336. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19337. // Transfer-Encoding is not its body.
  19338. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19339. Server svr;
  19340. svr.set_payload_max_length(8);
  19341. svr.Post("/test", [](const Request &, Response &res) {
  19342. res.set_content("ok", "text/plain");
  19343. });
  19344. auto port = svr.bind_to_any_port(HOST);
  19345. ASSERT_GT(port, 0);
  19346. thread t = thread([&] { svr.listen_after_bind(); });
  19347. auto se = detail::scope_exit([&] {
  19348. svr.stop();
  19349. t.join();
  19350. ASSERT_FALSE(svr.is_running());
  19351. });
  19352. svr.wait_until_ready();
  19353. std::string resp;
  19354. ASSERT_TRUE(send_request(1,
  19355. "POST /test HTTP/1.1\r\n"
  19356. "Host: localhost\r\n"
  19357. "Connection: close\r\n"
  19358. "\r\n" +
  19359. std::string(16, 'X'),
  19360. &resp, port));
  19361. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19362. }
  19363. #ifndef _WIN32
  19364. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19365. Server svr;
  19366. svr.Post("/post", [&](const Request &req, Response &res) {
  19367. res.set_content(req.body, "text/plain");
  19368. });
  19369. svr.Put("/put", [&](const Request &req, Response &res) {
  19370. res.set_content(req.body, "text/plain");
  19371. });
  19372. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19373. res.set_content(req.body, "text/plain");
  19374. });
  19375. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19376. res.set_content(req.body, "text/plain");
  19377. });
  19378. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19379. auto se = detail::scope_exit([&] {
  19380. svr.stop();
  19381. t.join();
  19382. ASSERT_FALSE(svr.is_running());
  19383. });
  19384. svr.wait_until_ready();
  19385. std::string resp;
  19386. // POST without Content-Length
  19387. ASSERT_TRUE(send_request(5,
  19388. "POST /post HTTP/1.1\r\n"
  19389. "Host: localhost\r\n"
  19390. "Connection: close\r\n"
  19391. "\r\n",
  19392. &resp));
  19393. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19394. // PUT without Content-Length
  19395. resp.clear();
  19396. ASSERT_TRUE(send_request(5,
  19397. "PUT /put HTTP/1.1\r\n"
  19398. "Host: localhost\r\n"
  19399. "Connection: close\r\n"
  19400. "\r\n",
  19401. &resp));
  19402. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19403. // PATCH without Content-Length
  19404. resp.clear();
  19405. ASSERT_TRUE(send_request(5,
  19406. "PATCH /patch HTTP/1.1\r\n"
  19407. "Host: localhost\r\n"
  19408. "Connection: close\r\n"
  19409. "\r\n",
  19410. &resp));
  19411. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19412. // DELETE without Content-Length
  19413. resp.clear();
  19414. ASSERT_TRUE(send_request(5,
  19415. "DELETE /delete HTTP/1.1\r\n"
  19416. "Host: localhost\r\n"
  19417. "Connection: close\r\n"
  19418. "\r\n",
  19419. &resp));
  19420. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19421. }
  19422. #endif
  19423. //==============================================================================
  19424. // open_stream() Tests
  19425. //==============================================================================
  19426. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19427. std::string result;
  19428. char buf[8192];
  19429. ssize_t n;
  19430. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19431. result.append(buf, static_cast<size_t>(n));
  19432. }
  19433. return result;
  19434. }
  19435. // Mock stream for unit tests
  19436. class MockStream : public Stream {
  19437. public:
  19438. std::string data;
  19439. size_t pos = 0;
  19440. ssize_t error_after = -1; // -1 = no error
  19441. explicit MockStream(const std::string &d, ssize_t err = -1)
  19442. : data(d), error_after(err) {}
  19443. bool is_readable() const override { return true; }
  19444. bool wait_readable() const override { return true; }
  19445. bool wait_writable() const override { return true; }
  19446. ssize_t read(char *ptr, size_t size) override {
  19447. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19448. if (pos >= data.size()) return 0;
  19449. size_t limit =
  19450. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19451. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19452. std::memcpy(ptr, data.data() + pos, to_read);
  19453. pos += to_read;
  19454. return static_cast<ssize_t>(to_read);
  19455. }
  19456. ssize_t write(const char *, size_t) override { return -1; }
  19457. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19458. ip = "127.0.0.1";
  19459. port = 0;
  19460. }
  19461. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19462. ip = "127.0.0.1";
  19463. port = 0;
  19464. }
  19465. socket_t socket() const override { return INVALID_SOCKET; }
  19466. time_t duration() const override { return 0; }
  19467. };
  19468. TEST(StreamHandleTest, Basic) {
  19469. ClientImpl::StreamHandle handle;
  19470. EXPECT_FALSE(handle.is_valid());
  19471. handle.response = detail::make_unique<Response>();
  19472. handle.error = Error::Connection;
  19473. EXPECT_FALSE(handle.is_valid());
  19474. handle.error = Error::Success;
  19475. EXPECT_TRUE(handle.is_valid());
  19476. }
  19477. TEST(BodyReaderTest, Basic) {
  19478. MockStream stream("Hello, World!");
  19479. detail::BodyReader reader;
  19480. reader.stream = &stream;
  19481. reader.content_length = 13;
  19482. char buf[32];
  19483. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19484. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19485. EXPECT_TRUE(reader.eof);
  19486. }
  19487. TEST(BodyReaderTest, NoStream) {
  19488. detail::BodyReader reader;
  19489. char buf[32];
  19490. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19491. EXPECT_EQ(Error::Connection, reader.last_error);
  19492. }
  19493. TEST(BodyReaderTest, Error) {
  19494. MockStream stream("Hello, World!", 5);
  19495. detail::BodyReader reader;
  19496. reader.stream = &stream;
  19497. reader.content_length = 13;
  19498. char buf[32];
  19499. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19500. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19501. EXPECT_EQ(Error::Read, reader.last_error);
  19502. }
  19503. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19504. // Mock-based StreamHandle tests relying on private internals are removed.
  19505. class OpenStreamTest : public ::testing::Test {
  19506. protected:
  19507. void SetUp() override {
  19508. svr_.Get("/hello", [](const Request &, Response &res) {
  19509. res.set_content("Hello World!", "text/plain");
  19510. });
  19511. svr_.Get("/large", [](const Request &, Response &res) {
  19512. res.set_content(std::string(10000, 'X'), "text/plain");
  19513. });
  19514. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19515. res.set_content("Hello World!", "image/jpeg");
  19516. res.set_header("Content-Encoding", "UTF-8");
  19517. });
  19518. svr_.Get("/chunked", [](const Request &, Response &res) {
  19519. res.set_chunked_content_provider("text/plain",
  19520. [](size_t offset, DataSink &sink) {
  19521. if (offset < 15) {
  19522. sink.write("chunk", 5);
  19523. return true;
  19524. }
  19525. sink.done();
  19526. return true;
  19527. });
  19528. });
  19529. svr_.Get("/compressible", [](const Request &, Response &res) {
  19530. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19531. DataSink &sink) {
  19532. if (offset < 100 * 1024) {
  19533. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19534. sink.write(chunk.data(), chunk.size());
  19535. return true;
  19536. }
  19537. sink.done();
  19538. return true;
  19539. });
  19540. });
  19541. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19542. [](const Request & /*req*/, Response &res) {
  19543. auto i = new int(0);
  19544. res.set_header("Trailer", "Content-Length, X-Allowed");
  19545. res.set_chunked_content_provider(
  19546. "text/plain",
  19547. [i](size_t /*offset*/, DataSink &sink) {
  19548. switch (*i) {
  19549. case 0: sink.os << "123"; break;
  19550. case 1: sink.os << "456"; break;
  19551. case 2: sink.os << "789"; break;
  19552. case 3: {
  19553. sink.done_with_trailer(
  19554. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19555. } break;
  19556. }
  19557. (*i)++;
  19558. return true;
  19559. },
  19560. [i](bool success) {
  19561. EXPECT_TRUE(success);
  19562. delete i;
  19563. });
  19564. });
  19565. // Echo headers endpoint for header-related tests
  19566. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19567. std::string body;
  19568. for (const auto &h : req.headers) {
  19569. body.append(h.first);
  19570. body.push_back(':');
  19571. body.append(h.second);
  19572. body.push_back('\n');
  19573. }
  19574. res.set_content(body, "text/plain");
  19575. });
  19576. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19577. std::string body;
  19578. for (const auto &h : req.headers) {
  19579. body.append(h.first);
  19580. body.push_back(':');
  19581. body.append(h.second);
  19582. body.push_back('\n');
  19583. }
  19584. res.set_content(body, "text/plain");
  19585. });
  19586. port_ = svr_.bind_to_any_port("127.0.0.1");
  19587. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19588. svr_.wait_until_ready();
  19589. }
  19590. void TearDown() override {
  19591. svr_.stop();
  19592. if (thread_.joinable()) thread_.join();
  19593. }
  19594. Server svr_;
  19595. std::thread thread_;
  19596. int port_ = 0;
  19597. };
  19598. TEST_F(OpenStreamTest, Basic) {
  19599. Client cli("127.0.0.1", port_);
  19600. auto handle = cli.open_stream("GET", "/hello");
  19601. EXPECT_TRUE(handle.is_valid());
  19602. EXPECT_EQ("Hello World!", read_all(handle));
  19603. }
  19604. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19605. Client cli("127.0.0.1", port_);
  19606. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19607. ASSERT_TRUE(handle.is_valid());
  19608. EXPECT_EQ("Hello World!", read_all(handle));
  19609. }
  19610. TEST_F(OpenStreamTest, SmallBuffer) {
  19611. Client cli("127.0.0.1", port_);
  19612. auto handle = cli.open_stream("GET", "/hello");
  19613. std::string result;
  19614. char buf[4];
  19615. ssize_t n;
  19616. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19617. result.append(buf, static_cast<size_t>(n));
  19618. EXPECT_EQ("Hello World!", result);
  19619. }
  19620. TEST_F(OpenStreamTest, DefaultHeaders) {
  19621. Client cli("127.0.0.1", port_);
  19622. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19623. {
  19624. auto handle = cli.open_stream("GET", "/echo-headers");
  19625. ASSERT_TRUE(handle.is_valid());
  19626. auto body = read_all(handle);
  19627. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19628. std::string::npos);
  19629. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19630. std::string::npos);
  19631. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19632. }
  19633. // open_stream POST with body and no explicit content_type should NOT add
  19634. // text/plain Content-Type (behavior differs from non-streaming path), but
  19635. // should include Content-Length
  19636. {
  19637. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19638. ASSERT_TRUE(handle.is_valid());
  19639. auto body = read_all(handle);
  19640. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19641. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19642. }
  19643. // open_stream POST with explicit Content-Type should preserve it
  19644. {
  19645. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19646. {{"Content-Type", "application/custom"}},
  19647. "{}", "application/custom");
  19648. ASSERT_TRUE(handle.is_valid());
  19649. auto body = read_all(handle);
  19650. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19651. }
  19652. // User-specified User-Agent must not be overwritten for stream API
  19653. {
  19654. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19655. {{"User-Agent", "MyAgent/1.2"}});
  19656. ASSERT_TRUE(handle.is_valid());
  19657. auto body = read_all(handle);
  19658. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19659. }
  19660. }
  19661. TEST_F(OpenStreamTest, Large) {
  19662. Client cli("127.0.0.1", port_);
  19663. auto handle = cli.open_stream("GET", "/large");
  19664. EXPECT_EQ(10000u, read_all(handle).size());
  19665. }
  19666. TEST_F(OpenStreamTest, ConnectionError) {
  19667. Client cli("127.0.0.1", 9999);
  19668. auto handle = cli.open_stream("GET", "/hello");
  19669. EXPECT_FALSE(handle.is_valid());
  19670. }
  19671. TEST_F(OpenStreamTest, Chunked) {
  19672. Client cli("127.0.0.1", port_);
  19673. auto handle = cli.open_stream("GET", "/chunked");
  19674. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19675. "Transfer-Encoding") == "chunked");
  19676. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19677. }
  19678. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19679. Client cli("127.0.0.1", port_);
  19680. auto handle =
  19681. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19682. ASSERT_TRUE(handle.is_valid());
  19683. // Consume body to allow trailers to be received/parsed
  19684. auto body = read_all(handle);
  19685. // Explicitly parse trailers (ensure trailers are available for assertion)
  19686. handle.parse_trailers_if_needed();
  19687. EXPECT_EQ(std::string("123456789"), body);
  19688. // The response should include a Trailer header declaring both names
  19689. ASSERT_TRUE(handle.response);
  19690. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19691. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19692. handle.response->get_header_value("Trailer"));
  19693. // Prohibited trailer must not be present
  19694. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19695. // Allowed trailer should be present
  19696. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19697. EXPECT_EQ(std::string("yes"),
  19698. handle.response->get_trailer_value("X-Allowed"));
  19699. // Verify trailers are NOT present as regular headers
  19700. EXPECT_EQ(std::string(""),
  19701. handle.response->get_header_value("Content-Length"));
  19702. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19703. }
  19704. // Accepts one connection on an OS-assigned port, which it hands over through
  19705. // port_promise, reads the request head and sends back response. after_send,
  19706. // if given, runs on the connection before it is closed.
  19707. static std::thread
  19708. serve_single_response(std::promise<int> &port_promise,
  19709. const std::string &response,
  19710. std::function<void(socket_t)> after_send = nullptr) {
  19711. return std::thread([&port_promise, response, after_send] {
  19712. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19713. default_socket_options(srv);
  19714. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19715. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19716. sockaddr_in addr{};
  19717. addr.sin_family = AF_INET;
  19718. addr.sin_port = htons(0); // Let OS assign a free port
  19719. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19720. int opt = 1;
  19721. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19722. #ifdef _WIN32
  19723. reinterpret_cast<const char *>(&opt),
  19724. #else
  19725. &opt,
  19726. #endif
  19727. sizeof(opt));
  19728. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19729. ::listen(srv, 1) != 0) {
  19730. port_promise.set_value(-1);
  19731. detail::close_socket(srv);
  19732. return;
  19733. }
  19734. socklen_t addr_len = sizeof(addr);
  19735. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19736. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19737. sockaddr_in cli_addr{};
  19738. socklen_t cli_len = sizeof(cli_addr);
  19739. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19740. if (cli != INVALID_SOCKET) {
  19741. // Read the complete HTTP request (until the blank line that terminates
  19742. // headers) before sending the response. If the server closes the socket
  19743. // while the client's request data is still unread in the kernel receive
  19744. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19745. // connection on both sides: it discards the client's receive buffer
  19746. // (which already holds our response) and causes any in-progress write on
  19747. // the client to fail with ECONNRESET. Reading all request data first
  19748. // ensures close() emits a graceful FIN.
  19749. {
  19750. char rbuf[256];
  19751. std::string req;
  19752. while (req.find("\r\n\r\n") == std::string::npos) {
  19753. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19754. if (n <= 0) { break; }
  19755. req.append(rbuf, static_cast<size_t>(n));
  19756. }
  19757. }
  19758. ::send(cli,
  19759. #ifdef _WIN32
  19760. static_cast<const char *>(response.c_str()),
  19761. static_cast<int>(response.size()),
  19762. #else
  19763. response.c_str(), response.size(),
  19764. #endif
  19765. 0);
  19766. if (after_send) { after_send(cli); }
  19767. detail::close_socket(cli);
  19768. }
  19769. detail::close_socket(srv);
  19770. });
  19771. }
  19772. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19773. #ifndef _WIN32
  19774. signal(SIGPIPE, SIG_IGN);
  19775. #endif
  19776. std::promise<int> port_promise;
  19777. auto port_future = port_promise.get_future();
  19778. auto server_thread =
  19779. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19780. "Content-Type: text/plain\r\n"
  19781. "Content-Length: not-a-number\r\n"
  19782. "Connection: close\r\n"
  19783. "\r\n"
  19784. "hello");
  19785. auto port = port_future.get();
  19786. ASSERT_GT(port, 0);
  19787. Client cli("127.0.0.1", port);
  19788. auto handle = cli.open_stream("GET", "/");
  19789. EXPECT_FALSE(handle.is_valid());
  19790. server_thread.join();
  19791. }
  19792. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19793. #ifndef _WIN32
  19794. signal(SIGPIPE, SIG_IGN);
  19795. #endif
  19796. std::promise<int> port_promise;
  19797. auto port_future = port_promise.get_future();
  19798. auto server_thread = serve_single_response(
  19799. port_promise, "HTTP/1.1 200 OK\r\n"
  19800. "Content-Type: text/plain\r\n"
  19801. "Content-Length: 99999999999999999999999999\r\n"
  19802. "Connection: close\r\n"
  19803. "\r\n"
  19804. "hello");
  19805. auto port = port_future.get();
  19806. ASSERT_GT(port, 0);
  19807. // Historically std::stoull would throw std::out_of_range here and crash
  19808. // the process, then parsing silently clamped to a bogus framing length and
  19809. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19810. // so the stream fails to open, matching the not-a-number case above. The
  19811. // process still must NOT terminate.
  19812. Client cli("127.0.0.1", port);
  19813. auto handle = cli.open_stream("GET", "/");
  19814. EXPECT_FALSE(handle.is_valid());
  19815. server_thread.join();
  19816. }
  19817. // Serves `response` to the single request `fn` makes with a fresh client.
  19818. template <typename Fn>
  19819. static void with_single_response(const std::string &response, Fn fn) {
  19820. #ifndef _WIN32
  19821. signal(SIGPIPE, SIG_IGN);
  19822. #endif
  19823. std::promise<int> port_promise;
  19824. auto port_future = port_promise.get_future();
  19825. auto server_thread = serve_single_response(port_promise, response);
  19826. auto se = detail::scope_exit([&] { server_thread.join(); });
  19827. auto port = port_future.get();
  19828. ASSERT_GT(port, 0);
  19829. Client cli("127.0.0.1", port);
  19830. fn(cli);
  19831. }
  19832. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19833. // Neither Content-Length nor chunked: the body ends at the close
  19834. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19835. "Connection: close\r\n"
  19836. "\r\n"
  19837. "hello";
  19838. with_single_response(close_delimited, [](Client &cli) {
  19839. auto handle = cli.open_stream("GET", "/");
  19840. ASSERT_TRUE(handle.is_valid());
  19841. EXPECT_EQ("hello", read_all(handle));
  19842. EXPECT_FALSE(handle.has_read_error());
  19843. });
  19844. // A close before the end of the Content-Length is still an error
  19845. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19846. "Content-Length: 10\r\n"
  19847. "\r\n"
  19848. "hello";
  19849. with_single_response(short_content_length, [](Client &cli) {
  19850. auto handle = cli.open_stream("GET", "/");
  19851. ASSERT_TRUE(handle.is_valid());
  19852. read_all(handle);
  19853. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19854. });
  19855. // So is a close before the last chunk
  19856. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19857. "Transfer-Encoding: chunked\r\n"
  19858. "\r\n"
  19859. "5\r\nhello\r\n";
  19860. with_single_response(short_chunked, [](Client &cli) {
  19861. auto handle = cli.open_stream("GET", "/");
  19862. ASSERT_TRUE(handle.is_valid());
  19863. read_all(handle);
  19864. EXPECT_TRUE(handle.has_read_error());
  19865. });
  19866. }
  19867. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19868. const char *responses[] = {
  19869. "HTTP/1.1 103 Early Hints\r\n"
  19870. "Link: </style.css>; rel=preload\r\n"
  19871. "\r\n"
  19872. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19873. "HTTP/1.1 100 Continue\r\n"
  19874. "X-Note: interim\r\n"
  19875. "\r\n"
  19876. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19877. };
  19878. for (auto response : responses) {
  19879. with_single_response(response, [](Client &cli) {
  19880. auto res = cli.Get("/");
  19881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19882. EXPECT_EQ(StatusCode::OK_200, res->status);
  19883. EXPECT_EQ("ok", res->body);
  19884. });
  19885. }
  19886. }
  19887. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19888. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19889. const std::string final_response =
  19890. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19891. std::string interims;
  19892. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19893. interims += interim;
  19894. }
  19895. with_single_response(interims + final_response, [](Client &cli) {
  19896. auto res = cli.Get("/");
  19897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19898. EXPECT_EQ("ok", res->body);
  19899. });
  19900. with_single_response(interims + interim + final_response, [](Client &cli) {
  19901. auto res = cli.Get("/");
  19902. ASSERT_FALSE(res);
  19903. EXPECT_EQ(Error::Read, res.error());
  19904. });
  19905. }
  19906. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19907. #ifndef _WIN32
  19908. signal(SIGPIPE, SIG_IGN);
  19909. #endif
  19910. // The server answers the head without asking for the body. Bytes it then
  19911. // reads on the connection would be taken for the body the request declared.
  19912. auto closed_by_client = false;
  19913. std::promise<int> port_promise;
  19914. auto server_thread = serve_single_response(
  19915. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19916. [&](socket_t sock) {
  19917. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19918. char buf[256];
  19919. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19920. });
  19921. Client cli("127.0.0.1", port_promise.get_future().get());
  19922. cli.set_keep_alive(true);
  19923. cli.set_read_timeout(1, 0);
  19924. // Long enough for the client to send Expect: 100-continue.
  19925. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19927. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19928. cli.Get("/second");
  19929. server_thread.join();
  19930. EXPECT_TRUE(closed_by_client);
  19931. }
  19932. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19933. // Long enough for the client to send Expect: 100-continue
  19934. with_single_response(
  19935. "HTTP/1.1 103 Early Hints\r\n"
  19936. "Link: </style.css>; rel=preload\r\n"
  19937. "\r\n"
  19938. "HTTP/1.1 401 Unauthorized\r\n"
  19939. "Content-Length: 0\r\n\r\n",
  19940. [](Client &cli) {
  19941. cli.set_read_timeout(2, 0);
  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. });
  19946. }
  19947. #ifdef CPPHTTPLIB_SSL_ENABLED
  19948. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19949. #ifndef _WIN32
  19950. signal(SIGPIPE, SIG_IGN);
  19951. #endif
  19952. auto reused = false;
  19953. std::promise<int> port_promise;
  19954. auto server_thread = serve_single_response(
  19955. port_promise,
  19956. "HTTP/1.1 401 Unauthorized\r\n"
  19957. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19958. "Content-Length: 0\r\n\r\n",
  19959. [&](socket_t sock) {
  19960. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19961. char buf[256];
  19962. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19963. });
  19964. Client cli("127.0.0.1", port_promise.get_future().get());
  19965. cli.set_keep_alive(true);
  19966. cli.set_digest_auth("user", "pass");
  19967. cli.set_read_timeout(1, 0);
  19968. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19969. server_thread.join();
  19970. EXPECT_FALSE(reused);
  19971. }
  19972. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19973. // Any other answer to CONNECT would read as the origin's response.
  19974. struct {
  19975. const char *response;
  19976. bool passed_on;
  19977. } cases[] = {
  19978. {"HTTP/1.1 201 Created\r\n"
  19979. "Set-Cookie: session=from-proxy\r\n"
  19980. "Content-Length: 0\r\n\r\n",
  19981. false},
  19982. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19983. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19984. "Content-Length: 0\r\n\r\n",
  19985. true},
  19986. };
  19987. for (const auto &c : cases) {
  19988. std::promise<int> port_promise;
  19989. auto server_thread = serve_single_response(port_promise, c.response);
  19990. SSLClient cli("example.com", 443);
  19991. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19992. auto res = cli.Get("/");
  19993. server_thread.join();
  19994. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19995. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19996. if (res) {
  19997. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19998. }
  19999. }
  20000. }
  20001. #endif
  20002. // Records the client's error logger calls as "error METHOD path", or
  20003. // "error null" for a call without a request
  20004. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20005. return [&log](const Error &err, const Request *req) {
  20006. log.push_back(to_string(err) + " " +
  20007. (req ? req->method + " " + req->path : "null"));
  20008. };
  20009. }
  20010. // A failed request is reported once, with the request the caller made
  20011. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20012. Server svr;
  20013. svr.Get("/big", [](const Request &, Response &res) {
  20014. res.set_content(std::string(100000, 'b'), "text/plain");
  20015. });
  20016. auto port = svr.bind_to_any_port(HOST);
  20017. std::thread t([&]() { svr.listen_after_bind(); });
  20018. auto se = detail::scope_exit([&] {
  20019. svr.stop();
  20020. t.join();
  20021. });
  20022. svr.wait_until_ready();
  20023. Client cli(HOST, port);
  20024. std::vector<std::string> log;
  20025. cli.set_error_logger(record_errors(log));
  20026. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20027. cli.Get("/big", [](const char *, size_t) { return false; });
  20028. EXPECT_EQ(expected, log);
  20029. log.clear();
  20030. cli.Get("/big", [](size_t, size_t) { return false; });
  20031. EXPECT_EQ(expected, log);
  20032. }
  20033. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20034. // Fails while the body is read
  20035. auto broken = [](const Request &, Response &res) {
  20036. res.set_content_provider(10, "text/plain",
  20037. [](size_t, size_t, DataSink &) { return false; });
  20038. };
  20039. Server other;
  20040. other.Get("/broken", broken);
  20041. auto other_port = other.bind_to_any_port(HOST);
  20042. std::thread other_t([&]() { other.listen_after_bind(); });
  20043. auto other_se = detail::scope_exit([&] {
  20044. other.stop();
  20045. other_t.join();
  20046. });
  20047. other.wait_until_ready();
  20048. Server svr;
  20049. svr.Get("/broken", broken);
  20050. svr.Get("/same-origin",
  20051. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20052. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20053. res.set_redirect("http://" + std::string(HOST) + ":" +
  20054. std::to_string(other_port) + "/broken");
  20055. });
  20056. auto port = svr.bind_to_any_port(HOST);
  20057. std::thread t([&]() { svr.listen_after_bind(); });
  20058. auto se = detail::scope_exit([&] {
  20059. svr.stop();
  20060. t.join();
  20061. });
  20062. svr.wait_until_ready();
  20063. Client cli(HOST, port);
  20064. cli.set_follow_location(true);
  20065. std::vector<std::string> log;
  20066. cli.set_error_logger(record_errors(log));
  20067. for (auto path : {"/same-origin", "/cross-origin"}) {
  20068. log.clear();
  20069. auto res = cli.Get(path);
  20070. ASSERT_FALSE(res);
  20071. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20072. log);
  20073. }
  20074. }
  20075. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20076. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20077. std::vector<std::string> log;
  20078. cli.set_error_logger(record_errors(log));
  20079. auto handle = cli.open_stream("GET", "/x");
  20080. EXPECT_FALSE(handle.is_valid());
  20081. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20082. log);
  20083. });
  20084. }
  20085. #ifdef CPPHTTPLIB_SSL_ENABLED
  20086. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20087. // Not a TLS server, so the handshake fails. It waits for a request line in
  20088. // the handshake bytes, so a short read timeout lets it close quickly.
  20089. Server svr;
  20090. svr.set_read_timeout(0, 100000);
  20091. svr.Get("/x", [](const Request &, Response &res) {
  20092. res.set_content("x", "text/plain");
  20093. });
  20094. auto port = svr.bind_to_any_port(HOST);
  20095. std::thread t([&]() { svr.listen_after_bind(); });
  20096. auto se = detail::scope_exit([&] {
  20097. svr.stop();
  20098. t.join();
  20099. });
  20100. svr.wait_until_ready();
  20101. std::vector<std::string> log;
  20102. SSLClient cli(HOST, port);
  20103. cli.enable_server_certificate_verification(false);
  20104. cli.set_error_logger(record_errors(log));
  20105. auto res = cli.Get("/x");
  20106. ASSERT_FALSE(res);
  20107. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20108. log.clear();
  20109. auto handle = cli.open_stream("GET", "/x");
  20110. EXPECT_FALSE(handle.is_valid());
  20111. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20112. log.clear();
  20113. SSLClient no_ca(HOST, port);
  20114. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20115. no_ca.set_error_logger(record_errors(log));
  20116. res = no_ca.Get("/x");
  20117. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20118. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20119. }
  20120. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20121. #ifndef _WIN32
  20122. signal(SIGPIPE, SIG_IGN);
  20123. #endif
  20124. // Refused, answered with a challenge, or closed without an answer
  20125. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20126. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20127. "Content-Length: 0\r\n\r\n",
  20128. ""}) {
  20129. std::promise<int> port_promise;
  20130. auto server_thread = serve_single_response(port_promise, response);
  20131. SSLClient cli("example.com", 443);
  20132. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20133. std::vector<std::string> log;
  20134. cli.set_error_logger(record_errors(log));
  20135. auto res = cli.Get("/");
  20136. server_thread.join();
  20137. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20138. << response;
  20139. }
  20140. }
  20141. #endif
  20142. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20143. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20144. // the chunked coding and drop Content-Length, so a front-end that trusts
  20145. // Content-Length would disagree about where the body ends (response
  20146. // smuggling). The client must reject such a response.
  20147. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20148. for (const char *te : {"chunked", "gzip, chunked"}) {
  20149. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20150. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20151. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20152. "5\r\nhello\r\n0\r\n\r\n";
  20153. with_single_response(response, [&](Client &cli) {
  20154. auto res = cli.Get("/");
  20155. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20156. EXPECT_EQ(Error::Read, res.error()) << te;
  20157. });
  20158. with_single_response(response, [&](Client &cli) {
  20159. auto handle = cli.open_stream("GET", "/");
  20160. EXPECT_FALSE(handle.is_valid()) << te;
  20161. EXPECT_EQ(Error::Read, handle.error) << te;
  20162. });
  20163. }
  20164. }
  20165. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20166. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20167. // closing the connection (unlike a request, which must be rejected).
  20168. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20169. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20170. "Transfer-Encoding: chunked\r\n"
  20171. "Connection: close\r\n"
  20172. "\r\n"
  20173. "5\r\nhello\r\n0\r\n\r\n",
  20174. "HTTP/1.1 200 OK\r\n"
  20175. "Transfer-Encoding: gzip\r\n"
  20176. "Connection: close\r\n"
  20177. "\r\n"
  20178. "hello"}) {
  20179. with_single_response(response, [&](Client &cli) {
  20180. auto res = cli.Get("/");
  20181. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20182. EXPECT_EQ("hello", res->body);
  20183. });
  20184. with_single_response(response, [&](Client &cli) {
  20185. auto handle = cli.open_stream("GET", "/");
  20186. ASSERT_TRUE(handle.is_valid()) << response;
  20187. EXPECT_EQ("hello", read_all(handle));
  20188. });
  20189. }
  20190. }
  20191. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20192. // framing headers describe nothing to read and must not be rejected.
  20193. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20194. const std::string framing = "Content-Length: 5\r\n"
  20195. "Transfer-Encoding: chunked\r\n"
  20196. "Connection: close\r\n"
  20197. "\r\n";
  20198. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20199. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20200. });
  20201. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20202. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20203. });
  20204. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20205. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20206. with_single_response(response, [&](Client &cli) {
  20207. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20208. });
  20209. with_single_response(response, [&](Client &cli) {
  20210. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20211. });
  20212. }
  20213. }
  20214. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20215. // header section, so a stream opened on one has nothing to read, whatever
  20216. // framing or coding headers it carries.
  20217. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20218. struct Case {
  20219. const char *method;
  20220. const char *status;
  20221. };
  20222. // A reader of the declared body reports an early close when nothing
  20223. // follows, and hands back what does.
  20224. struct Framing {
  20225. const char *headers;
  20226. const char *after;
  20227. };
  20228. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20229. Case{"GET", "304 Not Modified"}}) {
  20230. for (const auto &f :
  20231. {Framing{"Content-Length: 5\r\n", ""},
  20232. Framing{"Content-Length: 5\r\n", "hello"},
  20233. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20234. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20235. // Not decoded, so a build without Brotli opens it too
  20236. Framing{"Content-Encoding: br\r\n", ""}}) {
  20237. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20238. "Connection: close\r\n"
  20239. "\r\n" +
  20240. f.after;
  20241. with_single_response(response, [&](Client &cli) {
  20242. auto handle = cli.open_stream(c.method, "/");
  20243. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20244. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20245. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20246. });
  20247. }
  20248. }
  20249. }
  20250. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20251. // response, is faulty framing, so the connection is not reused after it.
  20252. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20253. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20254. "Content-Length: 0\r\n"
  20255. "Transfer-Encoding: chunked\r\n"
  20256. "\r\n"
  20257. "5\r\nhello\r\n0\r\n\r\n",
  20258. "HTTP/1.0 200 Connection established\r\n"
  20259. "Connection: keep-alive\r\n"
  20260. "Transfer-Encoding: chunked\r\n"
  20261. "\r\n"
  20262. "5\r\nhello\r\n0\r\n\r\n"}) {
  20263. with_single_response(response, [&](Client &cli) {
  20264. cli.set_keep_alive(true);
  20265. auto res = cli.Get("/");
  20266. ASSERT_TRUE(res) << response;
  20267. EXPECT_EQ("hello", res->body);
  20268. EXPECT_FALSE(cli.is_socket_open()) << response;
  20269. });
  20270. }
  20271. }
  20272. // A payload max length of 0 means no limit, however the body is framed.
  20273. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20274. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20275. "Transfer-Encoding: chunked\r\n"
  20276. "\r\n"
  20277. "5\r\nhello\r\n0\r\n\r\n",
  20278. "HTTP/1.1 200 OK\r\n"
  20279. "Connection: close\r\n"
  20280. "\r\n"
  20281. "hello"}) {
  20282. with_single_response(response, [&](Client &cli) {
  20283. cli.set_payload_max_length(0);
  20284. auto res = cli.Get("/");
  20285. ASSERT_TRUE(res) << response;
  20286. EXPECT_EQ("hello", res->body) << response;
  20287. });
  20288. }
  20289. }
  20290. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20291. Server svr;
  20292. svr.set_payload_max_length(0);
  20293. svr.Post("/echo", [](const Request &req, Response &res) {
  20294. res.set_content(req.body, "text/plain");
  20295. });
  20296. auto port = svr.bind_to_any_port(HOST);
  20297. thread t = thread([&] { svr.listen_after_bind(); });
  20298. auto se = detail::scope_exit([&] {
  20299. svr.stop();
  20300. t.join();
  20301. ASSERT_FALSE(svr.is_running());
  20302. });
  20303. svr.wait_until_ready();
  20304. Client cli(HOST, port);
  20305. auto res = cli.Post(
  20306. "/echo",
  20307. [](size_t /*offset*/, DataSink &sink) {
  20308. sink.write("hello", 5);
  20309. sink.done();
  20310. return true;
  20311. },
  20312. "text/plain");
  20313. ASSERT_TRUE(res);
  20314. EXPECT_EQ(StatusCode::OK_200, res->status);
  20315. EXPECT_EQ("hello", res->body);
  20316. }
  20317. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20318. TEST_F(OpenStreamTest, Gzip) {
  20319. Client cli("127.0.0.1", port_);
  20320. auto handle = cli.open_stream("GET", "/compressible", {},
  20321. {{"Accept-Encoding", "gzip"}});
  20322. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20323. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20324. }
  20325. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20326. Client cli("127.0.0.1", port_);
  20327. auto handle =
  20328. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20329. {{"Accept-Encoding", "gzip"}});
  20330. ASSERT_TRUE(handle.is_valid());
  20331. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20332. EXPECT_EQ("123456789", read_all(handle));
  20333. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20334. }
  20335. #endif
  20336. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20337. TEST_F(OpenStreamTest, Brotli) {
  20338. Client cli("127.0.0.1", port_);
  20339. auto handle =
  20340. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20341. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20342. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20343. }
  20344. #endif
  20345. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20346. TEST_F(OpenStreamTest, Zstd) {
  20347. Client cli("127.0.0.1", port_);
  20348. auto handle = cli.open_stream("GET", "/compressible", {},
  20349. {{"Accept-Encoding", "zstd"}});
  20350. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20351. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20352. }
  20353. #endif
  20354. #ifdef CPPHTTPLIB_SSL_ENABLED
  20355. class SSLOpenStreamTest : public ::testing::Test {
  20356. protected:
  20357. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20358. void SetUp() override {
  20359. svr_.Get("/hello", [](const Request &, Response &res) {
  20360. res.set_content("Hello SSL World!", "text/plain");
  20361. });
  20362. svr_.Get("/chunked", [](const Request &, Response &res) {
  20363. res.set_chunked_content_provider("text/plain",
  20364. [](size_t offset, DataSink &sink) {
  20365. if (offset < 15) {
  20366. sink.write("chunk", 5);
  20367. return true;
  20368. }
  20369. sink.done();
  20370. return true;
  20371. });
  20372. });
  20373. svr_.Post("/echo", [](const Request &req, Response &res) {
  20374. res.set_content(req.body, req.get_header_value("Content-Type"));
  20375. });
  20376. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20377. std::string body = req.body;
  20378. res.set_chunked_content_provider(
  20379. "text/plain", [body](size_t offset, DataSink &sink) {
  20380. if (offset < body.size()) {
  20381. sink.write(body.data() + offset, body.size() - offset);
  20382. }
  20383. sink.done();
  20384. return true;
  20385. });
  20386. });
  20387. port_ = svr_.bind_to_any_port("127.0.0.1");
  20388. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20389. svr_.wait_until_ready();
  20390. }
  20391. void TearDown() override {
  20392. svr_.stop();
  20393. if (thread_.joinable()) thread_.join();
  20394. }
  20395. SSLServer svr_;
  20396. std::thread thread_;
  20397. int port_ = 0;
  20398. };
  20399. TEST_F(SSLOpenStreamTest, Basic) {
  20400. SSLClient cli("127.0.0.1", port_);
  20401. cli.enable_server_certificate_verification(false);
  20402. auto handle = cli.open_stream("GET", "/hello");
  20403. ASSERT_TRUE(handle.is_valid());
  20404. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20405. }
  20406. TEST_F(SSLOpenStreamTest, Chunked) {
  20407. SSLClient cli("127.0.0.1", port_);
  20408. cli.enable_server_certificate_verification(false);
  20409. auto handle = cli.open_stream("GET", "/chunked");
  20410. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20411. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20412. "Transfer-Encoding") == "chunked");
  20413. auto body = read_all(handle);
  20414. EXPECT_EQ("chunkchunkchunk", body);
  20415. }
  20416. TEST_F(SSLOpenStreamTest, Post) {
  20417. SSLClient cli("127.0.0.1", port_);
  20418. cli.enable_server_certificate_verification(false);
  20419. auto handle =
  20420. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20421. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20422. EXPECT_EQ(200, handle.response->status);
  20423. auto body = read_all(handle);
  20424. EXPECT_EQ("Hello SSL POST", body);
  20425. }
  20426. TEST_F(SSLOpenStreamTest, PostChunked) {
  20427. SSLClient cli("127.0.0.1", port_);
  20428. cli.enable_server_certificate_verification(false);
  20429. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20430. "Chunked SSL Data", "text/plain");
  20431. ASSERT_TRUE(handle.is_valid());
  20432. EXPECT_EQ(200, handle.response->status);
  20433. auto body = read_all(handle);
  20434. EXPECT_EQ("Chunked SSL Data", body);
  20435. }
  20436. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20437. // Content-Length is terminated by the server closing the connection. When the
  20438. // SSL peer sends a close_notify after the body, the client must treat it as a
  20439. // clean EOF and return a successful response rather than an error.
  20440. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20442. ASSERT_TRUE(svr.is_valid());
  20443. svr.set_keep_alive_max_count(1);
  20444. const std::string expected_body = "Hello from connection-close response!";
  20445. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20446. res.set_content_provider("text/plain",
  20447. [&](size_t offset, DataSink &sink) -> bool {
  20448. if (offset < expected_body.size()) {
  20449. sink.write(expected_body.data() + offset,
  20450. expected_body.size() - offset);
  20451. }
  20452. sink.done();
  20453. return true;
  20454. });
  20455. });
  20456. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20457. auto se = detail::scope_exit([&] {
  20458. svr.stop();
  20459. listen_thread.join();
  20460. ASSERT_FALSE(svr.is_running());
  20461. });
  20462. svr.wait_until_ready();
  20463. SSLClient cli(HOST, PORT);
  20464. cli.enable_server_certificate_verification(false);
  20465. auto res = cli.Get("/no-content-length");
  20466. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20467. EXPECT_EQ(StatusCode::OK_200, res->status);
  20468. EXPECT_EQ(expected_body, res->body);
  20469. }
  20470. #endif // CPPHTTPLIB_SSL_ENABLED
  20471. //==============================================================================
  20472. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20473. // results for various scenarios.
  20474. //==============================================================================
  20475. TEST(ParityTest, GetVsOpenStream) {
  20476. Server svr;
  20477. const std::string path = "/parity";
  20478. const std::string content = "Parity test content: hello world";
  20479. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20480. res.set_content(content, "text/plain");
  20481. });
  20482. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20483. auto se = detail::scope_exit([&] {
  20484. svr.stop();
  20485. t.join();
  20486. ASSERT_FALSE(svr.is_running());
  20487. });
  20488. svr.wait_until_ready();
  20489. Client cli(HOST, PORT);
  20490. // Non-stream path
  20491. auto r1 = cli.Get(path);
  20492. ASSERT_TRUE(r1);
  20493. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20494. // Stream path
  20495. auto h = cli.open_stream("GET", path);
  20496. ASSERT_TRUE(h.is_valid());
  20497. EXPECT_EQ(r1->body, read_all(h));
  20498. }
  20499. // Helper to compress data with provided compressor type T
  20500. template <typename Compressor>
  20501. static std::string compress_payload_for_parity(const std::string &in) {
  20502. std::string out;
  20503. Compressor compressor;
  20504. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20505. [&](const char *data, size_t n) {
  20506. out.append(data, n);
  20507. return true;
  20508. });
  20509. EXPECT_TRUE(ok);
  20510. return out;
  20511. }
  20512. // Helper function for compression parity tests
  20513. template <typename Compressor>
  20514. static void test_compression_parity(const std::string &original,
  20515. const std::string &path,
  20516. const std::string &encoding) {
  20517. const std::string compressed =
  20518. compress_payload_for_parity<Compressor>(original);
  20519. Server svr;
  20520. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20521. res.set_content(compressed, "application/octet-stream");
  20522. res.set_header("Content-Encoding", encoding);
  20523. });
  20524. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20525. auto se = detail::scope_exit([&] {
  20526. svr.stop();
  20527. t.join();
  20528. ASSERT_FALSE(svr.is_running());
  20529. });
  20530. svr.wait_until_ready();
  20531. Client cli(HOST, PORT);
  20532. // Non-streaming
  20533. {
  20534. auto res = cli.Get(path);
  20535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20536. EXPECT_EQ(StatusCode::OK_200, res->status);
  20537. EXPECT_EQ(original, res->body);
  20538. }
  20539. // Streaming
  20540. {
  20541. auto h = cli.open_stream("GET", path);
  20542. ASSERT_TRUE(h.is_valid());
  20543. EXPECT_EQ(original, read_all(h));
  20544. }
  20545. }
  20546. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20547. TEST(ParityTest, Gzip) {
  20548. test_compression_parity<detail::gzip_compressor>(
  20549. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20550. }
  20551. #endif
  20552. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20553. TEST(ParityTest, Brotli) {
  20554. test_compression_parity<detail::brotli_compressor>(
  20555. "Hello, brotli parity test payload", "/parity-br", "br");
  20556. }
  20557. #endif
  20558. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20559. TEST(ParityTest, Zstd) {
  20560. test_compression_parity<detail::zstd_compressor>(
  20561. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20562. }
  20563. #endif
  20564. //==============================================================================
  20565. // New Stream API Tests
  20566. //==============================================================================
  20567. inline std::string read_body(httplib::stream::Result &result) {
  20568. std::string body;
  20569. while (result.next()) {
  20570. body.append(result.data(), result.size());
  20571. }
  20572. return body;
  20573. }
  20574. TEST(ClientConnectionTest, Basic) {
  20575. httplib::ClientConnection conn;
  20576. EXPECT_FALSE(conn.is_open());
  20577. conn.sock = 1;
  20578. EXPECT_TRUE(conn.is_open());
  20579. httplib::ClientConnection conn2(std::move(conn));
  20580. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20581. conn2.sock = INVALID_SOCKET;
  20582. }
  20583. // Unified test server for all stream::* tests
  20584. class StreamApiTest : public ::testing::Test {
  20585. protected:
  20586. void SetUp() override {
  20587. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20588. res.set_content("Hello World!", "text/plain");
  20589. });
  20590. svr_.Get("/echo-params",
  20591. [](const httplib::Request &req, httplib::Response &res) {
  20592. std::string r;
  20593. for (const auto &p : req.params) {
  20594. if (!r.empty()) r += "&";
  20595. r += p.first + "=" + p.second;
  20596. }
  20597. res.set_content(r, "text/plain");
  20598. });
  20599. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20600. res.set_content(req.body, req.get_header_value("Content-Type"));
  20601. });
  20602. svr_.Post("/echo-headers",
  20603. [](const httplib::Request &req, httplib::Response &res) {
  20604. std::string r;
  20605. for (const auto &h : req.headers)
  20606. r += h.first + ": " + h.second + "\n";
  20607. res.set_content(r, "text/plain");
  20608. });
  20609. svr_.Post("/echo-params",
  20610. [](const httplib::Request &req, httplib::Response &res) {
  20611. std::string r = "params:";
  20612. for (const auto &p : req.params)
  20613. r += p.first + "=" + p.second + ";";
  20614. res.set_content(r + " body:" + req.body, "text/plain");
  20615. });
  20616. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20617. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20618. });
  20619. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20620. res.set_content("PUT:" + req.body, "text/plain");
  20621. });
  20622. svr_.Patch("/echo",
  20623. [](const httplib::Request &req, httplib::Response &res) {
  20624. res.set_content("PATCH:" + req.body, "text/plain");
  20625. });
  20626. svr_.Delete(
  20627. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20628. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20629. "text/plain");
  20630. });
  20631. svr_.Get("/head-test",
  20632. [](const httplib::Request &, httplib::Response &res) {
  20633. res.set_content("body for HEAD", "text/plain");
  20634. });
  20635. svr_.Options("/options",
  20636. [](const httplib::Request &, httplib::Response &res) {
  20637. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20638. });
  20639. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20640. svr_.wait_until_ready();
  20641. }
  20642. void TearDown() override {
  20643. svr_.stop();
  20644. if (thread_.joinable()) thread_.join();
  20645. }
  20646. httplib::Server svr_;
  20647. std::thread thread_;
  20648. };
  20649. // stream::Get tests
  20650. TEST_F(StreamApiTest, GetBasic) {
  20651. httplib::Client cli(HOST, PORT);
  20652. auto result = httplib::stream::Get(cli, "/hello");
  20653. ASSERT_TRUE(result.is_valid());
  20654. EXPECT_EQ(200, result.status());
  20655. EXPECT_EQ("Hello World!", read_body(result));
  20656. }
  20657. TEST_F(StreamApiTest, GetWithParams) {
  20658. httplib::Client cli(HOST, PORT);
  20659. httplib::Params params{{"foo", "bar"}};
  20660. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20661. ASSERT_TRUE(result.is_valid());
  20662. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20663. }
  20664. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20665. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20666. httplib::Client cli(HOST, PORT);
  20667. cli.set_payload_max_length(0);
  20668. auto result = httplib::stream::Get(cli, "/hello");
  20669. ASSERT_TRUE(result.is_valid());
  20670. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20671. EXPECT_EQ("Hello World!", read_body(result));
  20672. }
  20673. #endif
  20674. TEST_F(StreamApiTest, GetConnectionError) {
  20675. httplib::Client cli(HOST, 9999);
  20676. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20677. }
  20678. TEST_F(StreamApiTest, Get404) {
  20679. httplib::Client cli(HOST, PORT);
  20680. auto result = httplib::stream::Get(cli, "/nonexistent");
  20681. EXPECT_TRUE(result.is_valid());
  20682. EXPECT_EQ(404, result.status());
  20683. }
  20684. // stream::Post tests
  20685. TEST_F(StreamApiTest, PostBasic) {
  20686. httplib::Client cli(HOST, PORT);
  20687. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20688. "application/json");
  20689. ASSERT_TRUE(result.is_valid());
  20690. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20691. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20692. }
  20693. TEST_F(StreamApiTest, PostWithHeaders) {
  20694. httplib::Client cli(HOST, PORT);
  20695. httplib::Headers headers{{"X-Custom", "value"}};
  20696. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20697. "text/plain");
  20698. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20699. }
  20700. TEST_F(StreamApiTest, PostWithParams) {
  20701. httplib::Client cli(HOST, PORT);
  20702. httplib::Params params{{"k", "v"}};
  20703. auto result =
  20704. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20705. auto body = read_body(result);
  20706. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20707. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20708. }
  20709. TEST_F(StreamApiTest, PostLarge) {
  20710. httplib::Client cli(HOST, PORT);
  20711. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20712. size_t total = 0;
  20713. while (result.next()) {
  20714. total += result.size();
  20715. }
  20716. EXPECT_EQ(100u * 1024u, total);
  20717. }
  20718. // stream::Put/Patch tests
  20719. TEST_F(StreamApiTest, PutAndPatch) {
  20720. httplib::Client cli(HOST, PORT);
  20721. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20722. EXPECT_EQ("PUT:test", read_body(put));
  20723. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20724. EXPECT_EQ("PATCH:test", read_body(patch));
  20725. }
  20726. // stream::Delete tests
  20727. TEST_F(StreamApiTest, Delete) {
  20728. httplib::Client cli(HOST, PORT);
  20729. auto del1 = httplib::stream::Delete(cli, "/resource");
  20730. EXPECT_EQ("Deleted", read_body(del1));
  20731. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20732. EXPECT_EQ("Deleted:data", read_body(del2));
  20733. }
  20734. // stream::Head/Options tests
  20735. TEST_F(StreamApiTest, HeadAndOptions) {
  20736. httplib::Client cli(HOST, PORT);
  20737. auto head = httplib::stream::Head(cli, "/head-test");
  20738. EXPECT_TRUE(head.is_valid());
  20739. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20740. auto opts = httplib::stream::Options(cli, "/options");
  20741. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20742. }
  20743. // SSL stream::* tests
  20744. #ifdef CPPHTTPLIB_SSL_ENABLED
  20745. class SSLStreamApiTest : public ::testing::Test {
  20746. protected:
  20747. void SetUp() override {
  20748. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20749. res.set_content("Hello SSL!", "text/plain");
  20750. });
  20751. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20752. res.set_content(req.body, "text/plain");
  20753. });
  20754. port_ = svr_.bind_to_any_port("127.0.0.1");
  20755. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20756. svr_.wait_until_ready();
  20757. }
  20758. void TearDown() override {
  20759. svr_.stop();
  20760. if (thread_.joinable()) thread_.join();
  20761. }
  20762. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20763. std::thread thread_;
  20764. int port_ = 0;
  20765. };
  20766. TEST_F(SSLStreamApiTest, GetAndPost) {
  20767. httplib::SSLClient cli("127.0.0.1", port_);
  20768. cli.enable_server_certificate_verification(false);
  20769. auto get = httplib::stream::Get(cli, "/hello");
  20770. EXPECT_EQ("Hello SSL!", read_body(get));
  20771. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20772. EXPECT_EQ("test", read_body(post));
  20773. }
  20774. #endif
  20775. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20776. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20777. // BodyReader
  20778. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20779. // Test that read timeout during streaming is detected
  20780. // Use a large content-length response where server delays mid-stream
  20781. Server svr;
  20782. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20783. // Send a large response with delay in the middle
  20784. res.set_content_provider(
  20785. 1000, // content_length
  20786. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20787. if (offset < 100) {
  20788. // Send first 100 bytes immediately
  20789. std::string data(100, 'A');
  20790. sink.write(data.c_str(), data.size());
  20791. return true;
  20792. }
  20793. // Then delay longer than client timeout
  20794. std::this_thread::sleep_for(std::chrono::seconds(3));
  20795. std::string data(900, 'B');
  20796. sink.write(data.c_str(), data.size());
  20797. return true;
  20798. });
  20799. });
  20800. auto port = 8091;
  20801. std::thread t([&]() { svr.listen("localhost", port); });
  20802. svr.wait_until_ready();
  20803. Client cli("localhost", port);
  20804. cli.set_read_timeout(1, 0); // 1 second timeout
  20805. auto handle = cli.open_stream("GET", "/slow-stream");
  20806. ASSERT_TRUE(handle.is_valid());
  20807. char buf[256];
  20808. ssize_t total = 0;
  20809. ssize_t n;
  20810. bool got_error = false;
  20811. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20812. total += n;
  20813. }
  20814. if (n < 0) {
  20815. got_error = true;
  20816. // Should be timeout or read error
  20817. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20818. handle.get_read_error() == Error::Read)
  20819. << "Actual error: " << to_string(handle.get_read_error());
  20820. }
  20821. // Either we got an error, or we got less data than expected
  20822. EXPECT_TRUE(got_error || total < 1000)
  20823. << "Expected timeout but got all " << total << " bytes";
  20824. svr.stop();
  20825. t.join();
  20826. }
  20827. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20828. // Test connection closed detection via BodyReader
  20829. Server svr;
  20830. std::atomic<bool> close_now{false};
  20831. svr.Get("/will-close", [&](const Request &, Response &res) {
  20832. res.set_content_provider(
  20833. 10000, // Large content_length that we won't fully send
  20834. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20835. if (offset < 100) {
  20836. std::string data(100, 'X');
  20837. sink.write(data.c_str(), data.size());
  20838. return true;
  20839. }
  20840. // Wait for signal then abort
  20841. while (!close_now) {
  20842. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20843. }
  20844. return false; // Abort - server will close connection
  20845. });
  20846. });
  20847. auto port = 8092;
  20848. std::thread t([&]() { svr.listen("localhost", port); });
  20849. svr.wait_until_ready();
  20850. Client cli("localhost", port);
  20851. auto handle = cli.open_stream("GET", "/will-close");
  20852. ASSERT_TRUE(handle.is_valid());
  20853. char buf[256];
  20854. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20855. EXPECT_GT(n, 0) << "First read should succeed";
  20856. // Signal server to close
  20857. close_now = true;
  20858. // Keep reading until error or EOF
  20859. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20860. // Keep reading
  20861. }
  20862. // Should get an error since content_length wasn't satisfied
  20863. if (n < 0) {
  20864. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20865. handle.get_read_error() == Error::Read)
  20866. << "Actual error: " << to_string(handle.get_read_error());
  20867. }
  20868. svr.stop();
  20869. t.join();
  20870. }
  20871. #ifdef CPPHTTPLIB_SSL_ENABLED
  20872. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20873. // Test that read timeout during SSL streaming is detected
  20874. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20875. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20876. res.set_content_provider(
  20877. 1000, "text/plain",
  20878. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20879. if (offset < 100) {
  20880. std::string data(100, 'A');
  20881. sink.write(data.c_str(), data.size());
  20882. return true;
  20883. }
  20884. std::this_thread::sleep_for(std::chrono::seconds(3));
  20885. std::string data(900, 'B');
  20886. sink.write(data.c_str(), data.size());
  20887. return true;
  20888. });
  20889. });
  20890. auto port = 8093;
  20891. std::thread t([&]() { svr.listen("localhost", port); });
  20892. svr.wait_until_ready();
  20893. SSLClient cli("localhost", port);
  20894. cli.enable_server_certificate_verification(false);
  20895. cli.set_read_timeout(1, 0); // 1 second timeout
  20896. auto handle = cli.open_stream("GET", "/slow-stream");
  20897. ASSERT_TRUE(handle.is_valid());
  20898. char buf[256];
  20899. ssize_t total = 0;
  20900. ssize_t n;
  20901. bool got_error = false;
  20902. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20903. total += n;
  20904. }
  20905. if (n < 0) {
  20906. got_error = true;
  20907. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20908. handle.get_read_error() == Error::Read)
  20909. << "Actual error: " << to_string(handle.get_read_error());
  20910. }
  20911. EXPECT_TRUE(got_error || total < 1000)
  20912. << "Expected timeout but got all " << total << " bytes";
  20913. svr.stop();
  20914. t.join();
  20915. }
  20916. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20917. // Test SSL connection closed detection
  20918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20919. std::atomic<bool> close_now{false};
  20920. svr.Get("/will-close", [&](const Request &, Response &res) {
  20921. res.set_content_provider(
  20922. 10000, "text/plain",
  20923. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20924. if (offset < 100) {
  20925. std::string data(100, 'X');
  20926. sink.write(data.c_str(), data.size());
  20927. return true;
  20928. }
  20929. while (!close_now) {
  20930. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20931. }
  20932. return false;
  20933. });
  20934. });
  20935. auto port = 8094;
  20936. std::thread t([&]() { svr.listen("localhost", port); });
  20937. svr.wait_until_ready();
  20938. SSLClient cli("localhost", port);
  20939. cli.enable_server_certificate_verification(false);
  20940. auto handle = cli.open_stream("GET", "/will-close");
  20941. ASSERT_TRUE(handle.is_valid());
  20942. char buf[256];
  20943. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20944. EXPECT_GT(n, 0);
  20945. // Signal server to close
  20946. close_now = true;
  20947. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20948. // Keep reading
  20949. }
  20950. if (n < 0) {
  20951. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20952. handle.get_read_error() == Error::Read)
  20953. << "Actual error: " << to_string(handle.get_read_error());
  20954. }
  20955. svr.stop();
  20956. t.join();
  20957. }
  20958. #endif
  20959. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20960. using namespace httplib;
  20961. // Create a test file
  20962. const char *fname = "etag_testfile.txt";
  20963. const char *content = "etag-content";
  20964. {
  20965. std::ofstream ofs(fname);
  20966. ofs << content;
  20967. ASSERT_TRUE(ofs.good());
  20968. }
  20969. Server svr;
  20970. svr.set_mount_point("/static", ".");
  20971. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20972. svr.wait_until_ready();
  20973. Client cli(HOST, PORT);
  20974. // First request: should get 200 with ETag header
  20975. auto res1 = cli.Get("/static/etag_testfile.txt");
  20976. ASSERT_TRUE(res1);
  20977. ASSERT_EQ(200, res1->status);
  20978. ASSERT_TRUE(res1->has_header("ETag"));
  20979. std::string etag = res1->get_header_value("ETag");
  20980. EXPECT_FALSE(etag.empty());
  20981. // Verify ETag format: W/"hex-hex"
  20982. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20983. EXPECT_EQ('W', etag[0]);
  20984. EXPECT_EQ('/', etag[1]);
  20985. EXPECT_EQ('"', etag[2]);
  20986. EXPECT_EQ('"', etag.back());
  20987. // Exact match: expect 304 Not Modified
  20988. Headers h2 = {{"If-None-Match", etag}};
  20989. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20990. ASSERT_TRUE(res2);
  20991. EXPECT_EQ(304, res2->status);
  20992. // Wildcard match: expect 304 Not Modified
  20993. Headers h3 = {{"If-None-Match", "*"}};
  20994. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20995. ASSERT_TRUE(res3);
  20996. EXPECT_EQ(304, res3->status);
  20997. // Non-matching ETag: expect 200
  20998. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20999. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21000. ASSERT_TRUE(res4);
  21001. EXPECT_EQ(200, res4->status);
  21002. // Multiple ETags with one matching: expect 304
  21003. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21004. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21005. ASSERT_TRUE(res5);
  21006. EXPECT_EQ(304, res5->status);
  21007. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21008. // that equivalent to the single comma-separated list above, so the match on
  21009. // the second line must still be found.
  21010. Headers h6;
  21011. h6.emplace("If-None-Match", "W/\"other\"");
  21012. h6.emplace("If-None-Match", etag);
  21013. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21014. ASSERT_TRUE(res6);
  21015. EXPECT_EQ(304, res6->status);
  21016. svr.stop();
  21017. t.join();
  21018. std::remove(fname);
  21019. }
  21020. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21021. using namespace httplib;
  21022. Server svr;
  21023. svr.set_mount_point("/static", ".");
  21024. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21025. svr.wait_until_ready();
  21026. Client cli(HOST, PORT);
  21027. // Send If-None-Match: * to a non-existent file
  21028. Headers h = {{"If-None-Match", "*"}};
  21029. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21031. EXPECT_EQ(404, res->status);
  21032. svr.stop();
  21033. t.join();
  21034. }
  21035. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21036. using namespace httplib;
  21037. // Create a test file
  21038. const char *fname = "etag_boundary_testfile.txt";
  21039. const char *content = "boundary-test";
  21040. {
  21041. std::ofstream ofs(fname);
  21042. ofs << content;
  21043. ASSERT_TRUE(ofs.good());
  21044. }
  21045. Server svr;
  21046. svr.set_mount_point("/static", ".");
  21047. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21048. svr.wait_until_ready();
  21049. Client cli(HOST, PORT);
  21050. // Get the actual ETag
  21051. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21052. ASSERT_TRUE(res1);
  21053. ASSERT_EQ(200, res1->status);
  21054. ASSERT_TRUE(res1->has_header("ETag"));
  21055. std::string etag = res1->get_header_value("ETag");
  21056. // Test 1: Very long ETag value (longer than actual ETag)
  21057. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21058. Headers h1 = {{"If-None-Match", "W/"
  21059. "\"very-long-etag-value-that-is-much-longer-"
  21060. "than-the-actual-etag-value\""}};
  21061. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21062. ASSERT_TRUE(res2);
  21063. EXPECT_EQ(200, res2->status); // Should not match
  21064. // Test 2: Long string followed by wildcard
  21065. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21066. // string)
  21067. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21068. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21069. ASSERT_TRUE(res3);
  21070. EXPECT_EQ(304, res3->status); // Should match on "*"
  21071. // Test 3: Wildcard followed by long string
  21072. // Should match on "*" immediately and return 304
  21073. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21074. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21075. ASSERT_TRUE(res4);
  21076. EXPECT_EQ(304, res4->status); // Should match on "*"
  21077. // Test 4: Multiple long non-matching values
  21078. // Should NOT match and return 200 (test that all comparisons are safe)
  21079. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21080. "W/\"second-long-non-matching-value\", "
  21081. "W/\"third-long-non-matching-value\""}};
  21082. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21083. ASSERT_TRUE(res5);
  21084. EXPECT_EQ(200, res5->status); // Should not match
  21085. // Test 5: Single character that is not "*" (edge case)
  21086. Headers h5 = {{"If-None-Match", "X"}};
  21087. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21088. ASSERT_TRUE(res6);
  21089. EXPECT_EQ(200, res6->status); // Should not match
  21090. svr.stop();
  21091. t.join();
  21092. std::remove(fname);
  21093. }
  21094. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21095. using namespace httplib;
  21096. // Create a test file
  21097. const char *fname = "ims_testfile.txt";
  21098. const char *content = "if-modified-since-test";
  21099. {
  21100. std::ofstream ofs(fname);
  21101. ofs << content;
  21102. ASSERT_TRUE(ofs.good());
  21103. }
  21104. Server svr;
  21105. svr.set_mount_point("/static", ".");
  21106. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21107. svr.wait_until_ready();
  21108. Client cli(HOST, PORT);
  21109. // First request: should get 200 with Last-Modified header
  21110. auto res1 = cli.Get("/static/ims_testfile.txt");
  21111. ASSERT_TRUE(res1);
  21112. ASSERT_EQ(200, res1->status);
  21113. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21114. std::string last_modified = res1->get_header_value("Last-Modified");
  21115. EXPECT_FALSE(last_modified.empty());
  21116. // If-Modified-Since with same time: expect 304
  21117. Headers h2 = {{"If-Modified-Since", last_modified}};
  21118. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21119. ASSERT_TRUE(res2);
  21120. EXPECT_EQ(304, res2->status);
  21121. // If-Modified-Since with future time: expect 304
  21122. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21123. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21124. ASSERT_TRUE(res3);
  21125. EXPECT_EQ(304, res3->status);
  21126. // If-Modified-Since with past time: expect 200
  21127. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21128. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21129. ASSERT_TRUE(res4);
  21130. EXPECT_EQ(200, res4->status);
  21131. // If-None-Match takes precedence over If-Modified-Since
  21132. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21133. ASSERT_TRUE(res1->has_header("ETag"));
  21134. std::string etag = res1->get_header_value("ETag");
  21135. Headers h5 = {{"If-None-Match", etag},
  21136. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21137. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21138. ASSERT_TRUE(res5);
  21139. EXPECT_EQ(304, res5->status);
  21140. svr.stop();
  21141. t.join();
  21142. std::remove(fname);
  21143. }
  21144. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21145. using namespace httplib;
  21146. Server svr;
  21147. // Endpoint that returns compressible content
  21148. svr.Get("/compressible", [](const Request &, Response &res) {
  21149. // Return a large enough body to trigger compression
  21150. std::string body(1000, 'a');
  21151. res.set_content(body, "text/plain");
  21152. });
  21153. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21154. svr.wait_until_ready();
  21155. Client cli(HOST, PORT);
  21156. // Request with gzip support: should get Vary header when compressed
  21157. cli.set_compress(true);
  21158. auto res1 = cli.Get("/compressible");
  21159. ASSERT_TRUE(res1);
  21160. EXPECT_EQ(200, res1->status);
  21161. // If Content-Encoding is set, Vary should also be set
  21162. if (res1->has_header("Content-Encoding")) {
  21163. EXPECT_TRUE(res1->has_header("Vary"));
  21164. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21165. }
  21166. // Request without Accept-Encoding header: should not have compression
  21167. Headers h_no_compress;
  21168. auto res2 = cli.Get("/compressible", h_no_compress);
  21169. ASSERT_TRUE(res2);
  21170. EXPECT_EQ(200, res2->status);
  21171. // Verify Vary header is present when compression is applied
  21172. // (the exact behavior depends on server configuration)
  21173. svr.stop();
  21174. t.join();
  21175. }
  21176. TEST(ETagTest, IfRangeWithETag) {
  21177. using namespace httplib;
  21178. // Create a test file with known content
  21179. const char *fname = "if_range_testfile.txt";
  21180. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21181. {
  21182. std::ofstream ofs(fname);
  21183. ofs << content;
  21184. ASSERT_TRUE(ofs.good());
  21185. }
  21186. Server svr;
  21187. svr.set_mount_point("/static", ".");
  21188. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21189. svr.wait_until_ready();
  21190. Client cli(HOST, PORT);
  21191. // First request: get ETag
  21192. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21193. ASSERT_TRUE(res1);
  21194. ASSERT_EQ(200, res1->status);
  21195. ASSERT_TRUE(res1->has_header("ETag"));
  21196. std::string etag = res1->get_header_value("ETag");
  21197. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21198. // Since our server generates weak ETags (W/"..."), If-Range with our
  21199. // ETag should NOT result in partial content - it should return full content.
  21200. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21201. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21202. ASSERT_TRUE(res2);
  21203. // Weak ETag in If-Range -> full content (200), not partial (206)
  21204. EXPECT_EQ(200, res2->status);
  21205. EXPECT_EQ(content, res2->body);
  21206. EXPECT_FALSE(res2->has_header("Content-Range"));
  21207. // Range request with non-matching If-Range (ETag): should get 200 (full
  21208. // content)
  21209. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21210. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21211. ASSERT_TRUE(res3);
  21212. EXPECT_EQ(200, res3->status);
  21213. EXPECT_EQ(content, res3->body);
  21214. EXPECT_FALSE(res3->has_header("Content-Range"));
  21215. // Range request with strong ETag (hypothetical - our server doesn't generate
  21216. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21217. // should return full content)
  21218. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21219. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21220. ASSERT_TRUE(res4);
  21221. EXPECT_EQ(200, res4->status);
  21222. EXPECT_EQ(content, res4->body);
  21223. EXPECT_FALSE(res4->has_header("Content-Range"));
  21224. svr.stop();
  21225. t.join();
  21226. std::remove(fname);
  21227. }
  21228. TEST(ETagTest, IfRangeWithDate) {
  21229. using namespace httplib;
  21230. // Create a test file
  21231. const char *fname = "if_range_date_testfile.txt";
  21232. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21233. {
  21234. std::ofstream ofs(fname);
  21235. ofs << content;
  21236. ASSERT_TRUE(ofs.good());
  21237. }
  21238. Server svr;
  21239. svr.set_mount_point("/static", ".");
  21240. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21241. svr.wait_until_ready();
  21242. Client cli(HOST, PORT);
  21243. // First request: get Last-Modified
  21244. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21245. ASSERT_TRUE(res1);
  21246. ASSERT_EQ(200, res1->status);
  21247. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21248. std::string last_modified = res1->get_header_value("Last-Modified");
  21249. // Range request with matching If-Range (date): should get 206
  21250. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21251. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21252. ASSERT_TRUE(res2);
  21253. EXPECT_EQ(206, res2->status);
  21254. EXPECT_EQ("FGHIJ", res2->body);
  21255. // Range request with old If-Range date: should get 200 (full content)
  21256. Headers h3 = {{"Range", "bytes=5-9"},
  21257. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21258. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21259. ASSERT_TRUE(res3);
  21260. EXPECT_EQ(200, res3->status);
  21261. EXPECT_EQ(content, res3->body);
  21262. // Range request with future If-Range date: should get 206
  21263. Headers h4 = {{"Range", "bytes=0-4"},
  21264. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21265. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21266. ASSERT_TRUE(res4);
  21267. EXPECT_EQ(206, res4->status);
  21268. EXPECT_EQ("ABCDE", res4->body);
  21269. svr.stop();
  21270. t.join();
  21271. std::remove(fname);
  21272. }
  21273. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21274. using namespace httplib;
  21275. const char *fname = "etag_malformed.txt";
  21276. const char *content = "malformed-etag";
  21277. {
  21278. std::ofstream ofs(fname);
  21279. ofs << content;
  21280. ASSERT_TRUE(ofs.good());
  21281. }
  21282. Server svr;
  21283. svr.set_mount_point("/static", ".");
  21284. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21285. svr.wait_until_ready();
  21286. Client cli(HOST, PORT);
  21287. // baseline: should get 200 and an ETag
  21288. auto res1 = cli.Get("/static/etag_malformed.txt");
  21289. ASSERT_TRUE(res1);
  21290. ASSERT_EQ(200, res1->status);
  21291. ASSERT_TRUE(res1->has_header("ETag"));
  21292. // Malformed ETag value (missing quotes) should be treated as non-matching
  21293. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21294. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21295. ASSERT_TRUE(res_bad);
  21296. EXPECT_EQ(200, res_bad->status);
  21297. // Whitespace-only header value should be considered invalid / non-matching
  21298. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21299. "Host: localhost\r\n"
  21300. "If-None-Match: \r\n"
  21301. "Connection: close\r\n"
  21302. "\r\n";
  21303. std::string out;
  21304. ASSERT_TRUE(send_request(5, raw_req, &out));
  21305. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21306. svr.stop();
  21307. t.join();
  21308. std::remove(fname);
  21309. }
  21310. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21311. using namespace httplib;
  21312. const char *fname = "ims_invalid_format.txt";
  21313. const char *content = "ims-bad-format";
  21314. {
  21315. std::ofstream ofs(fname);
  21316. ofs << content;
  21317. ASSERT_TRUE(ofs.good());
  21318. }
  21319. Server svr;
  21320. svr.set_mount_point("/static", ".");
  21321. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21322. svr.wait_until_ready();
  21323. Client cli(HOST, PORT);
  21324. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21325. ASSERT_TRUE(res1);
  21326. ASSERT_EQ(200, res1->status);
  21327. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21328. // If-Modified-Since with invalid format should not result in 304
  21329. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21330. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21331. ASSERT_TRUE(res_bad);
  21332. EXPECT_EQ(200, res_bad->status);
  21333. // If-Range with invalid date format should be treated as mismatch -> full
  21334. // content (200)
  21335. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21336. {"If-Range", "invalid-date"}};
  21337. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21338. ASSERT_TRUE(res_ifrange);
  21339. EXPECT_EQ(200, res_ifrange->status);
  21340. svr.stop();
  21341. t.join();
  21342. std::remove(fname);
  21343. }
  21344. TEST(ETagTest, IfRangeWithMalformedETag) {
  21345. using namespace httplib;
  21346. const char *fname = "ifrange_malformed.txt";
  21347. const std::string content = "0123456789";
  21348. {
  21349. std::ofstream ofs(fname);
  21350. ofs << content;
  21351. ASSERT_TRUE(ofs.good());
  21352. }
  21353. Server svr;
  21354. svr.set_mount_point("/static", ".");
  21355. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21356. svr.wait_until_ready();
  21357. Client cli(HOST, PORT);
  21358. // First request: get ETag
  21359. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21360. ASSERT_TRUE(res1);
  21361. ASSERT_EQ(200, res1->status);
  21362. ASSERT_TRUE(res1->has_header("ETag"));
  21363. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21364. // full content (200)
  21365. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21366. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21367. ASSERT_TRUE(res2);
  21368. EXPECT_EQ(200, res2->status);
  21369. EXPECT_EQ(content, res2->body);
  21370. svr.stop();
  21371. t.join();
  21372. std::remove(fname);
  21373. }
  21374. TEST(ETagTest, ExtremeLargeDateValues) {
  21375. using namespace httplib;
  21376. const char *fname = "ims_extreme_date.txt";
  21377. const char *content = "ims-extreme-date";
  21378. {
  21379. std::ofstream ofs(fname);
  21380. ofs << content;
  21381. ASSERT_TRUE(ofs.good());
  21382. }
  21383. Server svr;
  21384. svr.set_mount_point("/static", ".");
  21385. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21386. svr.wait_until_ready();
  21387. Client cli(HOST, PORT);
  21388. auto res1 = cli.Get(std::string("/static/") + fname);
  21389. ASSERT_TRUE(res1);
  21390. ASSERT_EQ(200, res1->status);
  21391. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21392. // Extremely large year that may overflow date parsing routines.
  21393. Headers h_large_date = {
  21394. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21395. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21396. ASSERT_TRUE(res_bad);
  21397. // Expect server to treat this as invalid/mismatch and return full content
  21398. EXPECT_EQ(200, res_bad->status);
  21399. // If-Range with extremely large date should be treated as mismatch -> full
  21400. // content (200)
  21401. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21402. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21403. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21404. ASSERT_TRUE(res_ifrange);
  21405. EXPECT_EQ(200, res_ifrange->status);
  21406. svr.stop();
  21407. t.join();
  21408. std::remove(fname);
  21409. }
  21410. TEST(ETagTest, NegativeFileModificationTime) {
  21411. using namespace httplib;
  21412. const char *fname = "ims_negative_mtime.txt";
  21413. const std::string content = "negative-mtime";
  21414. {
  21415. std::ofstream ofs(fname);
  21416. ofs << content;
  21417. ASSERT_TRUE(ofs.good());
  21418. }
  21419. // Try to set file mtime to a negative value. This may fail on some
  21420. // platforms/filesystems; if it fails, the test will still verify server
  21421. // behaves safely by performing a regular conditional request.
  21422. #if defined(__APPLE__) || defined(__linux__)
  21423. bool set_negative = false;
  21424. do {
  21425. struct timeval times[2];
  21426. // access time: now
  21427. times[0].tv_sec = time(nullptr);
  21428. times[0].tv_usec = 0;
  21429. // modification time: negative (e.g., -1)
  21430. times[1].tv_sec = -1;
  21431. times[1].tv_usec = 0;
  21432. if (utimes(fname, times) == 0) { set_negative = true; }
  21433. } while (0);
  21434. #else
  21435. bool set_negative = false;
  21436. #endif
  21437. Server svr;
  21438. svr.set_mount_point("/static", ".");
  21439. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21440. svr.wait_until_ready();
  21441. Client cli(HOST, PORT);
  21442. auto res1 = cli.Get(std::string("/static/") + fname);
  21443. ASSERT_TRUE(res1);
  21444. ASSERT_EQ(200, res1->status);
  21445. bool has_last_modified = res1->has_header("Last-Modified");
  21446. std::string last_modified;
  21447. if (has_last_modified) {
  21448. last_modified = res1->get_header_value("Last-Modified");
  21449. }
  21450. if (set_negative) {
  21451. // If we successfully set a negative mtime, ensure server returns a
  21452. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21453. // with an old date and ensure server handles it without crash.
  21454. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21455. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21456. ASSERT_TRUE(res2);
  21457. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21458. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21459. } else {
  21460. // Could not set negative mtime on this platform; fall back to verifying
  21461. // that normal invalid/malformed dates are treated safely (non-304).
  21462. Headers h_bad_date = {
  21463. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21464. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21465. ASSERT_TRUE(res_bad);
  21466. EXPECT_EQ(200, res_bad->status);
  21467. }
  21468. svr.stop();
  21469. t.join();
  21470. std::remove(fname);
  21471. }
  21472. //==============================================================================
  21473. // Integration Tests with Server
  21474. //==============================================================================
  21475. class SSEIntegrationTest : public ::testing::Test {
  21476. protected:
  21477. void SetUp() override {
  21478. stop_server_.store(false);
  21479. events_.clear();
  21480. server_ = httplib::detail::make_unique<Server>();
  21481. setup_server();
  21482. start_server();
  21483. }
  21484. void TearDown() override {
  21485. stop_server_.store(true);
  21486. event_cv_.notify_all();
  21487. server_->stop();
  21488. if (server_thread_.joinable()) { server_thread_.join(); }
  21489. }
  21490. void setup_server() {
  21491. // Simple SSE endpoint
  21492. server_->Get("/events", [this](const Request &req, Response &res) {
  21493. auto last_id = req.get_header_value("Last-Event-ID");
  21494. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21495. res.set_chunked_content_provider(
  21496. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21497. std::unique_lock<std::mutex> lock(event_mutex_);
  21498. if (event_cv_.wait_for(
  21499. lock, std::chrono::milliseconds(200), [this] {
  21500. return !events_.empty() || stop_server_.load();
  21501. })) {
  21502. if (stop_server_.load()) { return false; }
  21503. if (!events_.empty()) {
  21504. std::string event = events_.front();
  21505. events_.erase(events_.begin());
  21506. sink.write(event.data(), event.size());
  21507. return true;
  21508. }
  21509. }
  21510. return !stop_server_.load();
  21511. });
  21512. });
  21513. // Endpoint that returns error
  21514. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21515. res.status = 500;
  21516. res.set_content("Internal Server Error", "text/plain");
  21517. });
  21518. // Endpoint for custom event types
  21519. server_->Get("/custom-events", [](const Request &, Response &res) {
  21520. res.set_chunked_content_provider(
  21521. "text/event-stream", [](size_t offset, DataSink &sink) {
  21522. if (offset == 0) {
  21523. std::string event = "event: update\ndata: updated\n\n"
  21524. "event: delete\ndata: deleted\n\n";
  21525. sink.write(event.data(), event.size());
  21526. }
  21527. return false; // End stream after sending
  21528. });
  21529. });
  21530. }
  21531. void start_server() {
  21532. port_ = server_->bind_to_any_port(HOST);
  21533. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21534. // Wait for server to start
  21535. while (!server_->is_running()) {
  21536. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21537. }
  21538. }
  21539. int get_port() const { return port_; }
  21540. void send_event(const std::string &event) {
  21541. std::lock_guard<std::mutex> lock(event_mutex_);
  21542. events_.push_back(event);
  21543. event_cv_.notify_all();
  21544. }
  21545. std::unique_ptr<Server> server_;
  21546. std::thread server_thread_;
  21547. std::mutex event_mutex_;
  21548. std::condition_variable event_cv_;
  21549. std::vector<std::string> events_;
  21550. std::atomic<bool> stop_server_{false};
  21551. std::string last_received_event_id_;
  21552. int port_ = 0;
  21553. };
  21554. //==============================================================================
  21555. // SSE Parsing Tests
  21556. //==============================================================================
  21557. class SSEParsingTest : public SSEIntegrationTest {
  21558. protected:
  21559. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21560. // A trailing sentinel event tells when the whole stream has been parsed.
  21561. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21562. auto body = stream + "event: end\ndata: end\n\n";
  21563. server_->Get("/parse", [body](const Request &, Response &res) {
  21564. res.set_content(body, "text/event-stream");
  21565. });
  21566. return collect("/parse");
  21567. }
  21568. // Runs SSEClient against path until an "end" event arrives and returns the
  21569. // messages dispatched before it
  21570. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21571. Client client(HOST, get_port());
  21572. sse::SSEClient sse(client, path);
  21573. std::mutex mutex;
  21574. std::condition_variable cv;
  21575. std::vector<sse::SSEMessage> messages;
  21576. auto done = false;
  21577. sse.on_message([&](const sse::SSEMessage &msg) {
  21578. std::lock_guard<std::mutex> lock(mutex);
  21579. // Ignore a replay from a reconnect that races with stop()
  21580. if (!done) { messages.push_back(msg); }
  21581. });
  21582. sse.on_event("end", [&](const sse::SSEMessage &) {
  21583. std::lock_guard<std::mutex> lock(mutex);
  21584. done = true;
  21585. cv.notify_all();
  21586. });
  21587. sse.set_reconnect_interval(100);
  21588. sse.start_async();
  21589. {
  21590. std::unique_lock<std::mutex> lock(mutex);
  21591. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21592. }
  21593. sse.stop();
  21594. EXPECT_TRUE(done);
  21595. return messages;
  21596. }
  21597. };
  21598. TEST_F(SSEParsingTest, SingleLineData) {
  21599. auto msgs = parse("data: hello\n\n");
  21600. ASSERT_EQ(msgs.size(), 1u);
  21601. EXPECT_EQ(msgs[0].data, "hello");
  21602. EXPECT_EQ(msgs[0].event, "message");
  21603. }
  21604. TEST_F(SSEParsingTest, MultiLineData) {
  21605. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21606. ASSERT_EQ(msgs.size(), 1u);
  21607. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21608. }
  21609. TEST_F(SSEParsingTest, CustomEventType) {
  21610. auto msgs = parse("event: update\ndata: payload\n\n");
  21611. ASSERT_EQ(msgs.size(), 1u);
  21612. EXPECT_EQ(msgs[0].event, "update");
  21613. EXPECT_EQ(msgs[0].data, "payload");
  21614. }
  21615. TEST_F(SSEParsingTest, EventIdHandling) {
  21616. auto msgs = parse("id: 12345\ndata: test\n\n");
  21617. ASSERT_EQ(msgs.size(), 1u);
  21618. EXPECT_EQ(msgs[0].id, "12345");
  21619. }
  21620. TEST_F(SSEParsingTest, EmptyEventId) {
  21621. auto msgs = parse("id:\ndata: test\n\n");
  21622. ASSERT_EQ(msgs.size(), 1u);
  21623. EXPECT_EQ(msgs[0].id, "");
  21624. }
  21625. TEST_F(SSEParsingTest, CommentsIgnored) {
  21626. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21627. ASSERT_EQ(msgs.size(), 1u);
  21628. EXPECT_EQ(msgs[0].data, "hello");
  21629. EXPECT_EQ(msgs[0].event, "message");
  21630. }
  21631. TEST_F(SSEParsingTest, ColonInValue) {
  21632. auto msgs = parse("data: hello:world:test\n\n");
  21633. ASSERT_EQ(msgs.size(), 1u);
  21634. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21635. }
  21636. TEST_F(SSEParsingTest, FieldNameOnly) {
  21637. // A line without a colon is a field name with an empty value
  21638. auto msgs = parse("data\n\n");
  21639. ASSERT_EQ(msgs.size(), 1u);
  21640. EXPECT_EQ(msgs[0].data, "");
  21641. }
  21642. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21643. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21644. ASSERT_EQ(msgs.size(), 1u);
  21645. EXPECT_EQ(msgs[0].event, "update");
  21646. EXPECT_EQ(msgs[0].data, "hello");
  21647. }
  21648. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21649. auto msgs = parse("data\r\n\r\n");
  21650. ASSERT_EQ(msgs.size(), 1u);
  21651. EXPECT_EQ(msgs[0].data, "");
  21652. }
  21653. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21654. auto msgs = parse("event: update\rdata: hello\r\r");
  21655. ASSERT_EQ(msgs.size(), 1u);
  21656. EXPECT_EQ(msgs[0].event, "update");
  21657. EXPECT_EQ(msgs[0].data, "hello");
  21658. }
  21659. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21660. // Chunk boundaries fall inside every \r\n and right before the first one
  21661. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21662. "\n\r", "\nevent: end\ndata: end\n\n"};
  21663. server_->Get("/split", [chunks](const Request &, Response &res) {
  21664. auto i = std::make_shared<size_t>(0);
  21665. res.set_chunked_content_provider(
  21666. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21667. if (*i == chunks.size()) {
  21668. sink.done();
  21669. } else {
  21670. sink.write(chunks[*i].data(), chunks[*i].size());
  21671. (*i)++;
  21672. }
  21673. return true;
  21674. });
  21675. });
  21676. auto msgs = collect("/split");
  21677. ASSERT_EQ(msgs.size(), 1u);
  21678. EXPECT_EQ(msgs[0].event, "update");
  21679. EXPECT_EQ(msgs[0].data, "hello");
  21680. }
  21681. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21682. // Only a BOM at the start of the stream is ignored
  21683. auto msgs = parse("\xEF\xBB\xBF"
  21684. "data: first\n\n"
  21685. "\xEF\xBB\xBF"
  21686. "data: second\n\n");
  21687. ASSERT_EQ(msgs.size(), 1u);
  21688. EXPECT_EQ(msgs[0].data, "first");
  21689. }
  21690. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21691. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21692. ASSERT_EQ(msgs.size(), 1u);
  21693. EXPECT_EQ(msgs[0].data, "hello");
  21694. EXPECT_EQ(msgs[0].event, "message");
  21695. }
  21696. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21697. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21698. ASSERT_EQ(msgs.size(), 2u);
  21699. EXPECT_EQ(msgs[0].data, "hello");
  21700. EXPECT_EQ(msgs[1].data, "hello");
  21701. }
  21702. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21703. // An event without data is not dispatched, and its type must not leak
  21704. // into the next event
  21705. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21706. ASSERT_EQ(msgs.size(), 1u);
  21707. EXPECT_EQ(msgs[0].event, "message");
  21708. EXPECT_EQ(msgs[0].data, "hello");
  21709. }
  21710. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21711. // Also when the empty field replaces an earlier type
  21712. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21713. ASSERT_EQ(msgs.size(), 2u);
  21714. EXPECT_EQ(msgs[0].event, "message");
  21715. EXPECT_EQ(msgs[1].event, "message");
  21716. }
  21717. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21718. // The first connection sends only an id; the second echoes back the
  21719. // Last-Event-ID it was reconnected with
  21720. std::atomic<int> connection_count{0};
  21721. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21722. if (connection_count++ == 0) {
  21723. res.set_content("id: 42\n\n", "text/event-stream");
  21724. } else {
  21725. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21726. "\n\nevent: end\ndata: end\n\n",
  21727. "text/event-stream");
  21728. }
  21729. });
  21730. auto msgs = collect("/id-only");
  21731. ASSERT_EQ(msgs.size(), 1u);
  21732. EXPECT_EQ(msgs[0].data, "42");
  21733. }
  21734. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21735. // The first connection sets an id and then clears it with an empty one; the
  21736. // second reports whether it was reconnected with a Last-Event-ID
  21737. std::atomic<int> connection_count{0};
  21738. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21739. if (connection_count++ == 0) {
  21740. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21741. "text/event-stream");
  21742. } else {
  21743. res.set_content(
  21744. std::string("data: ") +
  21745. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21746. "\n\nevent: end\ndata: end\n\n",
  21747. "text/event-stream");
  21748. }
  21749. });
  21750. auto msgs = collect("/id-clear");
  21751. ASSERT_EQ(msgs.size(), 3u);
  21752. EXPECT_EQ(msgs[0].id, "1");
  21753. EXPECT_EQ(msgs[1].id, "");
  21754. EXPECT_EQ(msgs[2].data, "not sent");
  21755. }
  21756. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21757. // The first connection sets an id and then sends ids that cannot be carried
  21758. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21759. // with
  21760. std::atomic<int> connection_count{0};
  21761. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21762. if (connection_count++ == 0) {
  21763. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21764. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21765. "text/event-stream");
  21766. } else {
  21767. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21768. "\n\nevent: end\ndata: end\n\n",
  21769. "text/event-stream");
  21770. }
  21771. });
  21772. auto msgs = collect("/id-unsendable");
  21773. ASSERT_EQ(msgs.size(), 1u);
  21774. EXPECT_EQ(msgs[0].data, "42");
  21775. }
  21776. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21777. auto msgs = parse("event: notification\nid: evt-42\n"
  21778. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21779. ASSERT_EQ(msgs.size(), 1u);
  21780. EXPECT_EQ(msgs[0].event, "notification");
  21781. EXPECT_EQ(msgs[0].id, "evt-42");
  21782. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21783. }
  21784. TEST(SSEMessageTest, Clear) {
  21785. sse::SSEMessage msg;
  21786. msg.event = "custom";
  21787. msg.data = "some data";
  21788. msg.id = "123";
  21789. msg.clear();
  21790. EXPECT_EQ(msg.event, "message");
  21791. EXPECT_EQ(msg.data, "");
  21792. EXPECT_EQ(msg.id, "");
  21793. }
  21794. //==============================================================================
  21795. // SSE Integration Tests
  21796. //==============================================================================
  21797. // Test: Successful connection and on_open callback
  21798. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21799. // Add a simple endpoint that sends one event and closes
  21800. server_->Get("/simple-event", [](const Request &, Response &res) {
  21801. res.set_chunked_content_provider(
  21802. "text/event-stream", [](size_t offset, DataSink &sink) {
  21803. if (offset == 0) {
  21804. std::string event = "data: hello\n\n";
  21805. sink.write(event.data(), event.size());
  21806. }
  21807. return false; // Close stream after sending
  21808. });
  21809. });
  21810. Client client("localhost", get_port());
  21811. sse::SSEClient sse(client, "/simple-event");
  21812. std::atomic<bool> open_called{false};
  21813. std::atomic<bool> message_received{false};
  21814. sse.on_open([&open_called]() { open_called.store(true); });
  21815. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21816. if (msg.data == "hello") { message_received.store(true); }
  21817. });
  21818. sse.set_reconnect_interval(100);
  21819. sse.set_max_reconnect_attempts(1);
  21820. // Start async
  21821. sse.start_async();
  21822. // Wait for message to be processed
  21823. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21824. sse.stop();
  21825. EXPECT_TRUE(open_called.load());
  21826. EXPECT_TRUE(message_received.load());
  21827. }
  21828. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21829. // A data line that never ends.
  21830. server_->Get("/endless-line", [](const Request &, Response &res) {
  21831. res.set_chunked_content_provider(
  21832. "text/event-stream", [](size_t offset, DataSink &sink) {
  21833. if (offset == 0) { sink.write("data: ", 6); }
  21834. std::string chunk(64 * 1024, 'A');
  21835. return sink.write(chunk.data(), chunk.size());
  21836. });
  21837. });
  21838. Client client("localhost", get_port());
  21839. sse::SSEClient sse(client, "/endless-line");
  21840. std::atomic<bool> too_long{false};
  21841. sse.on_error([&](Error err) {
  21842. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21843. });
  21844. sse.set_max_reconnect_attempts(1);
  21845. sse.start_async();
  21846. for (int i = 0; i < 500 && !too_long; i++) {
  21847. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21848. }
  21849. sse.stop();
  21850. EXPECT_TRUE(too_long);
  21851. }
  21852. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21853. // Far more in all than the client's payload limit below.
  21854. server_->Get("/many-events", [](const Request &, Response &res) {
  21855. res.set_chunked_content_provider(
  21856. "text/event-stream", [](size_t offset, DataSink &sink) {
  21857. if (offset == 0) {
  21858. std::string events;
  21859. for (int i = 0; i < 1000; i++) {
  21860. events += "data: message\n\n";
  21861. }
  21862. sink.write(events.data(), events.size());
  21863. }
  21864. return false;
  21865. });
  21866. });
  21867. Client client("localhost", get_port());
  21868. client.set_payload_max_length(1024);
  21869. sse::SSEClient sse(client, "/many-events");
  21870. std::atomic<int> messages{0};
  21871. std::atomic<bool> too_large{false};
  21872. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21873. sse.on_error([&](Error err) {
  21874. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21875. });
  21876. sse.set_max_reconnect_attempts(1);
  21877. sse.start_async();
  21878. for (int i = 0; i < 500 && messages < 1000; i++) {
  21879. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21880. }
  21881. sse.stop();
  21882. EXPECT_GE(messages.load(), 1000);
  21883. EXPECT_FALSE(too_large);
  21884. }
  21885. // Test: on_message callback
  21886. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21887. // Endpoint that sends multiple events then closes
  21888. server_->Get("/multi-event", [](const Request &, Response &res) {
  21889. res.set_chunked_content_provider(
  21890. "text/event-stream", [](size_t offset, DataSink &sink) {
  21891. if (offset == 0) {
  21892. std::string events = "data: message1\n\ndata: message2\n\n";
  21893. sink.write(events.data(), events.size());
  21894. }
  21895. return false;
  21896. });
  21897. });
  21898. Client client("localhost", get_port());
  21899. sse::SSEClient sse(client, "/multi-event");
  21900. std::vector<std::string> received_messages;
  21901. std::mutex messages_mutex;
  21902. sse.on_message([&](const sse::SSEMessage &msg) {
  21903. std::lock_guard<std::mutex> lock(messages_mutex);
  21904. received_messages.push_back(msg.data);
  21905. });
  21906. sse.set_reconnect_interval(100);
  21907. sse.set_max_reconnect_attempts(1);
  21908. sse.start_async();
  21909. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21910. sse.stop();
  21911. std::lock_guard<std::mutex> lock(messages_mutex);
  21912. EXPECT_GE(received_messages.size(), 2u);
  21913. if (received_messages.size() >= 2) {
  21914. EXPECT_EQ(received_messages[0], "message1");
  21915. EXPECT_EQ(received_messages[1], "message2");
  21916. }
  21917. }
  21918. // Test: on_event for specific types
  21919. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21920. Client client("localhost", get_port());
  21921. sse::SSEClient sse(client, "/custom-events");
  21922. std::atomic<bool> update_received{false};
  21923. std::atomic<bool> delete_received{false};
  21924. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21925. if (msg.data == "updated") { update_received.store(true); }
  21926. });
  21927. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21928. if (msg.data == "deleted") { delete_received.store(true); }
  21929. });
  21930. sse.set_max_reconnect_attempts(1);
  21931. sse.start_async();
  21932. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21933. sse.stop();
  21934. EXPECT_TRUE(update_received.load());
  21935. EXPECT_TRUE(delete_received.load());
  21936. }
  21937. // Test: on_error callback on connection failure
  21938. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21939. // Connect to a non-existent port
  21940. Client client("localhost", 59999);
  21941. sse::SSEClient sse(client, "/events");
  21942. std::atomic<bool> error_called{false};
  21943. Error received_error = Error::Success;
  21944. sse.on_error([&](Error err) {
  21945. error_called.store(true);
  21946. received_error = err;
  21947. });
  21948. sse.set_reconnect_interval(50);
  21949. sse.set_max_reconnect_attempts(1);
  21950. sse.start_async();
  21951. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21952. sse.stop();
  21953. EXPECT_TRUE(error_called.load());
  21954. EXPECT_NE(received_error, Error::Success);
  21955. }
  21956. // Test: Last-Event-ID header sent on reconnect
  21957. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21958. // Endpoint that sends event with ID
  21959. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21960. res.set_chunked_content_provider(
  21961. "text/event-stream", [](size_t offset, DataSink &sink) {
  21962. if (offset == 0) {
  21963. std::string event = "id: evt-123\ndata: test\n\n";
  21964. sink.write(event.data(), event.size());
  21965. }
  21966. return false;
  21967. });
  21968. });
  21969. Client client("localhost", get_port());
  21970. sse::SSEClient sse(client, "/event-with-id");
  21971. std::atomic<bool> id_received{false};
  21972. sse.on_message([&](const sse::SSEMessage &msg) {
  21973. if (!msg.id.empty()) { id_received.store(true); }
  21974. });
  21975. sse.set_reconnect_interval(100);
  21976. sse.set_max_reconnect_attempts(1);
  21977. sse.start_async();
  21978. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21979. sse.stop();
  21980. EXPECT_TRUE(id_received.load());
  21981. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21982. }
  21983. // Test: Manual stop
  21984. TEST_F(SSEIntegrationTest, ManualStop) {
  21985. // Endpoint that sends one event and stays open briefly. The server outlives
  21986. // this test body, so the provider uses the fixture's flag, not a local.
  21987. server_->Get("/stay-open", [this](const Request &, Response &res) {
  21988. res.set_chunked_content_provider(
  21989. "text/event-stream", [this](size_t offset, DataSink &sink) {
  21990. if (offset == 0) {
  21991. std::string event = "data: connected\n\n";
  21992. sink.write(event.data(), event.size());
  21993. }
  21994. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  21995. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21996. }
  21997. return false;
  21998. });
  21999. });
  22000. Client client("localhost", get_port());
  22001. sse::SSEClient sse(client, "/stay-open");
  22002. std::atomic<bool> connected{false};
  22003. sse.on_open([&connected]() { connected.store(true); });
  22004. sse.set_reconnect_interval(100);
  22005. sse.set_max_reconnect_attempts(1);
  22006. sse.start_async();
  22007. // Wait for connection to establish
  22008. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22009. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22010. }
  22011. EXPECT_TRUE(connected.load());
  22012. EXPECT_TRUE(sse.is_connected());
  22013. // Signal handler to stop
  22014. stop_server_.store(true);
  22015. // Stop SSE client
  22016. sse.stop();
  22017. EXPECT_FALSE(sse.is_connected());
  22018. }
  22019. // Sends one event, then nothing until stop is set
  22020. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22021. return [&stop](const Request &, Response &res) {
  22022. res.set_chunked_content_provider(
  22023. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22024. if (offset == 0) {
  22025. std::string event = "data: hello\n\n";
  22026. sink.write(event.data(), event.size());
  22027. }
  22028. while (!stop.load()) {
  22029. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22030. }
  22031. return false;
  22032. });
  22033. };
  22034. }
  22035. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22036. static void check_stop_interrupts_blocked_read(Client &client) {
  22037. client.set_read_timeout(30, 0);
  22038. for (auto by_destructor : {false, true}) {
  22039. std::atomic<bool> received{false};
  22040. std::chrono::steady_clock::time_point start;
  22041. {
  22042. sse::SSEClient sse(client, "/idle-stream");
  22043. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22044. sse.start_async();
  22045. for (int i = 0; i < 500 && !received.load(); ++i) {
  22046. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22047. }
  22048. ASSERT_TRUE(received.load());
  22049. // Let the client block in the next read
  22050. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22051. start = std::chrono::steady_clock::now();
  22052. if (!by_destructor) { sse.stop(); }
  22053. }
  22054. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22055. std::chrono::seconds(2));
  22056. }
  22057. }
  22058. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22059. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22060. Client client("localhost", get_port());
  22061. check_stop_interrupts_blocked_read(client);
  22062. }
  22063. #ifdef CPPHTTPLIB_SSL_ENABLED
  22064. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22066. std::atomic<bool> done{false};
  22067. svr.Get("/idle-stream", idle_event_stream(done));
  22068. auto port = svr.bind_to_any_port(HOST);
  22069. std::thread t([&] { svr.listen_after_bind(); });
  22070. auto se = detail::scope_exit([&] {
  22071. done.store(true);
  22072. svr.stop();
  22073. t.join();
  22074. });
  22075. svr.wait_until_ready();
  22076. Client client("https://localhost:" + std::to_string(port));
  22077. client.enable_server_certificate_verification(false);
  22078. check_stop_interrupts_blocked_read(client);
  22079. }
  22080. #endif
  22081. // Test: SSEClient with custom headers
  22082. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22083. // Setup a server endpoint that checks for custom header
  22084. std::atomic<bool> header_received{false};
  22085. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22086. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22087. header_received.store(true);
  22088. }
  22089. res.set_chunked_content_provider("text/event-stream",
  22090. [](size_t, DataSink &) { return false; });
  22091. });
  22092. Client client("localhost", get_port());
  22093. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22094. sse::SSEClient sse(client, "/header-check", headers);
  22095. sse.set_max_reconnect_attempts(1);
  22096. sse.start_async();
  22097. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22098. sse.stop();
  22099. EXPECT_TRUE(header_received.load());
  22100. }
  22101. // Test: Reconnect interval configuration
  22102. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22103. Client client("localhost", get_port());
  22104. sse::SSEClient sse(client, "/events");
  22105. auto &result = sse.set_reconnect_interval(500);
  22106. // Builder pattern should return reference to self
  22107. EXPECT_EQ(&result, &sse);
  22108. }
  22109. // Test: Max reconnect attempts
  22110. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22111. // Connect to non-existent port to force reconnects
  22112. Client client("localhost", 59998);
  22113. sse::SSEClient sse(client, "/events");
  22114. std::atomic<int> error_count{0};
  22115. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22116. sse.set_reconnect_interval(50);
  22117. sse.set_max_reconnect_attempts(2);
  22118. auto start = std::chrono::steady_clock::now();
  22119. sse.start(); // Blocking call
  22120. auto end = std::chrono::steady_clock::now();
  22121. // Should have stopped after 2 failed attempts
  22122. EXPECT_GE(error_count.load(), 2);
  22123. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22124. auto duration =
  22125. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22126. #ifdef _WIN32
  22127. // Windows is much slower for socket connection failures
  22128. EXPECT_LT(duration.count(), 7000);
  22129. #else
  22130. EXPECT_LT(duration.count(), 1000);
  22131. #endif
  22132. }
  22133. // Test: Multi-line data in integration
  22134. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22135. // Endpoint with multi-line data
  22136. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22137. res.set_chunked_content_provider(
  22138. "text/event-stream", [](size_t offset, DataSink &sink) {
  22139. if (offset == 0) {
  22140. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22141. sink.write(event.data(), event.size());
  22142. }
  22143. return false;
  22144. });
  22145. });
  22146. Client client("localhost", get_port());
  22147. sse::SSEClient sse(client, "/multiline-data");
  22148. std::string received_data;
  22149. std::mutex data_mutex;
  22150. sse.on_message([&](const sse::SSEMessage &msg) {
  22151. std::lock_guard<std::mutex> lock(data_mutex);
  22152. received_data = msg.data;
  22153. });
  22154. sse.set_reconnect_interval(100);
  22155. sse.set_max_reconnect_attempts(1);
  22156. sse.start_async();
  22157. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22158. sse.stop();
  22159. std::lock_guard<std::mutex> lock(data_mutex);
  22160. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22161. }
  22162. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22163. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22164. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22165. DataSink &sink) {
  22166. if (offset == 0) {
  22167. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22168. sink.write(events.data(), events.size());
  22169. }
  22170. return false;
  22171. });
  22172. });
  22173. Client client("localhost", get_port());
  22174. sse::SSEClient sse(client, "/empty-data-lines");
  22175. std::mutex mutex;
  22176. std::condition_variable cv;
  22177. std::vector<std::string> received;
  22178. sse.on_message([&](const sse::SSEMessage &msg) {
  22179. std::lock_guard<std::mutex> lock(mutex);
  22180. received.push_back(msg.data);
  22181. cv.notify_all();
  22182. });
  22183. sse.set_max_reconnect_attempts(1);
  22184. sse.start_async();
  22185. {
  22186. std::unique_lock<std::mutex> lock(mutex);
  22187. cv.wait_for(lock, std::chrono::seconds(2),
  22188. [&] { return received.size() >= 3; });
  22189. }
  22190. sse.stop();
  22191. ASSERT_GE(received.size(), 3u);
  22192. EXPECT_EQ(received[0], "");
  22193. EXPECT_EQ(received[1], "\nhello");
  22194. EXPECT_EQ(received[2], "");
  22195. }
  22196. // Test: Auto-reconnect after server disconnection
  22197. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22198. std::atomic<int> connection_count{0};
  22199. std::atomic<int> message_count{0};
  22200. // Endpoint that sends one event and closes, forcing reconnect
  22201. server_->Get("/reconnect-test",
  22202. [&connection_count](const Request &, Response &res) {
  22203. connection_count.fetch_add(1);
  22204. res.set_chunked_content_provider(
  22205. "text/event-stream", [](size_t offset, DataSink &sink) {
  22206. if (offset == 0) {
  22207. std::string event = "data: hello\n\n";
  22208. sink.write(event.data(), event.size());
  22209. }
  22210. return false; // Close connection after sending
  22211. });
  22212. });
  22213. Client client("localhost", get_port());
  22214. sse::SSEClient sse(client, "/reconnect-test");
  22215. sse.on_message([&message_count](const sse::SSEMessage &) {
  22216. message_count.fetch_add(1);
  22217. });
  22218. sse.set_reconnect_interval(100);
  22219. sse.set_max_reconnect_attempts(3);
  22220. sse.start_async();
  22221. // Wait long enough for multiple reconnects
  22222. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22223. sse.stop();
  22224. // Should have connected multiple times (initial + reconnects)
  22225. EXPECT_GE(connection_count.load(), 2);
  22226. // Should have received messages from multiple connections
  22227. EXPECT_GE(message_count.load(), 2);
  22228. }
  22229. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22230. std::atomic<int> connection_count{0};
  22231. // Neither Content-Length nor chunked: the close ends the stream
  22232. server_->Get("/close-delimited",
  22233. [&connection_count](const Request &, Response &res) {
  22234. connection_count.fetch_add(1);
  22235. res.set_content_provider(
  22236. "text/event-stream", [](size_t offset, DataSink &sink) {
  22237. if (offset == 0) {
  22238. std::string event = "data: hello\n\n";
  22239. sink.write(event.data(), event.size());
  22240. } else {
  22241. sink.done();
  22242. }
  22243. return true;
  22244. });
  22245. });
  22246. Client client("localhost", get_port());
  22247. sse::SSEClient sse(client, "/close-delimited");
  22248. std::atomic<int> error_count{0};
  22249. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22250. sse.set_reconnect_interval(100);
  22251. sse.start_async();
  22252. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22253. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22254. }
  22255. sse.stop();
  22256. // Reconnects as after any end of the stream, but reports no error
  22257. EXPECT_GE(connection_count.load(), 2);
  22258. EXPECT_EQ(0, error_count.load());
  22259. }
  22260. // Test: A retry field that is not all ASCII digits is ignored
  22261. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22262. std::atomic<int> connection_count{0};
  22263. server_->Get("/bad-retry",
  22264. [&connection_count](const Request &, Response &res) {
  22265. connection_count.fetch_add(1);
  22266. res.set_chunked_content_provider(
  22267. "text/event-stream", [](size_t offset, DataSink &sink) {
  22268. if (offset == 0) {
  22269. std::string event = "retry: -1\ndata: hello\n\n";
  22270. sink.write(event.data(), event.size());
  22271. }
  22272. return false;
  22273. });
  22274. });
  22275. Client client("localhost", get_port());
  22276. sse::SSEClient sse(client, "/bad-retry");
  22277. sse.set_reconnect_interval(10000);
  22278. sse.start_async();
  22279. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22280. sse.stop();
  22281. EXPECT_EQ(connection_count.load(), 1);
  22282. }
  22283. // Test: A retry field of all ASCII digits sets the reconnection time
  22284. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22285. std::mutex mutex;
  22286. std::condition_variable cv;
  22287. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22288. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22289. {
  22290. std::lock_guard<std::mutex> lock(mutex);
  22291. connected_at.push_back(std::chrono::steady_clock::now());
  22292. cv.notify_all();
  22293. }
  22294. res.set_chunked_content_provider(
  22295. "text/event-stream", [](size_t offset, DataSink &sink) {
  22296. if (offset == 0) {
  22297. std::string event = "retry: 0\ndata: hello\n\n";
  22298. sink.write(event.data(), event.size());
  22299. }
  22300. return false;
  22301. });
  22302. });
  22303. Client client("localhost", get_port());
  22304. sse::SSEClient sse(client, "/zero-retry");
  22305. sse.set_reconnect_interval(10000);
  22306. sse.start_async();
  22307. {
  22308. std::unique_lock<std::mutex> lock(mutex);
  22309. cv.wait_for(lock, std::chrono::seconds(5),
  22310. [&] { return connected_at.size() >= 2; });
  22311. }
  22312. sse.stop();
  22313. // The server-supplied interval is applied, but never below 100ms, so
  22314. // "retry: 0" does not cause a busy reconnect loop
  22315. std::lock_guard<std::mutex> lock(mutex);
  22316. ASSERT_GE(connected_at.size(), 2u);
  22317. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22318. connected_at[1] - connected_at[0])
  22319. .count();
  22320. EXPECT_GE(interval_ms, 100);
  22321. }
  22322. // Test: Last-Event-ID sent on reconnect
  22323. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22324. std::atomic<int> connection_count{0};
  22325. std::vector<std::string> received_last_event_ids;
  22326. std::mutex id_mutex;
  22327. // Endpoint that checks Last-Event-ID header and sends event with ID
  22328. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22329. int conn = connection_count.fetch_add(1);
  22330. // Capture the Last-Event-ID header from each connection
  22331. {
  22332. std::lock_guard<std::mutex> lock(id_mutex);
  22333. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22334. }
  22335. res.set_chunked_content_provider(
  22336. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22337. if (offset == 0) {
  22338. std::string event =
  22339. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22340. sink.write(event.data(), event.size());
  22341. }
  22342. return false;
  22343. });
  22344. });
  22345. Client client("localhost", get_port());
  22346. sse::SSEClient sse(client, "/reconnect-with-id");
  22347. sse.set_reconnect_interval(100);
  22348. sse.set_max_reconnect_attempts(3);
  22349. sse.start_async();
  22350. // Wait for at least 2 connections
  22351. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22352. sse.stop();
  22353. // Verify behavior
  22354. std::lock_guard<std::mutex> lock(id_mutex);
  22355. EXPECT_GE(received_last_event_ids.size(), 2u);
  22356. // First connection should have no Last-Event-ID
  22357. if (!received_last_event_ids.empty()) {
  22358. EXPECT_EQ(received_last_event_ids[0], "");
  22359. }
  22360. // Second connection should have Last-Event-ID from first connection
  22361. if (received_last_event_ids.size() >= 2) {
  22362. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22363. }
  22364. }
  22365. // Test: set_headers updates headers used on reconnect
  22366. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22367. std::vector<std::string> received_tokens;
  22368. std::mutex token_mutex;
  22369. // Endpoint that captures Authorization header
  22370. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22371. {
  22372. std::lock_guard<std::mutex> lock(token_mutex);
  22373. received_tokens.push_back(req.get_header_value("Authorization"));
  22374. }
  22375. res.set_chunked_content_provider(
  22376. "text/event-stream", [](size_t offset, DataSink &sink) {
  22377. if (offset == 0) {
  22378. std::string event = "data: hello\n\n";
  22379. sink.write(event.data(), event.size());
  22380. }
  22381. return false; // Close connection to trigger reconnect
  22382. });
  22383. });
  22384. Client client("localhost", get_port());
  22385. Headers headers = {{"Authorization", "Bearer old-token"}};
  22386. sse::SSEClient sse(client, "/auth-check", headers);
  22387. // Update headers on each successful connection
  22388. sse.on_open(
  22389. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22390. sse.set_reconnect_interval(100);
  22391. sse.set_max_reconnect_attempts(3);
  22392. sse.start_async();
  22393. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22394. sse.stop();
  22395. std::lock_guard<std::mutex> lock(token_mutex);
  22396. ASSERT_GE(received_tokens.size(), 2u);
  22397. // First connection uses original header
  22398. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22399. // Second connection uses updated header from set_headers
  22400. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22401. }
  22402. // Test: 401 allows reconnection (so on_error can refresh headers)
  22403. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22404. std::atomic<int> connection_count{0};
  22405. // Endpoint: returns 401 on first attempt, 200 on second
  22406. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22407. int conn = connection_count.fetch_add(1);
  22408. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22409. res.status = StatusCode::Unauthorized_401;
  22410. res.set_content("Unauthorized", "text/plain");
  22411. return;
  22412. }
  22413. res.set_chunked_content_provider(
  22414. "text/event-stream", [](size_t offset, DataSink &sink) {
  22415. if (offset == 0) {
  22416. std::string event = "data: authenticated\n\n";
  22417. sink.write(event.data(), event.size());
  22418. }
  22419. return false;
  22420. });
  22421. });
  22422. Client client("localhost", get_port());
  22423. Headers headers = {{"Authorization", "Bearer expired"}};
  22424. sse::SSEClient sse(client, "/auth-retry", headers);
  22425. std::atomic<bool> message_received{false};
  22426. // Refresh token on error
  22427. sse.on_error(
  22428. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22429. sse.on_message([&](const sse::SSEMessage &msg) {
  22430. if (msg.data == "authenticated") { message_received.store(true); }
  22431. });
  22432. sse.set_reconnect_interval(100);
  22433. sse.set_max_reconnect_attempts(3);
  22434. sse.start_async();
  22435. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22436. sse.stop();
  22437. // Should have reconnected after 401 and succeeded with new token
  22438. EXPECT_GE(connection_count.load(), 2);
  22439. EXPECT_TRUE(message_received.load());
  22440. }
  22441. TEST(Issue2318Test, EmptyHostString) {
  22442. {
  22443. httplib::Client cli_empty("", PORT);
  22444. auto res = cli_empty.Get("/");
  22445. ASSERT_FALSE(res);
  22446. EXPECT_EQ(httplib::Error::Connection, res.error());
  22447. }
  22448. {
  22449. httplib::Client cli(" ", PORT);
  22450. auto res = cli.Get("/");
  22451. ASSERT_FALSE(res);
  22452. EXPECT_EQ(httplib::Error::Connection, res.error());
  22453. }
  22454. }
  22455. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22456. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22457. Server svr;
  22458. // Set a small payload limit (1KB)
  22459. svr.set_payload_max_length(1024);
  22460. svr.Post("/test", [&](const Request &req, Response &res) {
  22461. res.set_content("Body size: " + std::to_string(req.body.size()),
  22462. "text/plain");
  22463. });
  22464. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22465. auto se = detail::scope_exit([&] {
  22466. svr.stop();
  22467. listen_thread.join();
  22468. });
  22469. svr.wait_until_ready();
  22470. // Create data that compresses well but exceeds limit when decompressed
  22471. // 8KB of repeated null bytes compresses to a very small size
  22472. std::string original_data(8 * 1024, '\0');
  22473. // Compress the data using gzip
  22474. std::string compressed_data;
  22475. detail::gzip_compressor compressor;
  22476. compressor.compress(original_data.data(), original_data.size(), true,
  22477. [&](const char *data, size_t size) {
  22478. compressed_data.append(data, size);
  22479. return true;
  22480. });
  22481. // Verify compression worked (compressed should be much smaller)
  22482. ASSERT_LT(compressed_data.size(), original_data.size());
  22483. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22484. // Send compressed data with Content-Encoding: gzip
  22485. Client cli(HOST, PORT);
  22486. Headers headers = {{"Content-Encoding", "gzip"}};
  22487. auto res =
  22488. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22489. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22491. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22492. }
  22493. #endif
  22494. // ============================================================================
  22495. // OpenSSL-Specific Tests
  22496. // ============================================================================
  22497. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22498. X509 *readCertificate(const std::string &strFileName) {
  22499. std::ifstream inStream(strFileName);
  22500. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22501. std::istreambuf_iterator<char>());
  22502. if (strCertPEM.empty()) return (nullptr);
  22503. BIO *pbCert = BIO_new(BIO_s_mem());
  22504. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22505. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22506. BIO_free(pbCert);
  22507. return (pCert);
  22508. }
  22509. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22510. std::ifstream inStream(strFileName);
  22511. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22512. std::istreambuf_iterator<char>());
  22513. if (strPrivateKeyPEM.empty()) return (nullptr);
  22514. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22515. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22516. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22517. BIO_free(pbPrivKey);
  22518. return (pPrivateKey);
  22519. }
  22520. TEST(BindServerTest, UpdateCerts) {
  22521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22522. int port = svr.bind_to_any_port("0.0.0.0");
  22523. ASSERT_TRUE(svr.is_valid());
  22524. ASSERT_TRUE(port > 0);
  22525. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22526. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22527. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22528. ASSERT_TRUE(cert != nullptr);
  22529. ASSERT_TRUE(ca_cert != nullptr);
  22530. ASSERT_TRUE(key != nullptr);
  22531. X509_STORE *cert_store = X509_STORE_new();
  22532. X509_STORE_add_cert(cert_store, ca_cert);
  22533. // svr.update_certs(cert, key, cert_store); // deprecated
  22534. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22535. CLIENT_CA_CERT_FILE);
  22536. ASSERT_TRUE(svr.is_valid());
  22537. svr.stop();
  22538. X509_STORE_free(cert_store);
  22539. X509_free(cert);
  22540. X509_free(ca_cert);
  22541. EVP_PKEY_free(key);
  22542. }
  22543. // Test that update_certs() updates client CA list correctly
  22544. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22545. // Start with file-based constructor
  22546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22547. ASSERT_TRUE(svr.is_valid());
  22548. // Initially no client CA list should be set
  22549. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22550. ASSERT_TRUE(ssl_ctx != nullptr);
  22551. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22552. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22553. // Now update with client CA (PEM string)
  22554. std::string cert_pem, key_pem, ca_pem;
  22555. read_file(SERVER_CERT_FILE, cert_pem);
  22556. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22557. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22558. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22559. ASSERT_TRUE(svr.is_valid());
  22560. // Now client CA list should be set
  22561. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22562. ASSERT_TRUE(ca_list_after != nullptr);
  22563. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22564. }
  22565. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22566. // Test that the file-path SSLServer constructor properly sets the client CA
  22567. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22569. ASSERT_TRUE(svr.is_valid());
  22570. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22571. ASSERT_TRUE(ssl_ctx != nullptr);
  22572. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22573. ASSERT_TRUE(ca_list != nullptr);
  22574. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22575. }
  22576. #endif
  22577. // ============================================================================
  22578. // MbedTLS-Specific Tests
  22579. // ============================================================================
  22580. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22581. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22582. using namespace httplib::tls;
  22583. // Track if callback was invoked
  22584. bool callback_invoked = false;
  22585. // The callback receives void* ctx which is actually MbedTlsContext*
  22586. // We can access the mbedtls_ssl_config via the context
  22587. auto setup_callback = [&callback_invoked](void *ctx) {
  22588. callback_invoked = true;
  22589. // Cast to MbedTlsContext* to access the ssl config
  22590. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22591. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22592. // Use static variables to hold certificate data (simplified for test)
  22593. static mbedtls_x509_crt own_cert;
  22594. static mbedtls_pk_context own_key;
  22595. static mbedtls_x509_crt ca_chain;
  22596. static bool initialized = false;
  22597. if (!initialized) {
  22598. mbedtls_x509_crt_init(&own_cert);
  22599. mbedtls_pk_init(&own_key);
  22600. mbedtls_x509_crt_init(&ca_chain);
  22601. // Load server certificate
  22602. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22603. return false;
  22604. }
  22605. // Load server private key.
  22606. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22607. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22608. #if MBEDTLS_VERSION_MAJOR == 3
  22609. ,
  22610. mbedtls_ctr_drbg_random, nullptr
  22611. #endif
  22612. ) != 0) {
  22613. return false;
  22614. }
  22615. // Load CA chain for client verification
  22616. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22617. return false;
  22618. }
  22619. initialized = true;
  22620. }
  22621. // Configure the SSL config
  22622. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22623. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22624. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22625. // Set minimum TLS version using mbedTLS native API
  22626. #if MBEDTLS_VERSION_MAJOR >= 3
  22627. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22628. #else
  22629. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22630. MBEDTLS_SSL_MINOR_VERSION_3);
  22631. #endif
  22632. return true;
  22633. };
  22634. SSLServer svr(setup_callback);
  22635. ASSERT_TRUE(svr.is_valid());
  22636. ASSERT_TRUE(callback_invoked);
  22637. svr.Get("/test", [&](const Request &req, Response &res) {
  22638. res.set_content("test", "text/plain");
  22639. auto cert = req.peer_cert();
  22640. ASSERT_TRUE(static_cast<bool>(cert));
  22641. auto common_name = cert.subject_cn();
  22642. EXPECT_EQ("Common Name", common_name);
  22643. });
  22644. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22645. auto se = detail::scope_exit([&] {
  22646. svr.stop();
  22647. t.join();
  22648. ASSERT_FALSE(svr.is_running());
  22649. });
  22650. svr.wait_until_ready();
  22651. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22652. cli.enable_server_certificate_verification(false);
  22653. cli.set_connection_timeout(30);
  22654. auto res = cli.Get("/test");
  22655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22656. ASSERT_EQ(StatusCode::OK_200, res->status);
  22657. }
  22658. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22659. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22660. // keep-alive SSL session, which reads through that config in
  22661. // mbedtls_ssl_close_notify.
  22662. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22663. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22664. ASSERT_TRUE(svr.is_valid());
  22665. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22666. res.set_content("test", "text/plain");
  22667. });
  22668. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22669. auto se = detail::scope_exit([&] {
  22670. svr.stop();
  22671. t.join();
  22672. ASSERT_FALSE(svr.is_running());
  22673. });
  22674. svr.wait_until_ready();
  22675. {
  22676. SSLClient cli(HOST, PORT);
  22677. cli.enable_server_certificate_verification(false);
  22678. cli.set_keep_alive(true);
  22679. auto res = cli.Get("/test");
  22680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22681. ASSERT_EQ(StatusCode::OK_200, res->status);
  22682. // cli is destructed here with the keep-alive SSL session still open.
  22683. }
  22684. }
  22685. #endif
  22686. // WebSocket Tests
  22687. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22688. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22689. // defining the meaning of these bits has been negotiated.
  22690. auto make_frame = [](uint8_t first_byte) {
  22691. std::string frame;
  22692. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22693. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22694. frame += "Hello";
  22695. return frame;
  22696. };
  22697. // RSV1 set (0x40)
  22698. {
  22699. detail::BufferStream strm;
  22700. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22701. ws::Opcode opcode;
  22702. std::string payload;
  22703. bool fin;
  22704. EXPECT_EQ(
  22705. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22706. ws::impl::FrameRead::Fail);
  22707. }
  22708. // RSV2 set (0x20)
  22709. {
  22710. detail::BufferStream strm;
  22711. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22712. ws::Opcode opcode;
  22713. std::string payload;
  22714. bool fin;
  22715. EXPECT_EQ(
  22716. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22717. ws::impl::FrameRead::Fail);
  22718. }
  22719. // RSV3 set (0x10)
  22720. {
  22721. detail::BufferStream strm;
  22722. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22723. ws::Opcode opcode;
  22724. std::string payload;
  22725. bool fin;
  22726. EXPECT_EQ(
  22727. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22728. ws::impl::FrameRead::Fail);
  22729. }
  22730. // No RSV bits set - should succeed
  22731. {
  22732. detail::BufferStream strm;
  22733. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22734. ws::Opcode opcode;
  22735. std::string payload;
  22736. bool fin;
  22737. EXPECT_EQ(
  22738. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22739. ws::impl::FrameRead::Ok);
  22740. EXPECT_EQ(ws::Opcode::Text, opcode);
  22741. EXPECT_EQ("Hello", payload);
  22742. EXPECT_TRUE(fin);
  22743. }
  22744. }
  22745. TEST(WebSocketTest, ControlFrameValidation) {
  22746. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22747. // payload length <= 125.
  22748. // Ping with FIN=0 - must be rejected
  22749. {
  22750. detail::BufferStream strm;
  22751. std::string frame;
  22752. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22753. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22754. strm.write(frame.data(), frame.size());
  22755. ws::Opcode opcode;
  22756. std::string payload;
  22757. bool fin;
  22758. EXPECT_EQ(
  22759. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22760. ws::impl::FrameRead::Fail);
  22761. }
  22762. // Close with FIN=0 - must be rejected
  22763. {
  22764. detail::BufferStream strm;
  22765. std::string frame;
  22766. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22767. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22768. strm.write(frame.data(), frame.size());
  22769. ws::Opcode opcode;
  22770. std::string payload;
  22771. bool fin;
  22772. EXPECT_EQ(
  22773. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22774. ws::impl::FrameRead::Fail);
  22775. }
  22776. // Ping with payload_len=126 (extended length) - must be rejected
  22777. {
  22778. detail::BufferStream strm;
  22779. std::string frame;
  22780. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22781. frame += static_cast<char>(126); // payload_len=126 (>125)
  22782. frame += static_cast<char>(0x00); // extended length high byte
  22783. frame += static_cast<char>(126); // extended length low byte
  22784. frame += std::string(126, 'x');
  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 FIN=1 and payload_len=125 - should succeed
  22794. {
  22795. detail::BufferStream strm;
  22796. std::string frame;
  22797. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22798. frame += static_cast<char>(125); // payload_len=125
  22799. frame += std::string(125, 'x');
  22800. strm.write(frame.data(), frame.size());
  22801. ws::Opcode opcode;
  22802. std::string payload;
  22803. bool fin;
  22804. EXPECT_EQ(
  22805. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22806. ws::impl::FrameRead::Ok);
  22807. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22808. EXPECT_EQ(125u, payload.size());
  22809. EXPECT_TRUE(fin);
  22810. }
  22811. }
  22812. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22813. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22814. // length MUST be 0.
  22815. // MSB set - must be rejected
  22816. {
  22817. detail::BufferStream strm;
  22818. std::string frame;
  22819. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22820. frame += static_cast<char>(127); // 64-bit extended length
  22821. frame += static_cast<char>(0x80); // MSB set (invalid)
  22822. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22823. strm.write(frame.data(), frame.size());
  22824. ws::Opcode opcode;
  22825. std::string payload;
  22826. bool fin;
  22827. EXPECT_EQ(
  22828. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22829. ws::impl::FrameRead::Fail);
  22830. }
  22831. // MSB clear - should pass length parsing (will be rejected by max_len,
  22832. // but that's a different check; use a small length to verify)
  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 += std::string(7, '\0'); // high bytes = 0
  22839. frame += static_cast<char>(0x03); // length = 3
  22840. frame += "abc";
  22841. strm.write(frame.data(), frame.size());
  22842. ws::Opcode opcode;
  22843. std::string payload;
  22844. bool fin;
  22845. EXPECT_EQ(
  22846. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22847. ws::impl::FrameRead::Ok);
  22848. EXPECT_EQ(ws::Opcode::Text, opcode);
  22849. EXPECT_EQ("abc", payload);
  22850. }
  22851. }
  22852. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22853. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22854. // Valid UTF-8
  22855. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22856. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22857. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22858. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22859. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22860. // Invalid UTF-8
  22861. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22862. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22863. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22864. EXPECT_FALSE(
  22865. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22866. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22867. }
  22868. TEST(WebSocketTest, ConnectAndDisconnect) {
  22869. Server svr;
  22870. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22871. std::string msg;
  22872. while (ws.read(msg)) {}
  22873. });
  22874. auto port = svr.bind_to_any_port(HOST);
  22875. std::thread t([&]() { svr.listen_after_bind(); });
  22876. svr.wait_until_ready();
  22877. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22878. auto res = client.connect();
  22879. ASSERT_TRUE(res);
  22880. EXPECT_EQ(Error::Success, res.error());
  22881. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22882. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22883. EXPECT_TRUE(client.is_open());
  22884. client.close();
  22885. EXPECT_FALSE(client.is_open());
  22886. svr.stop();
  22887. t.join();
  22888. }
  22889. TEST(WebSocketTest, ValidURL) {
  22890. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22891. EXPECT_TRUE(ws1.is_valid());
  22892. ws::WebSocketClient ws2("ws://example.com/path");
  22893. EXPECT_TRUE(ws2.is_valid());
  22894. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22895. EXPECT_TRUE(ws3.is_valid());
  22896. #ifdef CPPHTTPLIB_SSL_ENABLED
  22897. ws::WebSocketClient wss1("wss://example.com/path");
  22898. EXPECT_TRUE(wss1.is_valid());
  22899. ws::WebSocketClient wss2("wss://example.com:443/path");
  22900. EXPECT_TRUE(wss2.is_valid());
  22901. #endif
  22902. }
  22903. TEST(WebSocketTest, InvalidURL) {
  22904. // No scheme
  22905. ws::WebSocketClient ws1("localhost:8080/path");
  22906. EXPECT_FALSE(ws1.is_valid());
  22907. // No path
  22908. ws::WebSocketClient ws2("ws://localhost:8080");
  22909. EXPECT_FALSE(ws2.is_valid());
  22910. // Empty string
  22911. ws::WebSocketClient ws3("");
  22912. EXPECT_FALSE(ws3.is_valid());
  22913. // Missing host
  22914. ws::WebSocketClient ws4("ws://:8080/path");
  22915. EXPECT_FALSE(ws4.is_valid());
  22916. // Port number overflow — should not crash
  22917. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22918. EXPECT_FALSE(ws5.is_valid());
  22919. // Port out of range
  22920. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22921. EXPECT_FALSE(ws6.is_valid());
  22922. }
  22923. TEST(WebSocketTest, UnsupportedScheme) {
  22924. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22925. ws::WebSocketClient ws1("http://localhost:8080/path");
  22926. EXPECT_FALSE(ws1.is_valid());
  22927. ws::WebSocketClient ws2("https://localhost:8080/path");
  22928. EXPECT_FALSE(ws2.is_valid());
  22929. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22930. EXPECT_FALSE(ws3.is_valid());
  22931. #else
  22932. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22933. std::invalid_argument);
  22934. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22935. std::invalid_argument);
  22936. #endif
  22937. }
  22938. TEST(WebSocketTest, ConnectWhenInvalid) {
  22939. ws::WebSocketClient ws("not a valid url");
  22940. EXPECT_FALSE(ws.is_valid());
  22941. auto res = ws.connect();
  22942. EXPECT_FALSE(res);
  22943. EXPECT_EQ(Error::Connection, res.error());
  22944. EXPECT_EQ(-1, res.status());
  22945. }
  22946. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22947. // Grab a port that is free, then close it again so nothing listens there
  22948. Server svr;
  22949. auto port = svr.bind_to_any_port(HOST);
  22950. svr.stop();
  22951. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22952. auto res = client.connect();
  22953. ASSERT_FALSE(res);
  22954. EXPECT_EQ(Error::Connection, res.error());
  22955. EXPECT_EQ(-1, res.status());
  22956. }
  22957. TEST(WebSocketTest, DefaultPort) {
  22958. ws::WebSocketClient ws1("ws://example.com/path");
  22959. EXPECT_TRUE(ws1.is_valid());
  22960. // ws:// defaults to port 80 (verified by successful parse)
  22961. #ifdef CPPHTTPLIB_SSL_ENABLED
  22962. ws::WebSocketClient ws2("wss://example.com/path");
  22963. EXPECT_TRUE(ws2.is_valid());
  22964. // wss:// defaults to port 443 (verified by successful parse)
  22965. #endif
  22966. }
  22967. TEST(WebSocketTest, IPv6LiteralAddress) {
  22968. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22969. EXPECT_TRUE(ws1.is_valid());
  22970. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22971. EXPECT_TRUE(ws2.is_valid());
  22972. }
  22973. TEST(WebSocketTest, ComplexPath) {
  22974. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22975. EXPECT_TRUE(ws1.is_valid());
  22976. ws::WebSocketClient ws2("ws://localhost:8080/");
  22977. EXPECT_TRUE(ws2.is_valid());
  22978. }
  22979. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22980. Server svr;
  22981. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22982. std::string msg;
  22983. while (ws.read(msg)) {}
  22984. });
  22985. auto port = svr.bind_to_any_port(HOST);
  22986. std::thread t([&]() { svr.listen_after_bind(); });
  22987. svr.wait_until_ready();
  22988. auto another_host = "example.com";
  22989. auto wrong_ip = "192.0.2.1";
  22990. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22991. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22992. ASSERT_TRUE(client.connect());
  22993. EXPECT_TRUE(client.is_open());
  22994. client.close();
  22995. svr.stop();
  22996. t.join();
  22997. }
  22998. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22999. Server svr;
  23000. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23001. std::string msg;
  23002. while (ws.read(msg)) {}
  23003. });
  23004. auto port = svr.bind_to_any_port(HOST);
  23005. std::thread t([&]() { svr.listen_after_bind(); });
  23006. svr.wait_until_ready();
  23007. auto wrong_ip = "192.0.2.1";
  23008. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23009. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23010. client.set_connection_timeout(1);
  23011. client.set_read_timeout(1);
  23012. client.set_write_timeout(1);
  23013. EXPECT_FALSE(client.connect());
  23014. EXPECT_FALSE(client.is_open());
  23015. svr.stop();
  23016. t.join();
  23017. }
  23018. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23019. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23020. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23021. // (RFC 6761) is only a map key and the Host header value.
  23022. auto host = "target.invalid";
  23023. Server svr;
  23024. std::string received_host;
  23025. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23026. received_host = req.get_header_value("Host");
  23027. std::string msg;
  23028. while (ws.read(msg)) {}
  23029. });
  23030. auto port = svr.bind_to_any_port(HOST);
  23031. std::thread t([&]() { svr.listen_after_bind(); });
  23032. // ASSERT_* below returns from the test body, which would leave t joinable
  23033. // and make ~thread call std::terminate.
  23034. auto se = detail::scope_exit([&] {
  23035. svr.stop();
  23036. if (t.joinable()) { t.join(); }
  23037. });
  23038. svr.wait_until_ready();
  23039. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23040. std::to_string(port) + "/ws");
  23041. client.set_hostname_addr_map({{host, HOST}});
  23042. ASSERT_TRUE(client.connect());
  23043. EXPECT_TRUE(client.is_open());
  23044. client.close();
  23045. svr.stop();
  23046. t.join();
  23047. // The mapping only redirects the connection; the identity stays host_.
  23048. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23049. }
  23050. class WebSocketIntegrationTest : public ::testing::Test {
  23051. protected:
  23052. void SetUp() override {
  23053. server_ = httplib::detail::make_unique<Server>();
  23054. setup_server();
  23055. start_server();
  23056. }
  23057. void TearDown() override {
  23058. server_->stop();
  23059. if (server_thread_.joinable()) { server_thread_.join(); }
  23060. }
  23061. void setup_server() {
  23062. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23063. std::string msg;
  23064. ws::ReadResult ret;
  23065. while ((ret = ws.read(msg))) {
  23066. if (ret == ws::Binary) {
  23067. ws.send(msg.data(), msg.size());
  23068. } else {
  23069. ws.send(msg);
  23070. }
  23071. }
  23072. });
  23073. server_->WebSocket("/ws-echo-string",
  23074. [](const Request &, ws::WebSocket &ws) {
  23075. std::string msg;
  23076. while (ws.read(msg)) {
  23077. ws.send("echo: " + msg);
  23078. }
  23079. });
  23080. server_->WebSocket(
  23081. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23082. // Echo back request metadata
  23083. ws.send("path:" + req.path);
  23084. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23085. std::string msg;
  23086. while (ws.read(msg)) {}
  23087. });
  23088. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23089. std::string msg;
  23090. ws.read(msg); // wait for a message
  23091. ws.close();
  23092. });
  23093. server_->WebSocket("/ws-close-status",
  23094. [](const Request &, ws::WebSocket &ws) {
  23095. std::string msg;
  23096. ws.read(msg); // wait for a message
  23097. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23098. });
  23099. server_->WebSocket(
  23100. "/ws-subprotocol",
  23101. [](const Request &, ws::WebSocket &ws) {
  23102. std::string msg;
  23103. while (ws.read(msg)) {
  23104. ws.send(msg);
  23105. }
  23106. },
  23107. [](const std::vector<std::string> &protocols) -> std::string {
  23108. for (const auto &p : protocols) {
  23109. if (p == "graphql-ws") { return p; }
  23110. }
  23111. return "";
  23112. });
  23113. server_->WebSocket(
  23114. "/ws-subprotocol-unoffered",
  23115. [](const Request &, ws::WebSocket &ws) {
  23116. std::string msg;
  23117. while (ws.read(msg)) {
  23118. ws.send(msg);
  23119. }
  23120. },
  23121. [](const std::vector<std::string> &) -> std::string {
  23122. return "admin";
  23123. });
  23124. }
  23125. void start_server() {
  23126. port_ = server_->bind_to_any_port(HOST);
  23127. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23128. server_->wait_until_ready();
  23129. }
  23130. std::unique_ptr<Server> server_;
  23131. std::thread server_thread_;
  23132. int port_ = 0;
  23133. };
  23134. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23135. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23136. "/ws-echo");
  23137. ASSERT_TRUE(client.connect());
  23138. ASSERT_TRUE(client.is_open());
  23139. ASSERT_TRUE(client.send("Hello WebSocket"));
  23140. std::string msg;
  23141. EXPECT_EQ(ws::Text, client.read(msg));
  23142. EXPECT_EQ("Hello WebSocket", msg);
  23143. client.close();
  23144. }
  23145. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23146. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23147. "/ws-echo");
  23148. ASSERT_TRUE(client.connect());
  23149. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23150. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23151. std::string msg;
  23152. EXPECT_EQ(ws::Binary, client.read(msg));
  23153. EXPECT_EQ(binary_data, msg);
  23154. client.close();
  23155. }
  23156. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23157. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23158. "/ws-echo");
  23159. ASSERT_TRUE(client.connect());
  23160. for (int i = 0; i < 10; i++) {
  23161. auto text = "message " + std::to_string(i);
  23162. ASSERT_TRUE(client.send(text));
  23163. std::string msg;
  23164. ASSERT_TRUE(client.read(msg));
  23165. EXPECT_EQ(text, msg);
  23166. }
  23167. client.close();
  23168. }
  23169. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23170. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23171. "/ws-close");
  23172. ASSERT_TRUE(client.connect());
  23173. // Send a message to trigger the server to close
  23174. ASSERT_TRUE(client.send("trigger close"));
  23175. // The server will close, so read should return false
  23176. std::string msg;
  23177. EXPECT_FALSE(client.read(msg));
  23178. EXPECT_FALSE(client.is_open());
  23179. }
  23180. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23181. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23182. "/ws-echo");
  23183. ASSERT_TRUE(client.connect());
  23184. // 128KB message
  23185. std::string large_data(128 * 1024, 'X');
  23186. ASSERT_TRUE(client.send(large_data));
  23187. std::string msg;
  23188. ASSERT_TRUE(client.read(msg));
  23189. EXPECT_EQ(large_data, msg);
  23190. client.close();
  23191. }
  23192. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23193. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23194. "/ws-echo");
  23195. ASSERT_TRUE(client.connect());
  23196. const int num_threads = 4;
  23197. std::vector<std::thread> threads;
  23198. std::atomic<int> send_count{0};
  23199. for (int t = 0; t < num_threads; t++) {
  23200. threads.emplace_back([&client, &send_count, t]() {
  23201. for (int i = 0; i < 5; i++) {
  23202. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23203. if (client.send(text)) { send_count++; }
  23204. }
  23205. });
  23206. }
  23207. for (auto &th : threads) {
  23208. th.join();
  23209. }
  23210. int received = 0;
  23211. std::string msg;
  23212. while (received < send_count.load()) {
  23213. if (!client.read(msg)) { break; }
  23214. received++;
  23215. }
  23216. EXPECT_EQ(send_count.load(), received);
  23217. client.close();
  23218. }
  23219. TEST_F(WebSocketIntegrationTest, ReadString) {
  23220. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23221. "/ws-echo-string");
  23222. ASSERT_TRUE(client.connect());
  23223. ASSERT_TRUE(client.send("hello"));
  23224. std::string msg;
  23225. ASSERT_TRUE(client.read(msg));
  23226. EXPECT_EQ("echo: hello", msg);
  23227. ASSERT_TRUE(client.send("world"));
  23228. ASSERT_TRUE(client.read(msg));
  23229. EXPECT_EQ("echo: world", msg);
  23230. client.close();
  23231. }
  23232. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23233. Headers headers = {{"X-Test-Header", "test-value"}};
  23234. ws::WebSocketClient client(
  23235. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23236. ASSERT_TRUE(client.connect());
  23237. std::string msg;
  23238. ASSERT_TRUE(client.read(msg));
  23239. EXPECT_EQ("path:/ws-request-info", msg);
  23240. ASSERT_TRUE(client.read(msg));
  23241. EXPECT_EQ("header:test-value", msg);
  23242. client.close();
  23243. }
  23244. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23245. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23246. "/ws-echo");
  23247. client.set_read_timeout(1, 0); // 1 second
  23248. ASSERT_TRUE(client.connect());
  23249. // Don't send anything — server echo handler waits for a message, so read()
  23250. // should time out. The connection survives it: nothing was consumed.
  23251. std::string msg;
  23252. EXPECT_EQ(client.read(msg), ws::Timeout);
  23253. EXPECT_TRUE(client.is_open());
  23254. // And it is still usable afterwards.
  23255. EXPECT_TRUE(client.send("after timeout"));
  23256. EXPECT_EQ(client.read(msg), ws::Text);
  23257. EXPECT_EQ(msg, "after timeout");
  23258. }
  23259. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23260. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23261. "/ws-echo");
  23262. client.set_read_timeout(1, 0);
  23263. ASSERT_TRUE(client.connect());
  23264. ASSERT_TRUE(client.send("first"));
  23265. std::string msg;
  23266. ASSERT_EQ(client.read(msg), ws::Text);
  23267. ASSERT_EQ(msg, "first");
  23268. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23269. // not be used with a read timeout: it would reprocess the previous message.
  23270. EXPECT_EQ(client.read(msg), ws::Timeout);
  23271. EXPECT_EQ(msg, "first");
  23272. }
  23273. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23274. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23275. "/ws-echo");
  23276. ASSERT_TRUE(client.connect());
  23277. // Setting it once the connection is open reaches the live stream, not just
  23278. // the seed for the next connect().
  23279. client.set_read_timeout(1, 0);
  23280. std::string msg;
  23281. EXPECT_EQ(client.read(msg), ws::Timeout);
  23282. EXPECT_TRUE(client.is_open());
  23283. }
  23284. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23285. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23286. "/ws-echo");
  23287. client.set_read_timeout(5, 0);
  23288. ASSERT_TRUE(client.connect());
  23289. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23290. // The server should reject it and close the connection.
  23291. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23292. client.send(oversized);
  23293. // The server's read() should have failed due to payload limit,
  23294. // so our read() should return false (connection closed).
  23295. std::string msg;
  23296. EXPECT_FALSE(client.read(msg));
  23297. }
  23298. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23299. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23300. "/ws-echo");
  23301. client.set_read_timeout(10, 0);
  23302. ASSERT_TRUE(client.connect());
  23303. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23304. // This should succeed.
  23305. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23306. ASSERT_TRUE(client.send(at_limit));
  23307. std::string msg;
  23308. ASSERT_TRUE(client.read(msg));
  23309. EXPECT_EQ(at_limit.size(), msg.size());
  23310. client.close();
  23311. }
  23312. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23313. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23314. "/nonexistent");
  23315. auto res = client.connect();
  23316. EXPECT_FALSE(res);
  23317. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23318. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23319. EXPECT_FALSE(client.is_open());
  23320. }
  23321. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23322. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23323. "/ws-echo");
  23324. ASSERT_TRUE(client.connect());
  23325. ASSERT_TRUE(client.send(""));
  23326. std::string msg;
  23327. EXPECT_EQ(ws::Text, client.read(msg));
  23328. EXPECT_EQ("", msg);
  23329. client.close();
  23330. }
  23331. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23332. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23333. "/ws-echo");
  23334. // First connection
  23335. ASSERT_TRUE(client.connect());
  23336. ASSERT_TRUE(client.send("first"));
  23337. std::string msg;
  23338. ASSERT_TRUE(client.read(msg));
  23339. EXPECT_EQ("first", msg);
  23340. client.close();
  23341. EXPECT_FALSE(client.is_open());
  23342. // Reconnect using the same client object
  23343. ASSERT_TRUE(client.connect());
  23344. ASSERT_TRUE(client.is_open());
  23345. ASSERT_TRUE(client.send("second"));
  23346. ASSERT_TRUE(client.read(msg));
  23347. EXPECT_EQ("second", msg);
  23348. client.close();
  23349. }
  23350. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23351. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23352. "/ws-close-status");
  23353. ASSERT_TRUE(client.connect());
  23354. // Trigger the server to close with GoingAway status
  23355. ASSERT_TRUE(client.send("trigger"));
  23356. // read() should return false after receiving the close frame
  23357. std::string msg;
  23358. EXPECT_FALSE(client.read(msg));
  23359. EXPECT_FALSE(client.is_open());
  23360. }
  23361. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23362. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23363. "/ws-echo");
  23364. ASSERT_TRUE(client.connect());
  23365. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23366. EXPECT_FALSE(client.is_open());
  23367. }
  23368. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23369. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23370. ws::WebSocketClient client(
  23371. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23372. ASSERT_TRUE(client.connect());
  23373. // Server should have selected graphql-ws
  23374. EXPECT_EQ("graphql-ws", client.subprotocol());
  23375. client.close();
  23376. }
  23377. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23378. Headers headers;
  23379. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23380. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23381. ws::WebSocketClient client(
  23382. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23383. ASSERT_TRUE(client.connect());
  23384. // The offer on the second field line counts too, so graphql-ws is selected
  23385. EXPECT_EQ("graphql-ws", client.subprotocol());
  23386. client.close();
  23387. }
  23388. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23389. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23390. ws::WebSocketClient client(
  23391. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23392. ASSERT_TRUE(client.connect());
  23393. // Server should not have selected any subprotocol
  23394. EXPECT_TRUE(client.subprotocol().empty());
  23395. client.close();
  23396. }
  23397. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23398. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23399. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23400. "/ws-subprotocol-unoffered",
  23401. headers);
  23402. ASSERT_TRUE(client.connect());
  23403. EXPECT_TRUE(client.subprotocol().empty());
  23404. client.close();
  23405. }
  23406. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23407. // Connect without requesting any subprotocol
  23408. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23409. "/ws-subprotocol");
  23410. ASSERT_TRUE(client.connect());
  23411. EXPECT_TRUE(client.subprotocol().empty());
  23412. client.close();
  23413. }
  23414. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23415. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23416. "/ws-echo");
  23417. client.set_tcp_nodelay(true);
  23418. client.set_connection_timeout(3, 0);
  23419. bool socket_options_called = false;
  23420. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23421. ASSERT_TRUE(client.connect());
  23422. ASSERT_TRUE(client.is_open());
  23423. EXPECT_TRUE(socket_options_called);
  23424. ASSERT_TRUE(client.send("hello"));
  23425. std::string msg;
  23426. auto result = client.read(msg);
  23427. EXPECT_EQ(result, ws::ReadResult::Text);
  23428. EXPECT_EQ(msg, "hello");
  23429. client.close();
  23430. }
  23431. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23432. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23433. "/ws-echo");
  23434. client.set_connection_timeout(std::chrono::seconds(3));
  23435. client.set_write_timeout(std::chrono::seconds(3));
  23436. // A sub-second remainder exercises the seconds/microseconds split.
  23437. client.set_read_timeout(std::chrono::milliseconds(1500));
  23438. ASSERT_TRUE(client.connect());
  23439. auto start = std::chrono::steady_clock::now();
  23440. std::string msg;
  23441. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23442. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23443. std::chrono::steady_clock::now() - start)
  23444. .count();
  23445. // Above 1s so that dropping the microseconds half of the split fails here.
  23446. // Ignoring the setter altogether would not reach this line at all: a client
  23447. // waits forever by default.
  23448. EXPECT_GE(elapsed, 1400);
  23449. EXPECT_LT(elapsed, 30000);
  23450. }
  23451. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23452. Server svr;
  23453. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23454. if (!req.has_header("Authorization")) {
  23455. res.status = StatusCode::Unauthorized_401;
  23456. res.set_content("Unauthorized", "text/plain");
  23457. return Server::HandlerResponse::Handled;
  23458. }
  23459. return Server::HandlerResponse::Unhandled;
  23460. });
  23461. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23462. std::string msg;
  23463. while (ws.read(msg)) {
  23464. ws.send(msg);
  23465. }
  23466. });
  23467. auto port = svr.bind_to_any_port("localhost");
  23468. std::thread t([&]() { svr.listen_after_bind(); });
  23469. svr.wait_until_ready();
  23470. // Without Authorization header - should be rejected before upgrade
  23471. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23472. EXPECT_FALSE(client1.connect());
  23473. // The rejection is framed like any other HTTP response
  23474. {
  23475. Client cli("localhost", port);
  23476. Headers headers = {{"Upgrade", "websocket"},
  23477. {"Connection", "Upgrade"},
  23478. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23479. {"Sec-WebSocket-Version", "13"}};
  23480. auto res = cli.Get("/ws", headers);
  23481. ASSERT_TRUE(res);
  23482. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23483. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23484. EXPECT_EQ("Unauthorized", res->body);
  23485. }
  23486. // With Authorization header - should succeed
  23487. Headers headers = {{"Authorization", "Bearer token123"}};
  23488. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23489. headers);
  23490. ASSERT_TRUE(client2.connect());
  23491. ASSERT_TRUE(client2.send("hello"));
  23492. std::string msg;
  23493. ASSERT_TRUE(client2.read(msg));
  23494. EXPECT_EQ("hello", msg);
  23495. client2.close();
  23496. svr.stop();
  23497. t.join();
  23498. }
  23499. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23500. Server svr;
  23501. std::atomic<int> pre_routing_calls{0};
  23502. std::atomic<int> pre_request_calls{0};
  23503. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23504. pre_routing_calls++;
  23505. if (req.path == "/handled") {
  23506. res.set_content("handled", "text/plain");
  23507. return Server::HandlerResponse::Handled;
  23508. }
  23509. return Server::HandlerResponse::Unhandled;
  23510. });
  23511. svr.set_pre_request_handler([&](const Request &, Response &) {
  23512. pre_request_calls++;
  23513. return Server::HandlerResponse::Unhandled;
  23514. });
  23515. svr.Get("/http", [](const Request &, Response &res) {
  23516. res.set_content("http", "text/plain");
  23517. });
  23518. svr.WebSocket("/ws",
  23519. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23520. auto port = svr.bind_to_any_port("localhost");
  23521. std::thread t([&]() { svr.listen_after_bind(); });
  23522. auto se = detail::scope_exit([&] {
  23523. svr.stop();
  23524. t.join();
  23525. });
  23526. svr.wait_until_ready();
  23527. Headers upgrade = {{"Upgrade", "websocket"},
  23528. {"Connection", "Upgrade"},
  23529. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23530. {"Sec-WebSocket-Version", "13"}};
  23531. auto get = [&](const char *path) {
  23532. pre_routing_calls = 0;
  23533. return Client("localhost", port).Get(path, upgrade);
  23534. };
  23535. // No WebSocket route, but an HTTP one
  23536. auto res = get("/http");
  23537. ASSERT_TRUE(res);
  23538. EXPECT_EQ(StatusCode::OK_200, res->status);
  23539. EXPECT_EQ("http", res->body);
  23540. EXPECT_EQ(1, pre_routing_calls);
  23541. EXPECT_EQ(1, pre_request_calls);
  23542. // No route at all
  23543. res = get("/none");
  23544. ASSERT_TRUE(res);
  23545. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23546. EXPECT_EQ(1, pre_routing_calls);
  23547. // Answered by the pre-routing handler
  23548. res = get("/handled");
  23549. ASSERT_TRUE(res);
  23550. EXPECT_EQ(StatusCode::OK_200, res->status);
  23551. EXPECT_EQ("handled", res->body);
  23552. EXPECT_EQ(1, pre_routing_calls);
  23553. // A WebSocket route
  23554. pre_routing_calls = 0;
  23555. pre_request_calls = 0;
  23556. {
  23557. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23558. "/ws");
  23559. ASSERT_TRUE(client.connect());
  23560. std::string msg;
  23561. ASSERT_TRUE(client.read(msg));
  23562. EXPECT_EQ("ws", msg);
  23563. client.close();
  23564. }
  23565. EXPECT_EQ(1, pre_routing_calls);
  23566. EXPECT_EQ(1, pre_request_calls);
  23567. }
  23568. // An upgrade request answered by a hook leaves its body unread, so that body
  23569. // must not be served as the next request on the connection.
  23570. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23571. Server svr;
  23572. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23573. if (req.path == "/pre-routing") {
  23574. res.set_content("pre-routing", "text/plain");
  23575. return Server::HandlerResponse::Handled;
  23576. }
  23577. return Server::HandlerResponse::Unhandled;
  23578. });
  23579. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23580. if (req.matched_route == "/pre-request") {
  23581. res.set_content("pre-request", "text/plain");
  23582. return Server::HandlerResponse::Handled;
  23583. }
  23584. return Server::HandlerResponse::Unhandled;
  23585. });
  23586. svr.Get("/smuggled", [](const Request &, Response &res) {
  23587. res.set_content("smuggled", "text/plain");
  23588. });
  23589. svr.WebSocket("/pre-request",
  23590. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23591. auto port = svr.bind_to_any_port(HOST);
  23592. std::thread t([&]() { svr.listen_after_bind(); });
  23593. auto se = detail::scope_exit([&] {
  23594. svr.stop();
  23595. t.join();
  23596. });
  23597. svr.wait_until_ready();
  23598. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23599. for (auto path : {"/pre-routing", "/pre-request"}) {
  23600. std::string req = std::string("GET ") + path +
  23601. " HTTP/1.1\r\n"
  23602. "Host: localhost\r\n"
  23603. "Upgrade: websocket\r\n"
  23604. "Connection: Upgrade\r\n"
  23605. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23606. "Sec-WebSocket-Version: 13\r\n"
  23607. "Content-Length: " +
  23608. std::to_string(body.size()) + "\r\n\r\n" + body;
  23609. std::string res;
  23610. ASSERT_TRUE(send_request(5, req, &res, port));
  23611. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23612. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23613. // Only one response, and the body was not served as a request
  23614. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23615. }
  23616. }
  23617. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23618. Server svr;
  23619. std::atomic<int> pre_request_calls{0};
  23620. std::atomic<bool> route_matched{false};
  23621. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23622. pre_request_calls++;
  23623. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23624. if (req.get_header_value("Authorization") != "Bearer token123") {
  23625. res.status = StatusCode::Unauthorized_401;
  23626. res.set_content("Unauthorized", "text/plain");
  23627. return Server::HandlerResponse::Handled;
  23628. }
  23629. return Server::HandlerResponse::Unhandled;
  23630. });
  23631. std::atomic<bool> handler_called{false};
  23632. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23633. handler_called = true;
  23634. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23635. });
  23636. auto port = svr.bind_to_any_port("localhost");
  23637. std::thread t([&]() { svr.listen_after_bind(); });
  23638. svr.wait_until_ready();
  23639. // Without Authorization header - should be rejected before upgrade
  23640. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23641. "/ws/1");
  23642. EXPECT_FALSE(client1.connect());
  23643. EXPECT_FALSE(handler_called);
  23644. EXPECT_EQ(1, pre_request_calls);
  23645. EXPECT_TRUE(route_matched);
  23646. // The rejection is an ordinary HTTP response, not a protocol switch
  23647. {
  23648. Client cli("localhost", port);
  23649. Headers headers = {{"Upgrade", "websocket"},
  23650. {"Connection", "Upgrade"},
  23651. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23652. {"Sec-WebSocket-Version", "13"}};
  23653. auto res = cli.Get("/ws/1", headers);
  23654. ASSERT_TRUE(res);
  23655. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23656. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23657. EXPECT_EQ("Unauthorized", res->body);
  23658. }
  23659. EXPECT_FALSE(handler_called);
  23660. // With Authorization header - should succeed
  23661. Headers headers = {{"Authorization", "Bearer token123"}};
  23662. ws::WebSocketClient client2(
  23663. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23664. ASSERT_TRUE(client2.connect());
  23665. std::string msg;
  23666. ASSERT_TRUE(client2.read(msg));
  23667. EXPECT_EQ("/ws/:id 2", msg);
  23668. EXPECT_TRUE(handler_called);
  23669. client2.close();
  23670. svr.stop();
  23671. t.join();
  23672. }
  23673. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23674. Server svr;
  23675. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23676. // A read timeout is how a handler gets control back. Without it, a handler
  23677. // parked in read() can never write on the connection it is reading.
  23678. ws.set_read_timeout(std::chrono::milliseconds(100));
  23679. std::string msg;
  23680. while (ws.is_open()) {
  23681. auto r = ws.read(msg);
  23682. if (r == httplib::ws::Timeout) {
  23683. ws.send("tick");
  23684. continue;
  23685. }
  23686. if (r == httplib::ws::Fail) { break; }
  23687. ws.send(msg);
  23688. }
  23689. });
  23690. auto port = svr.bind_to_any_port("localhost");
  23691. std::thread t([&]() { svr.listen_after_bind(); });
  23692. svr.wait_until_ready();
  23693. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23694. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23695. ASSERT_TRUE(client.connect());
  23696. // The client sends nothing, so anything it receives came out of the
  23697. // handler's timeout path.
  23698. std::string msg;
  23699. ASSERT_EQ(client.read(msg), ws::Text);
  23700. EXPECT_EQ("tick", msg);
  23701. client.close();
  23702. svr.stop();
  23703. t.join();
  23704. }
  23705. // Stream::read may return fewer bytes than asked for. This is that contract at
  23706. // its worst -- one byte per call -- which is what a frame header straddling a
  23707. // read buffer's boundary looks like to the frame parser.
  23708. class WsByteAtATimeStream : public Stream {
  23709. public:
  23710. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23711. bool is_readable() const override { return true; }
  23712. bool wait_readable() const override { return true; }
  23713. bool wait_writable() const override { return true; }
  23714. ssize_t read(char *ptr, size_t size) override {
  23715. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23716. *ptr = data_[pos_++];
  23717. return 1;
  23718. }
  23719. ssize_t write(const char *, size_t size) override {
  23720. return static_cast<ssize_t>(size);
  23721. }
  23722. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23723. ip = "127.0.0.1";
  23724. port = 0;
  23725. }
  23726. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23727. ip = "127.0.0.1";
  23728. port = 0;
  23729. }
  23730. socket_t socket() const override { return INVALID_SOCKET; }
  23731. time_t duration() const override { return 0; }
  23732. private:
  23733. std::string data_;
  23734. size_t pos_ = 0;
  23735. };
  23736. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23737. // The payload uses the 16-bit extended length, so the header, the length
  23738. // and the mask key are all multi-byte fields here. Each used to be read
  23739. // with a single read() call, which fails as soon as one is split. The
  23740. // payload is also a little over one read chunk, so it is read in two.
  23741. std::string body;
  23742. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23743. body += static_cast<char>(i % 251);
  23744. }
  23745. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23746. std::string frame;
  23747. frame += static_cast<char>(0x81); // FIN + Text
  23748. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23749. frame += static_cast<char>(body.size() >> 8);
  23750. frame += static_cast<char>(body.size() & 0xff);
  23751. for (size_t i = 0; i < 4; i++) {
  23752. frame += static_cast<char>(mask[i]);
  23753. }
  23754. for (size_t i = 0; i < body.size(); i++) {
  23755. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23756. }
  23757. WsByteAtATimeStream strm(frame);
  23758. ws::Opcode opcode;
  23759. std::string payload;
  23760. bool fin = false;
  23761. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23762. /*expect_masked=*/true, body.size()),
  23763. ws::impl::FrameRead::Ok);
  23764. EXPECT_TRUE(fin);
  23765. EXPECT_EQ(opcode, ws::Opcode::Text);
  23766. EXPECT_EQ(payload, body);
  23767. }
  23768. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23769. std::string body(2000, 'x');
  23770. std::string frame;
  23771. frame += static_cast<char>(0x82); // FIN + Binary
  23772. frame += static_cast<char>(126); // 16-bit length follows
  23773. frame += static_cast<char>(body.size() >> 8);
  23774. frame += static_cast<char>(body.size() & 0xff);
  23775. frame += body;
  23776. detail::BufferStream strm;
  23777. strm.write(frame.data(), frame.size());
  23778. ws::Opcode opcode;
  23779. std::string payload;
  23780. bool fin;
  23781. EXPECT_EQ(
  23782. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23783. ws::impl::FrameRead::Ok);
  23784. EXPECT_EQ(body, payload);
  23785. }
  23786. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23787. // The header announces the largest payload allowed, and only 3 bytes of it
  23788. // ever arrive.
  23789. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23790. std::string frame;
  23791. frame += static_cast<char>(0x82); // FIN + Binary
  23792. frame += static_cast<char>(127); // 64-bit length follows
  23793. for (int shift = 56; shift >= 0; shift -= 8) {
  23794. frame += static_cast<char>((len >> shift) & 0xff);
  23795. }
  23796. frame += "abc";
  23797. detail::BufferStream strm;
  23798. strm.write(frame.data(), frame.size());
  23799. ws::Opcode opcode;
  23800. std::string payload;
  23801. bool fin;
  23802. EXPECT_EQ(
  23803. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23804. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23805. ws::impl::FrameRead::Fail);
  23806. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23807. }
  23808. TEST(WebSocketTest, QueryStringInHandshake) {
  23809. Server svr;
  23810. std::mutex mtx;
  23811. std::string received_target;
  23812. std::string received_token;
  23813. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23814. {
  23815. std::lock_guard<std::mutex> lock(mtx);
  23816. received_target = req.target;
  23817. if (req.has_param("token")) {
  23818. received_token = req.get_param_value("token");
  23819. }
  23820. }
  23821. std::string msg;
  23822. while (ws.read(msg)) {
  23823. ws.send(msg);
  23824. }
  23825. });
  23826. auto port = svr.bind_to_any_port("localhost");
  23827. std::thread t([&]() { svr.listen_after_bind(); });
  23828. svr.wait_until_ready();
  23829. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23830. "/ws?token=ABC&session=123");
  23831. ASSERT_TRUE(client.connect());
  23832. // Round-trip ensures the handler has run and captured the request.
  23833. ASSERT_TRUE(client.send("hello"));
  23834. std::string msg;
  23835. ASSERT_TRUE(client.read(msg));
  23836. EXPECT_EQ("hello", msg);
  23837. client.close();
  23838. {
  23839. std::lock_guard<std::mutex> lock(mtx);
  23840. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23841. EXPECT_EQ("ABC", received_token);
  23842. }
  23843. svr.stop();
  23844. t.join();
  23845. }
  23846. // Run a handshake against a throwaway server and hand the request the server
  23847. // received back to the caller, so tests can assert on the headers the client
  23848. // actually put on the wire.
  23849. static void capture_websocket_handshake_request(
  23850. const Headers &client_headers,
  23851. std::function<void(const Request &, int port)> verify) {
  23852. Server svr;
  23853. std::mutex mtx;
  23854. Request received;
  23855. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23856. {
  23857. std::lock_guard<std::mutex> lock(mtx);
  23858. received = req;
  23859. }
  23860. std::string msg;
  23861. while (ws.read(msg)) {
  23862. ws.send(msg);
  23863. }
  23864. });
  23865. auto port = svr.bind_to_any_port("localhost");
  23866. std::thread t([&]() { svr.listen_after_bind(); });
  23867. auto se = detail::scope_exit([&] {
  23868. svr.stop();
  23869. t.join();
  23870. });
  23871. svr.wait_until_ready();
  23872. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23873. client_headers);
  23874. ASSERT_TRUE(client.connect());
  23875. ASSERT_TRUE(client.send("hello"));
  23876. std::string msg;
  23877. ASSERT_TRUE(client.read(msg));
  23878. client.close();
  23879. {
  23880. std::lock_guard<std::mutex> lock(mtx);
  23881. verify(received, port);
  23882. }
  23883. }
  23884. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23885. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23886. // Non-default port must be present in the Host header. Default ports
  23887. // (80/443) are omitted; that logic is covered by
  23888. // MakeHostAndPortStringTest.
  23889. EXPECT_EQ("localhost:" + std::to_string(port),
  23890. req.get_header_value("Host"));
  23891. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23892. req.get_header_value("User-Agent"));
  23893. EXPECT_FALSE(req.has_header("Accept"));
  23894. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23895. EXPECT_FALSE(req.has_header("Content-Length"));
  23896. });
  23897. }
  23898. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23899. capture_websocket_handshake_request(
  23900. {{"Host", "example.com"},
  23901. {"User-Agent", "custom-agent"},
  23902. {"X-Custom", "value"}},
  23903. [](const Request &req, int) {
  23904. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23905. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23906. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23907. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23908. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23909. });
  23910. }
  23911. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23912. capture_websocket_handshake_request(
  23913. {{"Upgrade", "bogus"},
  23914. {"Connection", "close"},
  23915. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23916. {"Sec-WebSocket-Version", "8"}},
  23917. [](const Request &req, int) {
  23918. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23919. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23920. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23921. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23922. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23923. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23924. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23925. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23926. req.get_header_value("Sec-WebSocket-Key"));
  23927. });
  23928. }
  23929. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23930. // A header the client refuses to send must abort the handshake before any
  23931. // part of it reaches the wire; a lone request line would otherwise sit in
  23932. // the peer's buffer as a truncated request.
  23933. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23934. ASSERT_NE(INVALID_SOCKET, srv);
  23935. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23936. sockaddr_in addr{};
  23937. addr.sin_family = AF_INET;
  23938. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23939. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23940. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23941. ASSERT_EQ(0, ::listen(srv, 1));
  23942. sockaddr_in bound{};
  23943. socklen_t bound_len = sizeof(bound);
  23944. ASSERT_EQ(
  23945. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23946. auto port = ntohs(bound.sin_port);
  23947. ssize_t received = -1;
  23948. std::thread t([&] {
  23949. // Bound every blocking call so a regression fails the test with a bad
  23950. // value instead of hanging the suite.
  23951. fd_set rfds;
  23952. FD_ZERO(&rfds);
  23953. FD_SET(srv, &rfds);
  23954. timeval tv{5, 0};
  23955. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23956. 0) {
  23957. return;
  23958. }
  23959. sockaddr_in cli_addr{};
  23960. socklen_t cli_len = sizeof(cli_addr);
  23961. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23962. if (cli == INVALID_SOCKET) { return; }
  23963. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23964. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23965. char buf[4096];
  23966. received = ::recv(cli, buf, sizeof(buf), 0);
  23967. });
  23968. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23969. // connect() has already shut the socket down by the time it returns false,
  23970. // so the peer sees EOF without waiting for the client to be destroyed.
  23971. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23972. {{"X-Bad", "a\r\nInjected: 1"}});
  23973. EXPECT_FALSE(client.connect());
  23974. t.join();
  23975. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23976. EXPECT_EQ(0, received);
  23977. }
  23978. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23979. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23980. // contains "upgrade" as a substring is a different token and must not
  23981. // start a WebSocket handshake.
  23982. auto make_request = [](const std::vector<std::string> &connection_values) {
  23983. Request req;
  23984. req.method = "GET";
  23985. req.headers.emplace("Upgrade", "websocket");
  23986. for (const auto &value : connection_values) {
  23987. req.headers.emplace("Connection", value);
  23988. }
  23989. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23990. req.headers.emplace("Sec-WebSocket-Version", "13");
  23991. return req;
  23992. };
  23993. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23994. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23995. EXPECT_TRUE(
  23996. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23997. EXPECT_TRUE(
  23998. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23999. EXPECT_TRUE(
  24000. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24001. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24002. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24003. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24004. EXPECT_FALSE(
  24005. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24006. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24007. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24008. }
  24009. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24010. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24011. // asks recipients to match each protocol-name case-insensitively, and RFC
  24012. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24013. // client naming websocket alongside another protocol, or on a second field
  24014. // line, is offering websocket; a value that merely contains "websocket" as a
  24015. // substring is a different protocol name and is not.
  24016. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24017. Request req;
  24018. req.method = "GET";
  24019. for (const auto &value : upgrade_values) {
  24020. req.headers.emplace("Upgrade", value);
  24021. }
  24022. req.headers.emplace("Connection", "Upgrade");
  24023. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24024. req.headers.emplace("Sec-WebSocket-Version", "13");
  24025. return req;
  24026. };
  24027. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24028. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24029. EXPECT_TRUE(
  24030. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24031. EXPECT_TRUE(
  24032. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24033. EXPECT_TRUE(
  24034. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24035. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24036. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24037. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24038. EXPECT_FALSE(
  24039. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24040. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24041. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24042. }
  24043. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24044. Server svr;
  24045. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24046. auto port = svr.bind_to_any_port("localhost");
  24047. std::thread t([&]() { svr.listen_after_bind(); });
  24048. auto se = detail::scope_exit([&] {
  24049. svr.stop();
  24050. t.join();
  24051. });
  24052. svr.wait_until_ready();
  24053. Headers headers = {{"Upgrade", "websocket"},
  24054. {"Connection", "notupgrade"},
  24055. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24056. {"Sec-WebSocket-Version", "13"}};
  24057. Client cli("localhost", port);
  24058. auto res = cli.Get("/ws", headers);
  24059. // The route exists only as a WebSocket route, so a request that fails the
  24060. // handshake check falls through to ordinary routing.
  24061. ASSERT_TRUE(res);
  24062. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24063. }
  24064. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24065. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24066. // Connection value is the only thing left for the client to reject.
  24067. Server svr;
  24068. svr.Get("/ws", [](const Request &req, Response &res) {
  24069. res.status = StatusCode::SwitchingProtocol_101;
  24070. res.set_header("Upgrade", "websocket");
  24071. res.set_header("Connection", "notupgrade");
  24072. res.set_header("Sec-WebSocket-Accept",
  24073. detail::websocket_accept_key(
  24074. req.get_header_value("Sec-WebSocket-Key")));
  24075. });
  24076. auto port = svr.bind_to_any_port("localhost");
  24077. std::thread t([&]() { svr.listen_after_bind(); });
  24078. auto se = detail::scope_exit([&] {
  24079. svr.stop();
  24080. t.join();
  24081. });
  24082. svr.wait_until_ready();
  24083. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24084. auto res = client.connect();
  24085. EXPECT_FALSE(res);
  24086. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24087. EXPECT_FALSE(client.is_open());
  24088. }
  24089. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24090. Server svr;
  24091. svr.Get("/ws", [](const Request &req, Response &res) {
  24092. res.status = StatusCode::SwitchingProtocol_101;
  24093. res.set_header("Upgrade", "websocket");
  24094. res.set_header("Connection", "Upgrade");
  24095. res.set_header("Sec-WebSocket-Accept",
  24096. detail::websocket_accept_key(
  24097. req.get_header_value("Sec-WebSocket-Key")));
  24098. res.set_header("Sec-WebSocket-Protocol", "admin");
  24099. });
  24100. auto port = svr.bind_to_any_port("localhost");
  24101. std::thread t([&]() { svr.listen_after_bind(); });
  24102. auto se = detail::scope_exit([&] {
  24103. svr.stop();
  24104. t.join();
  24105. });
  24106. svr.wait_until_ready();
  24107. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24108. // Server selects a subprotocol the client never offered
  24109. {
  24110. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24111. ws::WebSocketClient client(url, headers);
  24112. auto res = client.connect();
  24113. EXPECT_FALSE(res);
  24114. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24115. EXPECT_FALSE(client.is_open());
  24116. EXPECT_TRUE(client.subprotocol().empty());
  24117. }
  24118. // Client offered none but the server named one anyway
  24119. {
  24120. ws::WebSocketClient client(url);
  24121. auto res = client.connect();
  24122. EXPECT_FALSE(res);
  24123. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24124. EXPECT_FALSE(client.is_open());
  24125. EXPECT_TRUE(client.subprotocol().empty());
  24126. }
  24127. }
  24128. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24129. // The socket path doubles as the URL host, so it must not contain '/'.
  24130. const char *shard = getenv("GTEST_SHARD_INDEX");
  24131. const std::string sock_path =
  24132. shard ? std::string("httplib-ws-") + shard + ".sock"
  24133. : std::string("httplib-ws.sock");
  24134. std::remove(sock_path.c_str());
  24135. Server svr;
  24136. std::mutex mtx;
  24137. std::string received_host;
  24138. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24139. {
  24140. std::lock_guard<std::mutex> lock(mtx);
  24141. received_host = req.get_header_value("Host");
  24142. }
  24143. std::string msg;
  24144. while (ws.read(msg)) {
  24145. ws.send(msg);
  24146. }
  24147. });
  24148. svr.set_address_family(AF_UNIX);
  24149. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24150. auto se = detail::scope_exit([&] {
  24151. svr.stop();
  24152. t.join();
  24153. std::remove(sock_path.c_str());
  24154. });
  24155. svr.wait_until_ready();
  24156. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24157. client.set_address_family(AF_UNIX);
  24158. ASSERT_TRUE(client.connect());
  24159. ASSERT_TRUE(client.send("hello"));
  24160. std::string msg;
  24161. ASSERT_TRUE(client.read(msg));
  24162. client.close();
  24163. {
  24164. std::lock_guard<std::mutex> lock(mtx);
  24165. // There is no host:port for a Unix socket, so the same "localhost"
  24166. // placeholder the HTTP client uses is expected.
  24167. EXPECT_EQ("localhost", received_host);
  24168. }
  24169. }
  24170. // Two threads must never parse WebSocket frames from the same stream.
  24171. // close() used to read the peer's Close reply with its own frame read, so it
  24172. // raced a reader thread that was in the middle of a payload: the payload loop
  24173. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24174. // so bytes taken by close() were replaced with bytes from further along the
  24175. // stream. The message kept its length and silently changed content.
  24176. //
  24177. // The raw peer below sends a frame header plus part of the payload, waits for
  24178. // the handler to call close(), and only then sends the rest. Whichever thread
  24179. // would win the race for those bytes, the message must arrive intact, because
  24180. // close() must not touch the stream while read() owns it.
  24181. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24182. #ifndef _WIN32
  24183. signal(SIGPIPE, SIG_IGN);
  24184. #endif
  24185. const size_t payload_len = 120; // fits the 7-bit length field
  24186. const size_t prefix_len = 8;
  24187. const int attempts = 8;
  24188. std::string expected(payload_len, '\0');
  24189. for (size_t i = 0; i < payload_len; i++) {
  24190. expected[i] = static_cast<char>('a' + i % 26);
  24191. }
  24192. std::atomic<bool> peer_stalled{false};
  24193. std::atomic<bool> handler_done{false};
  24194. std::mutex received_mutex;
  24195. std::vector<std::string> received;
  24196. // Bound every wait, so a regression fails the test instead of hanging the
  24197. // suite.
  24198. auto wait_for = [](const std::atomic<bool> &flag) {
  24199. for (int i = 0; i < 500 && !flag; i++) {
  24200. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24201. }
  24202. };
  24203. Server svr;
  24204. svr.set_websocket_ping_interval(0);
  24205. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24206. std::thread reader([&]() {
  24207. std::string msg;
  24208. while (ws.read(msg)) {
  24209. std::lock_guard<std::mutex> guard(received_mutex);
  24210. received.push_back(msg);
  24211. }
  24212. });
  24213. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24214. // inside read_websocket_frame() when close() runs.
  24215. wait_for(peer_stalled);
  24216. ws.close();
  24217. reader.join();
  24218. handler_done = true;
  24219. });
  24220. auto port = svr.bind_to_any_port("127.0.0.1");
  24221. std::thread t([&]() { svr.listen_after_bind(); });
  24222. auto se = detail::scope_exit([&] {
  24223. svr.stop();
  24224. t.join();
  24225. });
  24226. svr.wait_until_ready();
  24227. auto send_bytes = [](socket_t s, const std::string &data) {
  24228. #ifdef _WIN32
  24229. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24230. #else
  24231. auto n = ::send(s, data.data(), data.size(), 0);
  24232. #endif
  24233. return n == static_cast<decltype(n)>(data.size());
  24234. };
  24235. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24236. // Every length used here fits the 7-bit length field.
  24237. auto masked_header = [](uint8_t first_byte, size_t len) {
  24238. std::string h;
  24239. h += static_cast<char>(first_byte);
  24240. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24241. h.append(4, '\0'); // mask key
  24242. return h;
  24243. };
  24244. for (int attempt = 0; attempt < attempts; attempt++) {
  24245. peer_stalled = false;
  24246. handler_done = false;
  24247. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24248. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24249. auto se_sock = detail::scope_exit([&] {
  24250. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24251. });
  24252. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24253. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24254. sockaddr_in addr{};
  24255. addr.sin_family = AF_INET;
  24256. addr.sin_port = htons(static_cast<uint16_t>(port));
  24257. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24258. ASSERT_EQ(
  24259. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24260. << "attempt " << attempt;
  24261. ASSERT_TRUE(send_bytes(sock,
  24262. "GET /ws HTTP/1.1\r\n"
  24263. "Host: 127.0.0.1\r\n"
  24264. "Upgrade: websocket\r\n"
  24265. "Connection: Upgrade\r\n"
  24266. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24267. "Sec-WebSocket-Version: 13\r\n"
  24268. "\r\n"))
  24269. << "attempt " << attempt;
  24270. std::string response;
  24271. while (response.find("\r\n\r\n") == std::string::npos) {
  24272. char buf[512];
  24273. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24274. if (n <= 0) { break; }
  24275. response.append(buf, static_cast<size_t>(n));
  24276. }
  24277. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24278. << "attempt " << attempt;
  24279. // Send the header of a Binary message but only the first prefix_len bytes
  24280. // of its payload, leaving the reader thread stalled inside the payload.
  24281. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24282. expected.substr(0, prefix_len)))
  24283. << "attempt " << attempt;
  24284. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24285. peer_stalled = true;
  24286. // Let close() send its Close frame and park in its own read before the
  24287. // rest of the payload arrives, so both threads are waiting for it.
  24288. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24289. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24290. close_frame += static_cast<char>(0x03); // status 1000
  24291. close_frame += static_cast<char>(0xE8);
  24292. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24293. << "attempt " << attempt;
  24294. // Closing the peer releases the reader thread even on the buggy path,
  24295. // where it waits for bytes another thread already consumed.
  24296. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24297. detail::close_socket(sock);
  24298. sock = INVALID_SOCKET;
  24299. wait_for(handler_done);
  24300. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24301. }
  24302. std::lock_guard<std::mutex> guard(received_mutex);
  24303. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24304. << "a message in flight when close() ran was dropped";
  24305. for (size_t i = 0; i < received.size(); i++) {
  24306. EXPECT_EQ(expected, received[i]) << "message " << i;
  24307. }
  24308. }
  24309. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24310. // returning the socket, or INVALID_SOCKET.
  24311. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24312. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24313. if (sock == INVALID_SOCKET) { return sock; }
  24314. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24315. sockaddr_in addr{};
  24316. addr.sin_family = AF_INET;
  24317. addr.sin_port = htons(static_cast<uint16_t>(port));
  24318. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24319. std::string req = "GET " + path +
  24320. " HTTP/1.1\r\n"
  24321. "Host: 127.0.0.1\r\n"
  24322. "Upgrade: websocket\r\n"
  24323. "Connection: Upgrade\r\n"
  24324. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24325. "Sec-WebSocket-Version: 13\r\n"
  24326. "\r\n";
  24327. std::string res;
  24328. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24329. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24330. static_cast<ssize_t>(req.size())) {
  24331. char c;
  24332. while (res.find("\r\n\r\n") == std::string::npos &&
  24333. ::recv(sock, &c, 1, 0) == 1) {
  24334. res += c;
  24335. }
  24336. }
  24337. if (res.find(" 101 ") == std::string::npos) {
  24338. detail::close_socket(sock);
  24339. return INVALID_SOCKET;
  24340. }
  24341. return sock;
  24342. }
  24343. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24344. // The payload must fit the 7-bit length field.
  24345. static std::string masked_frame(uint8_t first_byte,
  24346. const std::string &payload) {
  24347. std::string f;
  24348. f += static_cast<char>(first_byte);
  24349. f += static_cast<char>(0x80 | payload.size());
  24350. f.append(4, '\0');
  24351. return f + payload;
  24352. }
  24353. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24354. std::atomic<bool> done{false};
  24355. std::string received;
  24356. Server svr;
  24357. svr.set_websocket_ping_interval(0);
  24358. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24359. std::string msg;
  24360. if (ws.read(msg) == ws::Binary) { received = msg; }
  24361. done = true;
  24362. });
  24363. auto port = svr.bind_to_any_port("127.0.0.1");
  24364. std::thread t([&]() { svr.listen_after_bind(); });
  24365. auto se = detail::scope_exit([&] {
  24366. svr.stop();
  24367. t.join();
  24368. });
  24369. svr.wait_until_ready();
  24370. auto sock = connect_raw_websocket(port, "/ws");
  24371. ASSERT_NE(INVALID_SOCKET, sock);
  24372. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24373. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24374. masked_frame(0x89, "p") + // FIN + Ping
  24375. masked_frame(0x80, "lo"); // FIN + Continuation
  24376. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24377. for (int i = 0; i < 500 && !done; i++) {
  24378. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24379. }
  24380. ASSERT_TRUE(done);
  24381. EXPECT_EQ("Hello", received);
  24382. // The Ping between the fragments is answered with a Pong.
  24383. char pong[3];
  24384. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24385. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24386. }
  24387. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24388. Server svr;
  24389. svr.set_websocket_ping_interval(-1);
  24390. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24391. std::string msg;
  24392. while (ws.read(msg)) {}
  24393. });
  24394. auto port = svr.bind_to_any_port("127.0.0.1");
  24395. std::thread t([&]() { svr.listen_after_bind(); });
  24396. auto se = detail::scope_exit([&] {
  24397. svr.stop();
  24398. t.join();
  24399. });
  24400. svr.wait_until_ready();
  24401. auto sock = connect_raw_websocket(port, "/ws");
  24402. ASSERT_NE(INVALID_SOCKET, sock);
  24403. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24404. // Nothing comes while the client stays quiet.
  24405. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24406. char c;
  24407. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24408. }
  24409. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24410. // and that has to end a read() already waiting on the peer, on every platform.
  24411. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24412. // The peer sends no pings, and its handler never calls read(), which is
  24413. // where pongs are written.
  24414. std::mutex mutex;
  24415. std::condition_variable cv;
  24416. auto release = false;
  24417. svr.set_websocket_ping_interval(0);
  24418. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24419. std::unique_lock<std::mutex> lock(mutex);
  24420. cv.wait(lock, [&] { return release; });
  24421. });
  24422. auto port = svr.bind_to_any_port(HOST);
  24423. std::thread t([&]() { svr.listen_after_bind(); });
  24424. auto se = detail::scope_exit([&] {
  24425. {
  24426. std::lock_guard<std::mutex> lock(mutex);
  24427. release = true;
  24428. }
  24429. cv.notify_all();
  24430. svr.stop();
  24431. t.join();
  24432. });
  24433. svr.wait_until_ready();
  24434. ws::WebSocketClient client(std::string(scheme) +
  24435. "://localhost:" + std::to_string(port) + "/ws");
  24436. #ifdef CPPHTTPLIB_SSL_ENABLED
  24437. client.enable_server_certificate_verification(false);
  24438. #endif
  24439. // A ping a second, given up on after two go unanswered: about 3s
  24440. client.set_websocket_ping_interval(1);
  24441. client.set_websocket_max_missed_pongs(2);
  24442. // Well past that, so that a read the timeout ends instead stands out
  24443. client.set_read_timeout(10);
  24444. ASSERT_TRUE(client.connect());
  24445. auto start = std::chrono::steady_clock::now();
  24446. std::string msg;
  24447. EXPECT_EQ(ws::Fail, client.read(msg));
  24448. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24449. std::chrono::steady_clock::now() - start)
  24450. .count(),
  24451. 6000);
  24452. EXPECT_FALSE(client.is_open());
  24453. }
  24454. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24455. Server svr;
  24456. check_pong_timeout_ends_read(svr, "ws");
  24457. }
  24458. #ifdef CPPHTTPLIB_SSL_ENABLED
  24459. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24460. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24461. ASSERT_TRUE(svr.is_valid());
  24462. check_pong_timeout_ends_read(svr, "wss");
  24463. }
  24464. #endif
  24465. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24466. Server svr;
  24467. svr.set_websocket_ping_interval(0);
  24468. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24469. std::string msg;
  24470. while (ws.read(msg)) {}
  24471. });
  24472. auto port = svr.bind_to_any_port("127.0.0.1");
  24473. std::thread t([&]() { svr.listen_after_bind(); });
  24474. auto se = detail::scope_exit([&] {
  24475. svr.stop();
  24476. t.join();
  24477. });
  24478. svr.wait_until_ready();
  24479. // Each Close payload and the reply it should get: an echo when valid, 1002
  24480. // otherwise.
  24481. std::vector<std::pair<std::string, std::string>> cases = {
  24482. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24483. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24484. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24485. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24486. };
  24487. // Also between the fragments of a message.
  24488. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24489. for (const auto &c : cases) {
  24490. auto sock = connect_raw_websocket(port, "/ws");
  24491. ASSERT_NE(INVALID_SOCKET, sock);
  24492. auto frames = prefix + masked_frame(0x88, c.first);
  24493. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24494. std::string reply;
  24495. char buf[256];
  24496. while (reply.size() < 2 + c.second.size()) {
  24497. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24498. if (n <= 0) { break; }
  24499. reply.append(buf, static_cast<size_t>(n));
  24500. }
  24501. detail::close_socket(sock);
  24502. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24503. c.second,
  24504. reply);
  24505. }
  24506. }
  24507. }
  24508. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24509. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24510. protected:
  24511. void SetUp() override {
  24512. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24513. SERVER_PRIVATE_KEY_FILE);
  24514. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24515. std::string msg;
  24516. ws::ReadResult ret;
  24517. while ((ret = ws.read(msg))) {
  24518. if (ret == ws::Binary) {
  24519. ws.send(msg.data(), msg.size());
  24520. } else {
  24521. ws.send(msg);
  24522. }
  24523. }
  24524. });
  24525. port_ = server_->bind_to_any_port(HOST);
  24526. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24527. server_->wait_until_ready();
  24528. }
  24529. void TearDown() override {
  24530. server_->stop();
  24531. if (server_thread_.joinable()) { server_thread_.join(); }
  24532. }
  24533. std::unique_ptr<SSLServer> server_;
  24534. std::thread server_thread_;
  24535. int port_ = 0;
  24536. };
  24537. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24538. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24539. {
  24540. ws::WebSocketClient client(url);
  24541. client.enable_server_certificate_verification(false);
  24542. auto calls = 0;
  24543. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24544. calls++;
  24545. return false;
  24546. });
  24547. EXPECT_FALSE(client.connect());
  24548. EXPECT_GT(calls, 0);
  24549. }
  24550. {
  24551. ws::WebSocketClient client(url);
  24552. client.enable_server_certificate_verification(false);
  24553. client.set_session_verifier([](tls::session_t) {
  24554. return SSLVerifierResponse::CertificateRejected;
  24555. });
  24556. EXPECT_FALSE(client.connect());
  24557. }
  24558. {
  24559. ws::WebSocketClient client(url);
  24560. client.enable_server_certificate_verification(false);
  24561. client.set_session_verifier([](tls::session_t) {
  24562. return SSLVerifierResponse::CertificateAccepted;
  24563. });
  24564. EXPECT_TRUE(client.connect());
  24565. }
  24566. }
  24567. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24568. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24569. "/ws-echo");
  24570. client.enable_server_certificate_verification(false);
  24571. ASSERT_TRUE(client.connect());
  24572. ASSERT_TRUE(client.is_open());
  24573. ASSERT_TRUE(client.send("Hello WSS"));
  24574. std::string msg;
  24575. EXPECT_EQ(ws::Text, client.read(msg));
  24576. EXPECT_EQ("Hello WSS", msg);
  24577. client.close();
  24578. }
  24579. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24580. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24581. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24582. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24583. // client (without calling close() first) is the only path that runs
  24584. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24585. // bug exactly.
  24586. //
  24587. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24588. // when linked against an instrumented libssl; run under Valgrind to catch it
  24589. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24590. // suite (the freed session otherwise stalls on the close handshake) — this test
  24591. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24592. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24593. {
  24594. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24595. "/ws-echo");
  24596. client.enable_server_certificate_verification(false);
  24597. client.set_read_timeout(2, 0);
  24598. client.set_write_timeout(2, 0);
  24599. ASSERT_TRUE(client.connect());
  24600. ASSERT_TRUE(client.is_open());
  24601. ASSERT_TRUE(client.send("still open"));
  24602. // Intentionally do NOT call client.close(): leaving scope runs
  24603. // shutdown_and_close() with the WebSocket still open, which must send the
  24604. // close frame while the TLS session is still alive.
  24605. }
  24606. }
  24607. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24608. // shutdown_and_close() at the start of connect(), reproducing the same
  24609. // use-after-free within the test body rather than at scope exit. The second
  24610. // connect must succeed and echo, proving the close handshake ran over a live
  24611. // session. See the note above about memory-tool requirements.
  24612. TEST_F(WebSocketSSLIntegrationTest,
  24613. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24614. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24615. "/ws-echo");
  24616. client.enable_server_certificate_verification(false);
  24617. client.set_read_timeout(2, 0);
  24618. client.set_write_timeout(2, 0);
  24619. ASSERT_TRUE(client.connect());
  24620. ASSERT_TRUE(client.is_open());
  24621. ASSERT_TRUE(client.send("still open"));
  24622. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24623. // the still-open connection, which must not touch a freed TLS session.
  24624. ASSERT_TRUE(client.connect());
  24625. ASSERT_TRUE(client.is_open());
  24626. ASSERT_TRUE(client.send("after reconnect"));
  24627. std::string msg;
  24628. EXPECT_EQ(ws::Text, client.read(msg));
  24629. EXPECT_EQ("after reconnect", msg);
  24630. client.close();
  24631. }
  24632. #endif
  24633. #ifdef CPPHTTPLIB_SSL_ENABLED
  24634. class WebSocketSSLCATest : public ::testing::Test {
  24635. protected:
  24636. void SetUp() override {
  24637. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24638. SERVER_PRIVATE_KEY_FILE);
  24639. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24640. std::string msg;
  24641. while (ws.read(msg)) {
  24642. ws.send(msg);
  24643. }
  24644. });
  24645. port_ = server_->bind_to_any_port("127.0.0.1");
  24646. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24647. server_->wait_until_ready();
  24648. }
  24649. void TearDown() override {
  24650. server_->stop();
  24651. if (server_thread_.joinable()) { server_thread_.join(); }
  24652. }
  24653. std::string url() const {
  24654. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24655. }
  24656. std::unique_ptr<SSLServer> server_;
  24657. std::thread server_thread_;
  24658. int port_ = 0;
  24659. };
  24660. // A custom CA loaded as PEM verifies the server with full certificate
  24661. // verification enabled
  24662. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24663. ws::WebSocketClient client(url());
  24664. std::string cert;
  24665. read_file(SERVER_CERT2_FILE, cert);
  24666. client.load_ca_cert_store(cert.c_str(), cert.size());
  24667. ASSERT_TRUE(client.connect());
  24668. ASSERT_TRUE(client.send("hello"));
  24669. std::string msg;
  24670. EXPECT_EQ(ws::Text, client.read(msg));
  24671. EXPECT_EQ("hello", msg);
  24672. client.close();
  24673. }
  24674. // A custom CA that does not cover the server must fail verification (the
  24675. // custom CA is exclusive; system certs are not loaded alongside it)
  24676. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24677. ws::WebSocketClient client(url());
  24678. std::string cert;
  24679. read_file(CLIENT_CA_CERT_FILE, cert);
  24680. client.load_ca_cert_store(cert.c_str(), cert.size());
  24681. auto res = client.connect();
  24682. ASSERT_FALSE(res);
  24683. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24684. EXPECT_EQ(-1, res.status());
  24685. EXPECT_NE(0u, res.ssl_backend_error());
  24686. }
  24687. // The same CA as a file path rather than PEM in memory
  24688. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24689. ws::WebSocketClient client(url());
  24690. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24691. ASSERT_TRUE(client.connect());
  24692. ASSERT_TRUE(client.send("hello"));
  24693. std::string msg;
  24694. EXPECT_EQ(ws::Text, client.read(msg));
  24695. EXPECT_EQ("hello", msg);
  24696. client.close();
  24697. }
  24698. // ...and a CA file that does not cover the server still fails, so it is the
  24699. // path above that decides the outcome
  24700. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24701. ws::WebSocketClient client(url());
  24702. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24703. ASSERT_FALSE(client.connect());
  24704. }
  24705. // Regression test: reconnecting with a native custom CA store used to reuse
  24706. // a store handle the previous TLS context had already freed (use-after-free
  24707. // under the OpenSSL backend). The context now lives as long as the client.
  24708. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24709. ws::WebSocketClient client(url());
  24710. std::string cert;
  24711. read_file(SERVER_CERT2_FILE, cert);
  24712. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24713. ASSERT_TRUE(client.connect());
  24714. client.close();
  24715. ASSERT_TRUE(client.connect());
  24716. ASSERT_TRUE(client.send("again"));
  24717. std::string msg;
  24718. EXPECT_EQ(ws::Text, client.read(msg));
  24719. EXPECT_EQ("again", msg);
  24720. client.close();
  24721. }
  24722. // Regression test: a certificate with a trusted chain but no identity match
  24723. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24724. // verification entirely for IP hosts, so this connection succeeded there.
  24725. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24726. // chain verification while the identity check must still fail.
  24727. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24728. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24729. ASSERT_TRUE(svr.is_valid());
  24730. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24731. std::string msg;
  24732. while (ws.read(msg)) {
  24733. ws.send(msg);
  24734. }
  24735. });
  24736. auto port = svr.bind_to_any_port("127.0.0.1");
  24737. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24738. auto se = detail::scope_exit([&] {
  24739. svr.stop();
  24740. t.join();
  24741. });
  24742. svr.wait_until_ready();
  24743. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24744. "/echo");
  24745. std::string cert;
  24746. read_file(SERVER_CERT_FILE, cert);
  24747. client.load_ca_cert_store(cert.c_str(), cert.size());
  24748. ASSERT_FALSE(client.connect());
  24749. }
  24750. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24751. // SNI, so nothing binds the host name to the TLS session. These bind the
  24752. // server to "localhost" instead, the only shape that exercises the SNI and
  24753. // hostname-verification path with certificate verification left enabled.
  24754. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24755. protected:
  24756. void Start(const char *cert_file) {
  24757. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24758. SERVER_PRIVATE_KEY_FILE);
  24759. ASSERT_TRUE(server_->is_valid());
  24760. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24761. std::string msg;
  24762. while (ws.read(msg)) {
  24763. ws.send(msg);
  24764. }
  24765. });
  24766. port_ = server_->bind_to_any_port("localhost");
  24767. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24768. server_->wait_until_ready();
  24769. }
  24770. void TearDown() override {
  24771. if (server_) { server_->stop(); }
  24772. if (server_thread_.joinable()) { server_thread_.join(); }
  24773. }
  24774. std::string url() const {
  24775. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24776. }
  24777. std::unique_ptr<SSLServer> server_;
  24778. std::thread server_thread_;
  24779. int port_ = 0;
  24780. };
  24781. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24782. // out and the connection is usable
  24783. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24784. Start(SERVER_CERT2_FILE);
  24785. ws::WebSocketClient client(url());
  24786. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24787. ASSERT_TRUE(client.connect());
  24788. ASSERT_TRUE(client.send("hello"));
  24789. std::string msg;
  24790. EXPECT_EQ(ws::Text, client.read(msg));
  24791. EXPECT_EQ("hello", msg);
  24792. client.close();
  24793. }
  24794. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24795. // while the identity check must still reject "localhost"
  24796. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24797. Start(SERVER_CERT_FILE);
  24798. ws::WebSocketClient client(url());
  24799. client.set_ca_cert_path(SERVER_CERT_FILE);
  24800. auto res = client.connect();
  24801. ASSERT_FALSE(res);
  24802. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24803. EXPECT_EQ(-1, res.status());
  24804. }
  24805. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24806. // disabled: the chain is still checked, only the identity check is skipped
  24807. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24808. Start(SERVER_CERT_FILE);
  24809. ws::WebSocketClient client(url());
  24810. client.set_ca_cert_path(SERVER_CERT_FILE);
  24811. client.enable_server_hostname_verification(false);
  24812. ASSERT_TRUE(client.connect());
  24813. ASSERT_TRUE(client.send("hello"));
  24814. std::string msg;
  24815. EXPECT_EQ(ws::Text, client.read(msg));
  24816. EXPECT_EQ("hello", msg);
  24817. client.close();
  24818. }
  24819. // A CA that did not sign the server certificate fails the chain, even though
  24820. // the name would match
  24821. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24822. Start(SERVER_CERT2_FILE);
  24823. ws::WebSocketClient client(url());
  24824. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24825. ASSERT_FALSE(client.connect());
  24826. }
  24827. // With verification disabled, neither the chain nor the name is checked
  24828. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24829. Start(SERVER_CERT_FILE);
  24830. ws::WebSocketClient client(url());
  24831. client.enable_server_certificate_verification(false);
  24832. ASSERT_TRUE(client.connect());
  24833. ASSERT_TRUE(client.send("hello"));
  24834. std::string msg;
  24835. EXPECT_EQ(ws::Text, client.read(msg));
  24836. EXPECT_EQ("hello", msg);
  24837. client.close();
  24838. }
  24839. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24840. protected:
  24841. void SetUp() override {
  24842. server_ = httplib::detail::make_unique<SSLServer>(
  24843. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24844. ASSERT_TRUE(server_->is_valid());
  24845. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24846. std::string msg;
  24847. while (ws.read(msg)) {
  24848. ws.send(msg);
  24849. }
  24850. });
  24851. port_ = server_->bind_to_any_port("localhost");
  24852. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24853. server_->wait_until_ready();
  24854. }
  24855. void TearDown() override {
  24856. server_->stop();
  24857. if (server_thread_.joinable()) { server_thread_.join(); }
  24858. }
  24859. std::string url() const {
  24860. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24861. }
  24862. void ConnectWithClientCert(const std::string &client_cert_file,
  24863. const std::string &client_private_key_file,
  24864. const char *private_key_password) {
  24865. std::string cert_pem, key_pem;
  24866. read_file(client_cert_file, cert_pem);
  24867. read_file(client_private_key_file, key_pem);
  24868. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24869. key_pem.c_str(), key_pem.size(),
  24870. private_key_password};
  24871. ConnectWithPem(pem);
  24872. }
  24873. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24874. ws::WebSocketClient client(url(), pem);
  24875. ASSERT_TRUE(client.is_valid());
  24876. client.enable_server_certificate_verification(false);
  24877. ASSERT_TRUE(client.connect());
  24878. ASSERT_TRUE(client.send("hello"));
  24879. std::string msg;
  24880. EXPECT_EQ(ws::Text, client.read(msg));
  24881. EXPECT_EQ("hello", msg);
  24882. client.close();
  24883. }
  24884. std::unique_ptr<SSLServer> server_;
  24885. std::thread server_thread_;
  24886. int port_ = 0;
  24887. };
  24888. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24889. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24890. }
  24891. // Control for the tests above: the fixture's server really does require a
  24892. // client certificate, so it is the PEM the constructor installed that decides
  24893. // the outcome.
  24894. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24895. ws::WebSocketClient client(url());
  24896. ASSERT_TRUE(client.is_valid());
  24897. client.enable_server_certificate_verification(false);
  24898. EXPECT_FALSE(client.connect());
  24899. }
  24900. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24901. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24902. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24903. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24904. }
  24905. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24906. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24907. std::string cert_pem, key_pem;
  24908. read_file(CLIENT_CERT_FILE, cert_pem);
  24909. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24910. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24911. std::vector<char> key(key_pem.begin(), key_pem.end());
  24912. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24913. key.size(), nullptr};
  24914. ConnectWithPem(pem);
  24915. }
  24916. #endif
  24917. #if !defined(_WIN32)
  24918. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24919. auto secret_dir = std::string("./symlink_test_secret");
  24920. auto served_dir = std::string("./symlink_test_served");
  24921. auto secret_file = secret_dir + "/secret.txt";
  24922. auto symlink_path = served_dir + "/escape";
  24923. // Setup: create directories and files
  24924. mkdir(secret_dir.c_str(), 0755);
  24925. mkdir(served_dir.c_str(), 0755);
  24926. {
  24927. std::ofstream ofs(secret_file);
  24928. ofs << "SECRET_DATA";
  24929. }
  24930. // Create symlink using absolute path so it resolves correctly
  24931. #ifdef PATH_MAX
  24932. char abs_secret[PATH_MAX];
  24933. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24934. #else
  24935. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24936. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24937. ASSERT_NE(nullptr, abs_secret);
  24938. #endif
  24939. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24940. auto se = detail::scope_exit([&] {
  24941. unlink(symlink_path.c_str());
  24942. unlink(secret_file.c_str());
  24943. rmdir(served_dir.c_str());
  24944. rmdir(secret_dir.c_str());
  24945. });
  24946. Server svr;
  24947. svr.set_mount_point("/", served_dir);
  24948. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24949. auto se2 = detail::scope_exit([&] {
  24950. svr.stop();
  24951. listen_thread.join();
  24952. });
  24953. svr.wait_until_ready();
  24954. Client cli("localhost", PORT);
  24955. // Symlink pointing outside base dir should be blocked
  24956. auto res = cli.Get("/escape/secret.txt");
  24957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24958. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24959. }
  24960. #endif
  24961. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24962. // "GET /smuggled" request), reads the first response, and only then sends the
  24963. // embedded request as the body. Returns how many times /smuggled ran.
  24964. //
  24965. // The body is sent AFTER receiving the first response (as in the original
  24966. // PoC) so that the stream_line_reader cannot buffer it together with the
  24967. // headers of the first request.
  24968. static int count_smuggled_requests(const std::string &outer_head,
  24969. std::string &first_response) {
  24970. Server svr;
  24971. svr.set_mount_point("/", "./www");
  24972. std::atomic<int> smuggled_count(0);
  24973. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24974. smuggled_count++;
  24975. res.set_content("oops", "text/plain");
  24976. });
  24977. svr.Post("/post", [&](const Request &req, Response &res) {
  24978. res.set_content(req.body, "text/plain");
  24979. });
  24980. auto port = svr.bind_to_any_port("localhost");
  24981. thread t = thread([&] { svr.listen_after_bind(); });
  24982. auto se = detail::scope_exit([&] {
  24983. svr.stop();
  24984. t.join();
  24985. });
  24986. svr.wait_until_ready();
  24987. auto error = Error::Success;
  24988. auto sock = detail::create_client_socket(
  24989. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24990. /*connection_timeout_sec=*/2, 0,
  24991. /*read_timeout_sec=*/2, 0,
  24992. /*write_timeout_sec=*/2, 0, std::string(), error);
  24993. EXPECT_NE(INVALID_SOCKET, sock);
  24994. if (sock == INVALID_SOCKET) { return -1; }
  24995. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24996. // The "smuggled" request will be sent as the body of the outer request
  24997. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24998. "Host: localhost\r\n"
  24999. "Connection: close\r\n"
  25000. "\r\n";
  25001. auto head = outer_head;
  25002. auto len = std::to_string(smuggled.size());
  25003. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25004. pos = head.find("{len}", pos + len.size())) {
  25005. head.replace(pos, 5, len);
  25006. }
  25007. // Step 1: Send only the outer request headers (no body yet)
  25008. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25009. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25010. // Step 2: Read the first response
  25011. char buf[4096];
  25012. for (;;) {
  25013. auto n = recv(sock, buf, sizeof(buf), 0);
  25014. if (n <= 0) break;
  25015. first_response.append(buf, static_cast<size_t>(n));
  25016. // Stop once we have a complete response (headers + body)
  25017. auto hdr_end = first_response.find("\r\n\r\n");
  25018. if (hdr_end != std::string::npos) {
  25019. // Check for Content-Length to know when the body is complete
  25020. auto cl_pos = first_response.find("Content-Length:");
  25021. if (cl_pos != std::string::npos) {
  25022. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25023. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25024. auto cl = std::stoul(
  25025. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25026. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25027. } else {
  25028. break; // No Content-Length, assume headers-only response
  25029. }
  25030. }
  25031. }
  25032. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25033. // vulnerable server the keep-alive loop reads this as a second request. The
  25034. // server may already have closed the connection, so the result is ignored.
  25035. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25036. // Half-close so that a server which drained the body sees EOF and closes,
  25037. // instead of the read below waiting for the read timeout.
  25038. #ifdef _WIN32
  25039. ::shutdown(sock, SD_SEND);
  25040. #else
  25041. ::shutdown(sock, SHUT_WR);
  25042. #endif
  25043. // Step 4: Read until the server closes the connection
  25044. for (;;) {
  25045. auto n = recv(sock, buf, sizeof(buf), 0);
  25046. if (n <= 0) break;
  25047. }
  25048. return smuggled_count.load();
  25049. }
  25050. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25051. // A GET request with Content-Length to a static file handler must have its
  25052. // body drained before the keep-alive connection is reused. Otherwise the
  25053. // unread body bytes are interpreted as the next HTTP request.
  25054. std::string first_response;
  25055. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25056. "Host: localhost\r\n"
  25057. "Content-Length: {len}\r\n"
  25058. "\r\n",
  25059. first_response));
  25060. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25061. }
  25062. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25063. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25064. // be answered with 400 and the connection closed. Treating it as "no body"
  25065. // leaves the body to be parsed as the next request.
  25066. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25067. const char *targets[] = {
  25068. "GET /file", // handler that never reads the body
  25069. "GET /not-found", // no handler matches (404)
  25070. "POST /post", // handler that reads the body
  25071. };
  25072. for (auto target : targets) {
  25073. for (auto value : values) {
  25074. std::string first_response;
  25075. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25076. " HTTP/1.1\r\n"
  25077. "Host: localhost\r\n"
  25078. "Content-Length: " +
  25079. value + "\r\n\r\n",
  25080. first_response))
  25081. << target << " with Content-Length: " << value;
  25082. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25083. << target << " with Content-Length: " << value;
  25084. }
  25085. }
  25086. }
  25087. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25088. // A 400 for an unparseable request line leaves the rest of the message
  25089. // unread, so the connection must be closed rather than reused.
  25090. std::string first_response;
  25091. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25092. "Host: localhost\r\n"
  25093. "Content-Length: {len}\r\n"
  25094. "\r\n",
  25095. first_response));
  25096. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25097. }
  25098. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25099. // Same as above for a header block that fails to parse.
  25100. std::string first_response;
  25101. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25102. "Host: localhost\r\n"
  25103. "Bad Header\r\n"
  25104. "Content-Length: {len}\r\n"
  25105. "\r\n",
  25106. first_response));
  25107. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25108. }
  25109. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25110. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25111. // server must not read another request on that connection, even when the
  25112. // request had no body to drain.
  25113. std::string first_response;
  25114. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25115. "Host: localhost\r\n"
  25116. "\r\n",
  25117. first_response));
  25118. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25119. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25120. }
  25121. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25122. // A content reader that stops early leaves the stream inside the body.
  25123. // Draining the whole Content-Length from there, or reading the body again,
  25124. // reads into the next request, and whatever follows is parsed as a request
  25125. // of its own.
  25126. Server svr;
  25127. std::atomic<int> smuggled_count(0);
  25128. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25129. svr.Post("/upload", [](const Request &req, Response &res,
  25130. const ContentReader &content_reader) {
  25131. // Stop at the last chunk, so the whole body has been read however it
  25132. // arrives.
  25133. auto length = req.get_header_value_u64("Content-Length");
  25134. size_t total = 0;
  25135. auto consumed = content_reader([&](const char *, size_t n) {
  25136. total += n;
  25137. return total < length;
  25138. });
  25139. EXPECT_FALSE(consumed);
  25140. if (req.has_param("retry")) {
  25141. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25142. }
  25143. // Replace the 400 the aborted read set, which would close the connection.
  25144. res.set_redirect("/done");
  25145. });
  25146. auto port = svr.bind_to_any_port(HOST);
  25147. thread t = thread([&] { svr.listen_after_bind(); });
  25148. auto se = detail::scope_exit([&] {
  25149. svr.stop();
  25150. t.join();
  25151. });
  25152. svr.wait_until_ready();
  25153. // A front end sees the second request as a POST whose body is the GET. The
  25154. // first body is as long as the POST's headers, so draining it again reads
  25155. // exactly those and leaves the GET to be parsed next.
  25156. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25157. "Host: localhost\r\n"
  25158. "\r\n";
  25159. std::string second_head = "POST /post HTTP/1.1\r\n"
  25160. "Host: localhost\r\n"
  25161. "Content-Length: " +
  25162. std::to_string(inner.size()) +
  25163. "\r\n"
  25164. "\r\n";
  25165. for (auto target : {"/upload", "/upload?retry"}) {
  25166. smuggled_count = 0;
  25167. std::string request = "POST " + std::string(target) +
  25168. " HTTP/1.1\r\n"
  25169. "Host: localhost\r\n"
  25170. "Content-Length: " +
  25171. std::to_string(second_head.size()) +
  25172. "\r\n"
  25173. "\r\n" +
  25174. std::string(second_head.size(), 'A') + second_head +
  25175. inner;
  25176. std::string response;
  25177. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25178. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25179. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25180. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25181. EXPECT_EQ(0, smuggled_count.load()) << target;
  25182. }
  25183. }
  25184. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25185. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25186. // must be rejected with 400 Bad Request.
  25187. Server svr;
  25188. svr.Post("/test", [&](const Request &, Response &res) {
  25189. res.set_content("ok", "text/plain");
  25190. });
  25191. thread t = thread([&] { svr.listen(HOST, PORT); });
  25192. auto se = detail::scope_exit([&] {
  25193. svr.stop();
  25194. t.join();
  25195. ASSERT_FALSE(svr.is_running());
  25196. });
  25197. svr.wait_until_ready();
  25198. // Exact "chunked"
  25199. {
  25200. auto req = "POST /test HTTP/1.1\r\n"
  25201. "Host: localhost\r\n"
  25202. "Content-Length: 5\r\n"
  25203. "Transfer-Encoding: chunked\r\n"
  25204. "Connection: close\r\n"
  25205. "\r\n"
  25206. "hello";
  25207. std::string response;
  25208. ASSERT_TRUE(send_request(1, req, &response));
  25209. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25210. response.substr(0, response.find("\r\n")));
  25211. }
  25212. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25213. {
  25214. auto req = "POST /test HTTP/1.1\r\n"
  25215. "Host: localhost\r\n"
  25216. "Content-Length: 5\r\n"
  25217. "Transfer-Encoding: gzip, chunked\r\n"
  25218. "Connection: close\r\n"
  25219. "\r\n"
  25220. "hello";
  25221. std::string response;
  25222. ASSERT_TRUE(send_request(1, req, &response));
  25223. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25224. response.substr(0, response.find("\r\n")));
  25225. }
  25226. }
  25227. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25228. Server svr;
  25229. svr.Post("/test", [&](const Request &, Response &res) {
  25230. res.set_content("ok", "text/plain");
  25231. });
  25232. thread t = thread([&] { svr.listen(HOST, PORT); });
  25233. auto se = detail::scope_exit([&] {
  25234. svr.stop();
  25235. t.join();
  25236. ASSERT_FALSE(svr.is_running());
  25237. });
  25238. svr.wait_until_ready();
  25239. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25240. // length cannot be determined, so the server must answer 400 and close
  25241. // rather than treat the request as bodyless and leave the body in the
  25242. // socket for the next request to pick up.
  25243. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25244. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25245. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25246. std::string response;
  25247. ASSERT_TRUE(send_request(1, req, &response));
  25248. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25249. response.substr(0, response.find("\r\n")))
  25250. << transfer_encoding;
  25251. }
  25252. // RFC 9110 5.3: the codings may also be split across several
  25253. // Transfer-Encoding lines, which combine in the order they were received.
  25254. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25255. // just like the single-line "chunked, gzip" above.
  25256. {
  25257. auto req = "POST /test HTTP/1.1\r\n"
  25258. "Host: localhost\r\n"
  25259. "Transfer-Encoding: chunked\r\n"
  25260. "Transfer-Encoding: gzip\r\n"
  25261. "\r\n"
  25262. "0\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. }
  25268. }
  25269. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25270. Server svr;
  25271. svr.Post("/test", [&](const Request &, Response &res) {
  25272. res.set_content("ok", "text/plain");
  25273. });
  25274. auto port = svr.bind_to_any_port(HOST);
  25275. ASSERT_GT(port, 0);
  25276. thread t = thread([&] { svr.listen_after_bind(); });
  25277. auto se = detail::scope_exit([&] {
  25278. svr.stop();
  25279. t.join();
  25280. ASSERT_FALSE(svr.is_running());
  25281. });
  25282. svr.wait_until_ready();
  25283. for (auto transfer_encoding :
  25284. {"Transfer-Encoding: gzip, chunked\r\n",
  25285. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25286. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25287. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25288. transfer_encoding + "\r\n0\r\n\r\n";
  25289. std::string response;
  25290. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25291. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25292. response.substr(0, response.find("\r\n")))
  25293. << transfer_encoding;
  25294. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25295. << transfer_encoding;
  25296. }
  25297. }
  25298. // Regression for issue #2450: a DELETE without Content-Length on a
  25299. // keep-alive connection must not let the post-response drain consume the
  25300. // next request's bytes.
  25301. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25302. Server svr;
  25303. std::atomic<int> delete_count(0);
  25304. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25305. delete_count++;
  25306. res.status = StatusCode::NoContent_204;
  25307. });
  25308. auto port = svr.bind_to_any_port(HOST);
  25309. thread t = thread([&] { svr.listen_after_bind(); });
  25310. auto se = detail::scope_exit([&] {
  25311. svr.stop();
  25312. t.join();
  25313. });
  25314. svr.wait_until_ready();
  25315. auto error = Error::Success;
  25316. auto sock = detail::create_client_socket(
  25317. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25318. /*connection_timeout_sec=*/2, 0,
  25319. /*read_timeout_sec=*/2, 0,
  25320. /*write_timeout_sec=*/2, 0, std::string(), error);
  25321. ASSERT_NE(INVALID_SOCKET, sock);
  25322. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25323. auto send_request_and_read_response = [&](const std::string &req,
  25324. std::string &out) -> bool {
  25325. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25326. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25327. char buf[4096];
  25328. for (;;) {
  25329. auto n = recv(sock, buf, sizeof(buf), 0);
  25330. if (n <= 0) { return !out.empty(); }
  25331. out.append(buf, static_cast<size_t>(n));
  25332. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25333. }
  25334. };
  25335. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25336. "Host: localhost\r\n"
  25337. "\r\n";
  25338. std::string resp1;
  25339. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25340. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25341. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25342. "Host: localhost\r\n"
  25343. "Connection: close\r\n"
  25344. "\r\n";
  25345. std::string resp2;
  25346. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25347. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25348. EXPECT_EQ(2, delete_count.load());
  25349. }
  25350. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25351. Server svr;
  25352. svr.Post("/ingest", [&](const Request &, Response &res,
  25353. const ContentReader &content_reader) {
  25354. auto consumed = content_reader([](const char *, size_t) { return false; });
  25355. EXPECT_FALSE(consumed);
  25356. res.status = StatusCode::Conflict_409;
  25357. res.set_header("Connection", "close");
  25358. });
  25359. auto port = svr.bind_to_any_port(HOST);
  25360. thread t = thread([&] { svr.listen_after_bind(); });
  25361. auto se = detail::scope_exit([&] {
  25362. svr.stop();
  25363. t.join();
  25364. });
  25365. svr.wait_until_ready();
  25366. auto error = Error::Success;
  25367. auto sock = detail::create_client_socket(
  25368. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25369. /*connection_timeout_sec=*/2, 0,
  25370. /*read_timeout_sec=*/1, 0,
  25371. /*write_timeout_sec=*/2, 0, std::string(), error);
  25372. ASSERT_NE(INVALID_SOCKET, sock);
  25373. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25374. std::string request = "POST /ingest HTTP/1.1\r\n"
  25375. "Host: localhost\r\n"
  25376. "Transfer-Encoding: chunked\r\n"
  25377. "\r\n"
  25378. "4\r\n"
  25379. "data\r\n";
  25380. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25381. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25382. std::string response;
  25383. ssize_t received = 0;
  25384. do {
  25385. char buf[4096];
  25386. received = recv(sock, buf, sizeof(buf), 0);
  25387. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25388. } while (received > 0);
  25389. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25390. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25391. EXPECT_EQ(0, received);
  25392. }
  25393. namespace no_proxy_test {
  25394. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25395. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25396. // calling listen().
  25397. class ScopedServer {
  25398. public:
  25399. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25400. ~ScopedServer() {
  25401. svr_.stop();
  25402. if (th_.joinable()) { th_.join(); }
  25403. }
  25404. Server &svr() { return svr_; }
  25405. int port() const { return port_; }
  25406. void listen() {
  25407. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25408. svr_.wait_until_ready();
  25409. }
  25410. private:
  25411. Server svr_;
  25412. std::thread th_;
  25413. int port_ = 0;
  25414. };
  25415. class ProxyAndTargetServers {
  25416. public:
  25417. ProxyAndTargetServers() {
  25418. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25419. proxy_hits_++;
  25420. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25421. res.set_content("via-proxy", "text/plain");
  25422. });
  25423. target_.Get(".*", [this](const Request &req, Response &res) {
  25424. target_hits_++;
  25425. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25426. res.set_content("direct", "text/plain");
  25427. });
  25428. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25429. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25430. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25431. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25432. proxy_mock_.wait_until_ready();
  25433. target_.wait_until_ready();
  25434. }
  25435. ~ProxyAndTargetServers() {
  25436. proxy_mock_.stop();
  25437. target_.stop();
  25438. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25439. if (target_thread_.joinable()) { target_thread_.join(); }
  25440. }
  25441. Server &proxy_mock() { return proxy_mock_; }
  25442. Server &target() { return target_; }
  25443. int proxy_port() const { return proxy_port_; }
  25444. int target_port() const { return target_port_; }
  25445. int proxy_hits() const { return proxy_hits_.load(); }
  25446. int target_hits() const { return target_hits_.load(); }
  25447. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25448. void reset_counters() {
  25449. proxy_hits_ = 0;
  25450. target_hits_ = 0;
  25451. last_had_proxy_authz_ = false;
  25452. }
  25453. private:
  25454. Server proxy_mock_;
  25455. Server target_;
  25456. std::thread proxy_thread_;
  25457. std::thread target_thread_;
  25458. int proxy_port_ = 0;
  25459. int target_port_ = 0;
  25460. std::atomic<int> proxy_hits_{0};
  25461. std::atomic<int> target_hits_{0};
  25462. std::atomic<bool> last_had_proxy_authz_{false};
  25463. };
  25464. inline std::unique_ptr<Client> make_client(const std::string &host,
  25465. ProxyAndTargetServers &s) {
  25466. auto cli = detail::make_unique<Client>(host, s.target_port());
  25467. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25468. cli->set_proxy("127.0.0.1", s.proxy_port());
  25469. return cli;
  25470. }
  25471. } // namespace no_proxy_test
  25472. using no_proxy_test::make_client;
  25473. using no_proxy_test::ProxyAndTargetServers;
  25474. // A stream request carries the credentials a buffered request does
  25475. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25476. no_proxy_test::ScopedServer origin;
  25477. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25478. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25479. });
  25480. origin.listen();
  25481. Client cli("127.0.0.1", origin.port());
  25482. cli.set_basic_auth("user", "pass");
  25483. auto handle = cli.open_stream("GET", "/x");
  25484. ASSERT_TRUE(handle.is_valid());
  25485. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25486. Client bearer("127.0.0.1", origin.port());
  25487. bearer.set_bearer_token_auth("tok");
  25488. auto handle2 = bearer.open_stream("GET", "/x");
  25489. ASSERT_TRUE(handle2.is_valid());
  25490. EXPECT_EQ("Bearer tok", read_all(handle2));
  25491. }
  25492. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25493. // takes its own credentials, as for a buffered request
  25494. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25495. std::string target, authz, proxy_authz;
  25496. no_proxy_test::ScopedServer proxy;
  25497. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25498. target = req.target;
  25499. authz = req.get_header_value("Authorization");
  25500. proxy_authz = req.get_header_value("Proxy-Authorization");
  25501. res.set_content("ok", "text/plain");
  25502. });
  25503. proxy.listen();
  25504. Client cli("origin.example", 8080);
  25505. cli.set_proxy("127.0.0.1", proxy.port());
  25506. cli.set_proxy_basic_auth("puser", "ppass");
  25507. cli.set_basic_auth("user", "pass");
  25508. auto handle = cli.open_stream("GET", "/x");
  25509. ASSERT_TRUE(handle.is_valid());
  25510. EXPECT_EQ("ok", read_all(handle));
  25511. EXPECT_EQ("http://origin.example:8080/x", target);
  25512. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25513. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25514. }
  25515. TEST(NoProxyTest, ExactHostnameBypasses) {
  25516. ProxyAndTargetServers s;
  25517. auto cli = make_client("example.com", s);
  25518. cli->set_no_proxy({"example.com"});
  25519. auto res = cli->Get("/");
  25520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25521. EXPECT_EQ(0, s.proxy_hits());
  25522. EXPECT_EQ(1, s.target_hits());
  25523. }
  25524. TEST(NoProxyTest, SubdomainBypasses) {
  25525. ProxyAndTargetServers s;
  25526. auto cli = make_client("foo.example.com", s);
  25527. cli->set_no_proxy({"example.com"});
  25528. auto res = cli->Get("/");
  25529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25530. EXPECT_EQ(0, s.proxy_hits());
  25531. EXPECT_EQ(1, s.target_hits());
  25532. }
  25533. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25534. // Regression guard: "evilexample.com" must not be considered a subdomain
  25535. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25536. // check would let traffic bypass the proxy and leak credentials direct
  25537. // to the attacker host.
  25538. ProxyAndTargetServers s;
  25539. auto cli = make_client("evilexample.com", s);
  25540. cli->set_no_proxy({"example.com"});
  25541. auto res = cli->Get("/");
  25542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25543. EXPECT_GE(s.proxy_hits(), 1);
  25544. EXPECT_EQ(0, s.target_hits());
  25545. }
  25546. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25547. ProxyAndTargetServers s;
  25548. auto cli = make_client("example.com.evil.com", s);
  25549. cli->set_no_proxy({"example.com"});
  25550. auto res = cli->Get("/");
  25551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25552. EXPECT_GE(s.proxy_hits(), 1);
  25553. EXPECT_EQ(0, s.target_hits());
  25554. }
  25555. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25556. ProxyAndTargetServers s;
  25557. auto cli = make_client("example.com", s);
  25558. cli->set_no_proxy({".example.com"});
  25559. auto res = cli->Get("/");
  25560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25561. EXPECT_EQ(0, s.proxy_hits());
  25562. EXPECT_EQ(1, s.target_hits());
  25563. }
  25564. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25565. ProxyAndTargetServers s;
  25566. auto cli = make_client("Example.COM", s);
  25567. cli->set_no_proxy({"EXAMPLE.com"});
  25568. auto res = cli->Get("/");
  25569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25570. EXPECT_EQ(0, s.proxy_hits());
  25571. EXPECT_EQ(1, s.target_hits());
  25572. }
  25573. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25574. ProxyAndTargetServers s;
  25575. auto cli = make_client("example.com.", s);
  25576. cli->set_no_proxy({"example.com"});
  25577. auto res = cli->Get("/");
  25578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25579. EXPECT_EQ(0, s.proxy_hits());
  25580. EXPECT_EQ(1, s.target_hits());
  25581. }
  25582. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25583. // Trailing dots must be normalized on BOTH sides — host and entry.
  25584. // An implementation that only strips the host-side trailing dot would
  25585. // fail to match host "example.com" against entry "example.com." because
  25586. // a literal substring search would compare 11 chars against 12.
  25587. ProxyAndTargetServers s;
  25588. auto cli = make_client("example.com", s);
  25589. cli->set_no_proxy({"example.com."});
  25590. auto res = cli->Get("/");
  25591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25592. EXPECT_EQ(0, s.proxy_hits());
  25593. EXPECT_EQ(1, s.target_hits());
  25594. }
  25595. TEST(NoProxyTest, WildcardBypassesEverything) {
  25596. ProxyAndTargetServers s;
  25597. auto cli = make_client("anything.invalid.test", s);
  25598. cli->set_no_proxy({"*"});
  25599. auto res = cli->Get("/");
  25600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25601. EXPECT_EQ(0, s.proxy_hits());
  25602. EXPECT_EQ(1, s.target_hits());
  25603. }
  25604. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25605. ProxyAndTargetServers s;
  25606. Client cli("127.0.0.1", s.target_port());
  25607. cli.set_proxy("127.0.0.1", s.proxy_port());
  25608. cli.set_no_proxy({"127.0.0.1"});
  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, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25615. ProxyAndTargetServers s;
  25616. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25617. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25618. cli.set_proxy("127.0.0.1", s.proxy_port());
  25619. cli.set_no_proxy({"::1"});
  25620. auto res = cli.Get("/");
  25621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25622. EXPECT_EQ(0, s.proxy_hits());
  25623. EXPECT_EQ(1, s.target_hits());
  25624. }
  25625. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25626. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25627. // must still be recognized as IPv6 for CIDR matching. Implementations
  25628. // that detect IPv6 only when the host begins with '[' would parse the
  25629. // host as a hostname and miss the match.
  25630. ProxyAndTargetServers s;
  25631. Client cli("fe80::1", s.target_port());
  25632. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25633. cli.set_proxy("127.0.0.1", s.proxy_port());
  25634. cli.set_no_proxy({"fe80::/10"});
  25635. auto res = cli.Get("/");
  25636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25637. EXPECT_EQ(0, s.proxy_hits());
  25638. EXPECT_EQ(1, s.target_hits());
  25639. }
  25640. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25641. ProxyAndTargetServers s;
  25642. Client cli("::1", s.target_port());
  25643. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25644. cli.set_proxy("127.0.0.1", s.proxy_port());
  25645. cli.set_no_proxy({"[::1]"});
  25646. auto res = cli.Get("/");
  25647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25648. EXPECT_EQ(0, s.proxy_hits());
  25649. EXPECT_EQ(1, s.target_hits());
  25650. }
  25651. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25652. ProxyAndTargetServers s;
  25653. Client cli("fe80::1", s.target_port());
  25654. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25655. cli.set_proxy("127.0.0.1", s.proxy_port());
  25656. cli.set_no_proxy({"[fe80::]/10"});
  25657. auto res = cli.Get("/");
  25658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25659. EXPECT_EQ(0, s.proxy_hits());
  25660. EXPECT_EQ(1, s.target_hits());
  25661. }
  25662. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25663. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25664. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25665. // tricks via address-family conversion.
  25666. ProxyAndTargetServers s;
  25667. Client cli("::ffff:127.0.0.1", s.target_port());
  25668. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25669. cli.set_proxy("127.0.0.1", s.proxy_port());
  25670. cli.set_no_proxy({"127.0.0.1"});
  25671. auto res = cli.Get("/");
  25672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25673. EXPECT_GE(s.proxy_hits(), 1);
  25674. EXPECT_EQ(0, s.target_hits());
  25675. }
  25676. TEST(NoProxyTest, IPv4CidrMatch) {
  25677. ProxyAndTargetServers s;
  25678. Client cli("127.0.0.1", s.target_port());
  25679. cli.set_proxy("127.0.0.1", s.proxy_port());
  25680. cli.set_no_proxy({"127.0.0.0/8"});
  25681. auto res = cli.Get("/");
  25682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25683. EXPECT_EQ(0, s.proxy_hits());
  25684. EXPECT_EQ(1, s.target_hits());
  25685. }
  25686. TEST(NoProxyTest, IPv4CidrNonMatch) {
  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({"10.0.0.0/8"});
  25691. auto res = cli.Get("/");
  25692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25693. EXPECT_GE(s.proxy_hits(), 1);
  25694. EXPECT_EQ(0, s.target_hits());
  25695. }
  25696. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25697. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25698. // IPv4 target matches.
  25699. ProxyAndTargetServers s;
  25700. Client cli("127.0.0.1", s.target_port());
  25701. cli.set_proxy("127.0.0.1", s.proxy_port());
  25702. cli.set_no_proxy({"0.0.0.0/0"});
  25703. auto res = cli.Get("/");
  25704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25705. EXPECT_EQ(0, s.proxy_hits());
  25706. EXPECT_EQ(1, s.target_hits());
  25707. }
  25708. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  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({"127.0.0.1"});
  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, MalformedCidrPrefixIsDropped) {
  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.0/33"});
  25723. auto res = cli.Get("/");
  25724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25725. EXPECT_GE(s.proxy_hits(), 1);
  25726. EXPECT_EQ(0, s.target_hits());
  25727. }
  25728. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25729. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25730. ProxyAndTargetServers s;
  25731. Client cli("127.0.0.1", s.target_port());
  25732. cli.set_proxy("127.0.0.1", s.proxy_port());
  25733. cli.set_no_proxy({"127.0.0.1/"});
  25734. auto res = cli.Get("/");
  25735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25736. EXPECT_GE(s.proxy_hits(), 1);
  25737. EXPECT_EQ(0, s.target_hits());
  25738. }
  25739. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25740. ProxyAndTargetServers s;
  25741. auto cli = make_client("internal.corp", s);
  25742. cli->set_proxy_basic_auth("u", "p");
  25743. cli->set_no_proxy({"internal.corp"});
  25744. auto res = cli->Get("/");
  25745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25746. EXPECT_EQ(1, s.target_hits());
  25747. EXPECT_EQ(0, s.proxy_hits());
  25748. EXPECT_FALSE(s.last_had_proxy_authz())
  25749. << "Proxy-Authorization must not be sent direct to the target";
  25750. }
  25751. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25752. ProxyAndTargetServers s;
  25753. auto cli = make_client("public.example", s);
  25754. cli->set_proxy_basic_auth("u", "p");
  25755. cli->set_no_proxy({"internal.corp"}); // does not match
  25756. auto res = cli->Get("/");
  25757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25758. EXPECT_GE(s.proxy_hits(), 1);
  25759. EXPECT_TRUE(s.last_had_proxy_authz());
  25760. }
  25761. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25762. std::atomic<int> hits{0};
  25763. std::atomic<int> hits_with_authz{0};
  25764. no_proxy_test::ScopedServer proxy_mock;
  25765. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25766. hits++;
  25767. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25768. if (req.target.find("/redir") != std::string::npos) {
  25769. res.set_redirect("http://other.example/landed");
  25770. } else {
  25771. res.set_content("via-proxy", "text/plain");
  25772. }
  25773. });
  25774. proxy_mock.listen();
  25775. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25776. hits = 0;
  25777. hits_with_authz = 0;
  25778. Client cli("public.example", 80);
  25779. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25780. cli.set_proxy_basic_auth(c.first, c.second);
  25781. cli.set_follow_location(true);
  25782. // The redirect to another host goes through the proxy as well
  25783. auto res = cli.Get("/redir");
  25784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25785. EXPECT_EQ(2, hits.load());
  25786. EXPECT_EQ(2, hits_with_authz.load());
  25787. }
  25788. }
  25789. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25790. ProxyAndTargetServers s;
  25791. auto cli = make_client("anything.test", s);
  25792. auto res = cli->Get("/");
  25793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25794. EXPECT_GE(s.proxy_hits(), 1);
  25795. EXPECT_EQ(0, s.target_hits());
  25796. }
  25797. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25798. ProxyAndTargetServers s;
  25799. auto cli = make_client("example.com", s);
  25800. cli->set_no_proxy({"example.com:8080"});
  25801. auto res = cli->Get("/");
  25802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25803. EXPECT_GE(s.proxy_hits(), 1);
  25804. EXPECT_EQ(0, s.target_hits());
  25805. }
  25806. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25807. ProxyAndTargetServers s;
  25808. auto cli = make_client("anything.test", s);
  25809. cli->set_no_proxy({"", " ", "\t"});
  25810. auto res = cli->Get("/");
  25811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25812. EXPECT_GE(s.proxy_hits(), 1);
  25813. EXPECT_EQ(0, s.target_hits());
  25814. }
  25815. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25816. // An entry with leading/trailing whitespace must still match — env-style
  25817. // values are commonly pasted with stray spaces and an implementation
  25818. // that feeds the raw token directly to inet_pton would fail to match
  25819. // valid CIDRs because of the spaces.
  25820. ProxyAndTargetServers s;
  25821. Client cli("127.0.0.1", s.target_port());
  25822. cli.set_proxy("127.0.0.1", s.proxy_port());
  25823. cli.set_no_proxy({" 127.0.0.0/8 "});
  25824. auto res = cli.Get("/");
  25825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25826. EXPECT_EQ(0, s.proxy_hits());
  25827. EXPECT_EQ(1, s.target_hits());
  25828. }
  25829. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25830. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25831. // go direct and must NOT carry Proxy-Authorization.
  25832. std::atomic<int> proxy_hits{0};
  25833. std::atomic<int> target_hits{0};
  25834. std::atomic<bool> target_saw_authz{false};
  25835. no_proxy_test::ScopedServer proxy_mock, target;
  25836. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25837. proxy_hits++;
  25838. res.status = 302;
  25839. res.set_header("Location", "http://127.0.0.1:" +
  25840. std::to_string(target.port()) + "/landed");
  25841. });
  25842. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25843. target_hits++;
  25844. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25845. res.set_content("direct", "text/plain");
  25846. });
  25847. proxy_mock.listen();
  25848. target.listen();
  25849. Client cli("public.example", target.port());
  25850. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25851. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25852. cli.set_proxy_basic_auth("u", "p");
  25853. cli.set_no_proxy({"127.0.0.1"});
  25854. cli.set_follow_location(true);
  25855. auto res = cli.Get("/redir");
  25856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25857. EXPECT_GE(proxy_hits.load(), 1);
  25858. EXPECT_GE(target_hits.load(), 1);
  25859. EXPECT_FALSE(target_saw_authz.load());
  25860. }
  25861. #ifdef CPPHTTPLIB_SSL_ENABLED
  25862. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25863. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25864. // proxy creds would be sent to the (possibly hostile) origin.
  25865. std::atomic<int> target_hits{0};
  25866. std::atomic<bool> target_saw_proxy_authz{false};
  25867. no_proxy_test::ScopedServer target;
  25868. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25869. target_hits++;
  25870. if (req.has_header("Proxy-Authorization")) {
  25871. target_saw_proxy_authz = true;
  25872. }
  25873. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25874. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25875. "nonce=\"abc\", algorithm=MD5");
  25876. });
  25877. target.listen();
  25878. // The proxy address is set to the target's port: the bypass MUST kick in;
  25879. // if it doesn't, the test still routes "via proxy" to the same server and
  25880. // the Proxy-Authorization assertion below catches the leak.
  25881. Client cli("evil.example", target.port());
  25882. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25883. cli.set_proxy("127.0.0.1", target.port());
  25884. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25885. cli.set_no_proxy({"evil.example"});
  25886. auto res = cli.Get("/x");
  25887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25888. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25889. EXPECT_EQ(1, target_hits.load());
  25890. EXPECT_FALSE(target_saw_proxy_authz.load());
  25891. }
  25892. #endif
  25893. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25894. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25895. std::atomic<int> proxy_hits{0};
  25896. std::atomic<int> bypass_hits{0};
  25897. std::atomic<bool> proxy_saw_c_url{false};
  25898. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25899. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25900. proxy_hits++;
  25901. if (req.path.find("/start") != std::string::npos) {
  25902. res.status = 302;
  25903. res.set_header("Location", "http://127.0.0.1:" +
  25904. std::to_string(bypass_server.port()) +
  25905. "/middle");
  25906. return;
  25907. }
  25908. if (req.path.find("/end") != std::string::npos) {
  25909. proxy_saw_c_url = true;
  25910. res.set_content("c-via-proxy", "text/plain");
  25911. return;
  25912. }
  25913. res.set_content("unexpected", "text/plain");
  25914. });
  25915. // public.example's "advertised" port is arbitrary (the request never lands
  25916. // there — it goes through the proxy), but use a dynamic value to stay
  25917. // friendly with sharded parallel runs.
  25918. int public_port = bypass_server.port();
  25919. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25920. bypass_hits++;
  25921. res.status = 302;
  25922. res.set_header("Location", "http://public.example:" +
  25923. std::to_string(public_port) + "/end");
  25924. });
  25925. proxy_mock.listen();
  25926. bypass_server.listen();
  25927. Client cli("public.example", public_port);
  25928. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25929. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25930. cli.set_no_proxy({"127.0.0.1"});
  25931. cli.set_follow_location(true);
  25932. auto res = cli.Get("/start");
  25933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25934. EXPECT_EQ(StatusCode::OK_200, res->status);
  25935. EXPECT_EQ("c-via-proxy", res->body);
  25936. EXPECT_GE(proxy_hits.load(), 2);
  25937. EXPECT_GE(bypass_hits.load(), 1);
  25938. EXPECT_TRUE(proxy_saw_c_url.load());
  25939. }
  25940. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25941. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25942. // request reconnects to the correct endpoint.
  25943. std::atomic<int> proxy_hits{0};
  25944. std::atomic<int> target_hits{0};
  25945. no_proxy_test::ScopedServer proxy_mock, target;
  25946. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25947. proxy_hits++;
  25948. res.set_content("via-proxy", "text/plain");
  25949. });
  25950. target.svr().Get(".*", [&](const Request &, Response &res) {
  25951. target_hits++;
  25952. res.set_content("direct", "text/plain");
  25953. });
  25954. proxy_mock.listen();
  25955. target.listen();
  25956. Client cli("public.example", target.port());
  25957. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25958. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25959. cli.set_keep_alive(true);
  25960. auto res1 = cli.Get("/a");
  25961. ASSERT_TRUE(res1);
  25962. EXPECT_EQ("via-proxy", res1->body);
  25963. EXPECT_EQ(1, proxy_hits.load());
  25964. EXPECT_EQ(0, target_hits.load());
  25965. cli.set_no_proxy({"public.example"});
  25966. auto res2 = cli.Get("/b");
  25967. ASSERT_TRUE(res2);
  25968. EXPECT_EQ("direct", res2->body);
  25969. EXPECT_EQ(1, proxy_hits.load());
  25970. EXPECT_EQ(1, target_hits.load());
  25971. }
  25972. // Forward declarations (see the base64_encode note).
  25973. namespace httplib {
  25974. namespace detail {
  25975. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  25976. int shutdown_socket(socket_t sock) noexcept;
  25977. } // namespace detail
  25978. } // namespace httplib
  25979. namespace proxy_tunnel_test {
  25980. const char *const kTunnelEstablished =
  25981. "HTTP/1.1 200 Connection established\r\n\r\n";
  25982. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  25983. using ConnectReply = std::function<std::string(const std::string &head)>;
  25984. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  25985. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  25986. class ScopedConnectProxy {
  25987. public:
  25988. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  25989. : forward_port_(forward_port), reply_(std::move(reply)) {
  25990. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25991. if (listen_sock_ == INVALID_SOCKET) { return; }
  25992. auto a = loopback(0);
  25993. auto addr = reinterpret_cast<sockaddr *>(&a);
  25994. socklen_t alen = sizeof(a);
  25995. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  25996. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  25997. ::listen(listen_sock_, 4) != 0) {
  25998. return;
  25999. }
  26000. port_ = ntohs(a.sin_port);
  26001. th_ = std::thread([this] { run(); });
  26002. }
  26003. ~ScopedConnectProxy() {
  26004. if (th_.joinable()) {
  26005. stop_ = true;
  26006. auto wake = connect_to(port_);
  26007. th_.join();
  26008. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26009. }
  26010. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26011. }
  26012. int port() const { return port_; }
  26013. int connect_hits() const { return connect_hits_.load(); }
  26014. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26015. std::string connect_request() const {
  26016. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26017. return connect_request_;
  26018. }
  26019. private:
  26020. static sockaddr_in loopback(int port) {
  26021. sockaddr_in a{};
  26022. a.sin_family = AF_INET;
  26023. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26024. a.sin_port = htons(static_cast<unsigned short>(port));
  26025. return a;
  26026. }
  26027. static socket_t connect_to(int port) {
  26028. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26029. if (sock == INVALID_SOCKET) { return sock; }
  26030. auto a = loopback(port);
  26031. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26032. detail::close_socket(sock);
  26033. return INVALID_SOCKET;
  26034. }
  26035. return sock;
  26036. }
  26037. static bool send_all(socket_t sock, const char *data, size_t size) {
  26038. while (size > 0) {
  26039. auto n = detail::send_socket(sock, data, size, 0);
  26040. if (n <= 0) { return false; }
  26041. data += n;
  26042. size -= static_cast<size_t>(n);
  26043. }
  26044. return true;
  26045. }
  26046. void run() {
  26047. for (;;) {
  26048. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26049. if (stop_) {
  26050. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26051. return;
  26052. }
  26053. if (client == INVALID_SOCKET) { continue; }
  26054. serve(client);
  26055. detail::close_socket(client);
  26056. }
  26057. }
  26058. void serve(socket_t client) {
  26059. std::string head;
  26060. char buf[2048];
  26061. while (head.find("\r\n\r\n") == std::string::npos) {
  26062. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26063. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26064. if (n <= 0) { return; }
  26065. head.append(buf, static_cast<size_t>(n));
  26066. }
  26067. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26068. connect_hits_++;
  26069. {
  26070. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26071. connect_request_ = head;
  26072. }
  26073. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26074. if (!send_all(client, res.data(), res.size()) ||
  26075. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26076. return;
  26077. }
  26078. auto origin = connect_to(forward_port_);
  26079. if (origin == INVALID_SOCKET) { return; }
  26080. // When either side stops, shut both down so the other pump returns too.
  26081. auto pump = [&](socket_t from, socket_t to) {
  26082. char b[8192];
  26083. for (;;) {
  26084. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26085. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26086. }
  26087. detail::shutdown_socket(client);
  26088. detail::shutdown_socket(origin);
  26089. };
  26090. std::thread up([&] { pump(client, origin); });
  26091. pump(origin, client);
  26092. up.join();
  26093. detail::close_socket(origin);
  26094. }
  26095. int forward_port_;
  26096. ConnectReply reply_;
  26097. socket_t listen_sock_ = INVALID_SOCKET;
  26098. int port_ = 0;
  26099. std::thread th_;
  26100. std::atomic<bool> stop_{false};
  26101. std::atomic<int> connect_hits_{0};
  26102. mutable std::mutex connect_request_mutex_;
  26103. std::string connect_request_;
  26104. };
  26105. } // namespace proxy_tunnel_test
  26106. #ifdef CPPHTTPLIB_SSL_ENABLED
  26107. namespace proxy_tunnel_test {
  26108. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26109. class ScopedSSLServer {
  26110. public:
  26111. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26112. port_ = svr_.bind_to_any_port("127.0.0.1");
  26113. }
  26114. ~ScopedSSLServer() {
  26115. svr_.stop();
  26116. if (th_.joinable()) { th_.join(); }
  26117. }
  26118. SSLServer &svr() { return svr_; }
  26119. int port() const { return port_; }
  26120. void listen() {
  26121. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26122. svr_.wait_until_ready();
  26123. }
  26124. private:
  26125. SSLServer svr_;
  26126. std::thread th_;
  26127. int port_ = 0;
  26128. };
  26129. // Sends one request through the CONNECT proxy to the TLS origin with a
  26130. // credential configured for each hop, and checks that each credential reaches
  26131. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26132. // origin's (every header in origin_headers) on the tunnelled request.
  26133. void CredentialsStayWithTheirHop(
  26134. const std::function<void(SSLClient &)> &set_credentials,
  26135. const std::string &scheme,
  26136. const std::vector<std::string> &origin_headers = {"Authorization"},
  26137. bool stream = false) {
  26138. std::atomic<int> origin_hits{0};
  26139. std::atomic<bool> origin_saw_proxy_authz{false};
  26140. std::atomic<bool> origin_saw_headers{false};
  26141. ScopedSSLServer origin;
  26142. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26143. origin_hits++;
  26144. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26145. origin_saw_headers =
  26146. std::all_of(origin_headers.begin(), origin_headers.end(),
  26147. [&](const std::string &h) { return req.has_header(h); });
  26148. res.set_content("ok", "text/plain");
  26149. });
  26150. origin.listen();
  26151. ScopedConnectProxy proxy(origin.port());
  26152. ASSERT_NE(0, proxy.port());
  26153. // Pinned to 127.0.0.1 for the same reason as the test below.
  26154. SSLClient cli("127.0.0.1", origin.port());
  26155. cli.enable_server_certificate_verification(false);
  26156. cli.set_proxy("127.0.0.1", proxy.port());
  26157. set_credentials(cli);
  26158. if (stream) {
  26159. auto handle = cli.open_stream("GET", "/x");
  26160. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26161. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26162. } else {
  26163. auto res = cli.Get("/x");
  26164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26165. EXPECT_EQ(StatusCode::OK_200, res->status);
  26166. }
  26167. EXPECT_EQ(1, origin_hits.load());
  26168. EXPECT_EQ(1, proxy.connect_hits());
  26169. EXPECT_TRUE(origin_saw_headers.load());
  26170. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26171. << "Proxy-Authorization must not be sent inside the tunnel";
  26172. auto connect_req = proxy.connect_request();
  26173. EXPECT_NE(std::string::npos,
  26174. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26175. for (const auto &h : origin_headers) {
  26176. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26177. << h << " must not be sent to the proxy on CONNECT";
  26178. }
  26179. }
  26180. } // namespace proxy_tunnel_test
  26181. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26182. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26183. [](SSLClient &cli) {
  26184. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26185. cli.set_basic_auth("origin-user", "origin-pass");
  26186. },
  26187. "Basic");
  26188. }
  26189. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26190. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26191. [](SSLClient &cli) {
  26192. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26193. cli.set_basic_auth("origin-user", "origin-pass");
  26194. },
  26195. "Basic", {"Authorization"}, true);
  26196. }
  26197. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26198. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26199. [](SSLClient &cli) {
  26200. cli.set_proxy_bearer_token_auth("proxy-token");
  26201. cli.set_bearer_token_auth("origin-token");
  26202. },
  26203. "Bearer");
  26204. }
  26205. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26206. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26207. [](SSLClient &cli) {
  26208. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26209. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26210. {"Cookie", "sid=origin-session"},
  26211. {"X-Api-Key", "origin-key"}});
  26212. },
  26213. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26214. }
  26215. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26216. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26217. // retry; otherwise proxy creds would be sent to the origin.
  26218. std::atomic<int> origin_hits{0};
  26219. std::atomic<bool> origin_saw_proxy_authz{false};
  26220. proxy_tunnel_test::ScopedSSLServer origin;
  26221. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26222. origin_hits++;
  26223. if (req.has_header("Proxy-Authorization")) {
  26224. origin_saw_proxy_authz = true;
  26225. }
  26226. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26227. res.set_header("Proxy-Authenticate",
  26228. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26229. "algorithm=MD5");
  26230. });
  26231. origin.listen();
  26232. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26233. ASSERT_NE(0, proxy.port());
  26234. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26235. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26236. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26237. // and answer with its own status, making this test flaky.
  26238. SSLClient cli("127.0.0.1", origin.port());
  26239. cli.enable_server_certificate_verification(false);
  26240. cli.set_proxy("127.0.0.1", proxy.port());
  26241. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26242. auto res = cli.Get("/x");
  26243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26244. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26245. EXPECT_EQ(1, origin_hits.load());
  26246. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26247. EXPECT_EQ(1, proxy.connect_hits());
  26248. }
  26249. #endif
  26250. namespace proxy_tunnel_test {
  26251. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26252. // anything else gets a 407 with `challenge`.
  26253. ConnectReply require_proxy_auth(const std::string &expected,
  26254. const std::string &challenge) {
  26255. return [=](const std::string &head) -> std::string {
  26256. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26257. std::string::npos) {
  26258. return kTunnelEstablished;
  26259. }
  26260. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26261. "Proxy-Authenticate: " +
  26262. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26263. };
  26264. }
  26265. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26266. // request, then echoes.
  26267. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26268. ws.send(
  26269. "authorization:" + req.get_header_value("Authorization") +
  26270. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26271. std::string msg;
  26272. while (ws.read(msg)) {
  26273. ws.send(msg);
  26274. }
  26275. }
  26276. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26277. class ScopedWebSocketOrigin {
  26278. public:
  26279. ScopedWebSocketOrigin() {
  26280. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26281. server_.listen();
  26282. }
  26283. int port() const { return server_.port(); }
  26284. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26285. std::string url() const {
  26286. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26287. }
  26288. private:
  26289. no_proxy_test::ScopedServer server_;
  26290. };
  26291. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26292. // passed as a constructor header, and checks that each reaches only its hop.
  26293. void WebSocketCredentialsStayWithTheirHop(
  26294. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26295. const std::string &proxy_authz, const std::string &origin_authz) {
  26296. ScopedWebSocketOrigin origin;
  26297. ScopedConnectProxy proxy(
  26298. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26299. ASSERT_NE(0, proxy.port());
  26300. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26301. client.set_proxy("127.0.0.1", proxy.port());
  26302. set_proxy_credentials(client);
  26303. auto res = client.connect();
  26304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26305. std::string msg;
  26306. ASSERT_TRUE(client.read(msg));
  26307. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26308. client.close();
  26309. EXPECT_EQ(1, proxy.connect_hits());
  26310. EXPECT_EQ(std::string::npos,
  26311. proxy.connect_request().find("\r\nAuthorization: "))
  26312. << "origin credentials must not be sent to the proxy";
  26313. }
  26314. } // namespace proxy_tunnel_test
  26315. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26316. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26317. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26318. ASSERT_NE(0, proxy.port());
  26319. ws::WebSocketClient client(origin.url());
  26320. client.set_proxy("127.0.0.1", proxy.port());
  26321. auto res = client.connect();
  26322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26323. std::string msg;
  26324. ASSERT_TRUE(client.read(msg));
  26325. ASSERT_TRUE(client.send("hello"));
  26326. ASSERT_TRUE(client.read(msg));
  26327. EXPECT_EQ("hello", msg);
  26328. client.close();
  26329. EXPECT_EQ(1, proxy.connect_hits());
  26330. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26331. auto connect_req = proxy.connect_request();
  26332. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26333. EXPECT_NE(std::string::npos,
  26334. connect_req.find("\r\nHost: " + target + "\r\n"));
  26335. }
  26336. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26337. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26338. [](ws::WebSocketClient &cli) {
  26339. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26340. },
  26341. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26342. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26343. }
  26344. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26345. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26346. [](ws::WebSocketClient &cli) {
  26347. cli.set_proxy_bearer_token_auth("proxy-token");
  26348. },
  26349. "Bearer proxy-token", "Bearer origin-token");
  26350. }
  26351. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26352. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26353. proxy_tunnel_test::ScopedConnectProxy proxy(
  26354. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26355. "Basic " + detail::base64_encode("proxy-user:"),
  26356. "Basic realm=\"proxy\""));
  26357. ASSERT_NE(0, proxy.port());
  26358. ws::WebSocketClient client(origin.url());
  26359. client.set_proxy("127.0.0.1", proxy.port());
  26360. client.set_proxy_basic_auth("proxy-user", "");
  26361. auto res = client.connect();
  26362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26363. client.close();
  26364. EXPECT_EQ(1, proxy.connect_hits());
  26365. }
  26366. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26367. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26368. proxy_tunnel_test::ScopedConnectProxy proxy(
  26369. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26370. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26371. ASSERT_NE(0, proxy.port());
  26372. ws::WebSocketClient client(origin.url());
  26373. client.set_proxy("127.0.0.1", proxy.port());
  26374. auto res = client.connect();
  26375. EXPECT_FALSE(res);
  26376. EXPECT_EQ(Error::ProxyConnection, res.error());
  26377. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26378. EXPECT_EQ("Basic realm=\"proxy\"",
  26379. res.get_header_value("Proxy-Authenticate"));
  26380. EXPECT_FALSE(client.is_open());
  26381. }
  26382. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26383. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26384. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26385. ASSERT_NE(0, proxy.port());
  26386. ws::WebSocketClient client(origin.url());
  26387. client.set_proxy("127.0.0.1", proxy.port());
  26388. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26389. client.set_no_proxy({"127.0.0.1"});
  26390. auto res = client.connect();
  26391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26392. std::string msg;
  26393. ASSERT_TRUE(client.read(msg));
  26394. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26395. << "proxy credentials must not reach a bypassed origin";
  26396. client.close();
  26397. EXPECT_EQ(0, proxy.connect_hits());
  26398. }
  26399. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26400. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26401. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26402. ASSERT_NE(0, proxy.port());
  26403. ws::WebSocketClient client(origin.url());
  26404. client.set_proxy("127.0.0.1", proxy.port());
  26405. ASSERT_TRUE(client.connect());
  26406. ASSERT_TRUE(client.connect());
  26407. client.close();
  26408. EXPECT_EQ(2, proxy.connect_hits());
  26409. }
  26410. #ifdef CPPHTTPLIB_SSL_ENABLED
  26411. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26412. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26413. proxy_tunnel_test::ScopedConnectProxy proxy(
  26414. origin.port(), [](const std::string &head) -> std::string {
  26415. if (head.find(
  26416. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26417. std::string::npos) {
  26418. return proxy_tunnel_test::kTunnelEstablished;
  26419. }
  26420. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26421. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26422. "nonce=\"abc\", algorithm=MD5\r\n"
  26423. "Content-Length: 0\r\n\r\n";
  26424. });
  26425. ASSERT_NE(0, proxy.port());
  26426. ws::WebSocketClient client(origin.url());
  26427. client.set_proxy("127.0.0.1", proxy.port());
  26428. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26429. auto res = client.connect();
  26430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26431. std::string msg;
  26432. ASSERT_TRUE(client.read(msg));
  26433. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26434. client.close();
  26435. EXPECT_EQ(2, proxy.connect_hits());
  26436. }
  26437. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26438. proxy_tunnel_test::ScopedSSLServer origin;
  26439. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26440. origin.listen();
  26441. proxy_tunnel_test::ScopedConnectProxy proxy(
  26442. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26443. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26444. ASSERT_NE(0, proxy.port());
  26445. ws::WebSocketClient client(
  26446. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26447. client.enable_server_certificate_verification(false);
  26448. client.set_proxy("127.0.0.1", proxy.port());
  26449. client.set_proxy_bearer_token_auth("proxy-token");
  26450. auto res = client.connect();
  26451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26452. std::string msg;
  26453. ASSERT_TRUE(client.read(msg));
  26454. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26455. << "Proxy-Authorization must not be sent inside the tunnel";
  26456. client.close();
  26457. EXPECT_EQ(1, proxy.connect_hits());
  26458. }
  26459. #endif