1
0

test.cc 455 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866
  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 <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. const int PORT = 1234;
  53. const string LONG_QUERY_VALUE = string(25000, '@');
  54. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  55. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  56. const string TOO_LONG_QUERY_URL =
  57. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  58. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  59. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  60. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  61. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  62. return file.name == key;
  63. });
  64. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  65. return *it;
  66. #else
  67. if (it != items.end()) { return *it; }
  68. throw std::runtime_error("invalid multipart form data name error");
  69. #endif
  70. }
  71. static void read_file(const std::string &path, std::string &out) {
  72. std::ifstream fs(path, std::ios_base::binary);
  73. if (!fs) {
  74. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  75. return;
  76. #else
  77. throw std::runtime_error("File not found: " + path);
  78. #endif
  79. }
  80. fs.seekg(0, std::ios_base::end);
  81. auto size = fs.tellg();
  82. fs.seekg(0);
  83. out.resize(static_cast<size_t>(size));
  84. fs.read(&out[0], static_cast<std::streamsize>(size));
  85. }
  86. void performance_test(const char *host) {
  87. Server svr;
  88. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  89. res.set_content("Benchmark Response", "text/plain");
  90. });
  91. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  92. auto se = detail::scope_exit([&] {
  93. svr.stop();
  94. listen_thread.join();
  95. ASSERT_FALSE(svr.is_running());
  96. });
  97. svr.wait_until_ready();
  98. Client cli(host, PORT);
  99. // Warm-up request to establish connection and resolve DNS
  100. auto warmup_res = cli.Get("/benchmark");
  101. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  102. // Run multiple trials and collect timings
  103. const int num_trials = 20;
  104. std::vector<int64_t> timings;
  105. timings.reserve(num_trials);
  106. for (int i = 0; i < num_trials; i++) {
  107. auto start = std::chrono::high_resolution_clock::now();
  108. auto res = cli.Get("/benchmark");
  109. auto end = std::chrono::high_resolution_clock::now();
  110. auto elapsed =
  111. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  112. .count();
  113. // Assertions after timing measurement to avoid overhead
  114. ASSERT_TRUE(res);
  115. EXPECT_EQ(StatusCode::OK_200, res->status);
  116. timings.push_back(elapsed);
  117. }
  118. // Calculate 25th percentile (lower quartile)
  119. std::sort(timings.begin(), timings.end());
  120. auto p25 = timings[num_trials / 4];
  121. // Format timings for output
  122. std::ostringstream timings_str;
  123. timings_str << "[";
  124. for (size_t i = 0; i < timings.size(); i++) {
  125. if (i > 0) timings_str << ", ";
  126. timings_str << timings[i];
  127. }
  128. timings_str << "]";
  129. // Localhost HTTP GET should be fast even in CI environments
  130. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  131. << "ms (Issue #1777). Timings: " << timings_str.str();
  132. }
  133. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  134. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  135. class UnixSocketTest : public ::testing::Test {
  136. protected:
  137. void TearDown() override { std::remove(pathname_.c_str()); }
  138. void client_GET(const std::string &addr) {
  139. httplib::Client cli{addr};
  140. cli.set_address_family(AF_UNIX);
  141. ASSERT_TRUE(cli.is_valid());
  142. const auto &result = cli.Get(pattern_);
  143. ASSERT_TRUE(result) << "error: " << result.error();
  144. const auto &resp = result.value();
  145. EXPECT_EQ(resp.status, StatusCode::OK_200);
  146. EXPECT_EQ(resp.body, content_);
  147. }
  148. const std::string pathname_{"./httplib-server.sock"};
  149. const std::string pattern_{"/hi"};
  150. const std::string content_{"Hello World!"};
  151. };
  152. TEST_F(UnixSocketTest, pathname) {
  153. httplib::Server svr;
  154. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  155. res.set_content(content_, "text/plain");
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. client_GET(pathname_);
  168. }
  169. #if defined(__linux__) || \
  170. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  171. TEST_F(UnixSocketTest, PeerPid) {
  172. httplib::Server svr;
  173. std::string remote_port_val;
  174. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  175. res.set_content(content_, "text/plain");
  176. remote_port_val = std::to_string(req.remote_port);
  177. });
  178. std::thread t{[&] {
  179. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  180. }};
  181. auto se = detail::scope_exit([&] {
  182. svr.stop();
  183. t.join();
  184. ASSERT_FALSE(svr.is_running());
  185. });
  186. svr.wait_until_ready();
  187. ASSERT_TRUE(svr.is_running());
  188. client_GET(pathname_);
  189. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  190. }
  191. #endif
  192. #ifdef __linux__
  193. TEST_F(UnixSocketTest, abstract) {
  194. constexpr char svr_path[]{"\x00httplib-server.sock"};
  195. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  196. httplib::Server svr;
  197. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  198. res.set_content(content_, "text/plain");
  199. });
  200. std::thread t{[&] {
  201. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  202. }};
  203. auto se = detail::scope_exit([&] {
  204. svr.stop();
  205. t.join();
  206. ASSERT_FALSE(svr.is_running());
  207. });
  208. svr.wait_until_ready();
  209. ASSERT_TRUE(svr.is_running());
  210. client_GET(abstract_addr);
  211. }
  212. #endif
  213. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  214. httplib::Server svr;
  215. std::string received_host_header;
  216. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  217. // Capture the Host header sent by the client
  218. auto host_iter = req.headers.find("Host");
  219. if (host_iter != req.headers.end()) {
  220. received_host_header = host_iter->second;
  221. }
  222. res.set_content(content_, "text/plain");
  223. });
  224. std::thread t{[&] {
  225. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  226. }};
  227. auto se = detail::scope_exit([&] {
  228. svr.stop();
  229. t.join();
  230. ASSERT_FALSE(svr.is_running());
  231. });
  232. svr.wait_until_ready();
  233. ASSERT_TRUE(svr.is_running());
  234. // Test that Host header is automatically set to "localhost" for Unix socket
  235. // connections
  236. httplib::Client cli{pathname_};
  237. cli.set_address_family(AF_UNIX);
  238. ASSERT_TRUE(cli.is_valid());
  239. const auto &result = cli.Get(pattern_);
  240. ASSERT_TRUE(result) << "error: " << result.error();
  241. const auto &resp = result.value();
  242. EXPECT_EQ(resp.status, StatusCode::OK_200);
  243. EXPECT_EQ(resp.body, content_);
  244. // Verify that Host header was automatically set to "localhost"
  245. EXPECT_EQ(received_host_header, "localhost");
  246. }
  247. #ifndef _WIN32
  248. TEST(SocketStream, wait_writable_UNIX) {
  249. int fds[2];
  250. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  251. const auto asSocketStream = [&](socket_t fd,
  252. std::function<bool(Stream &)> func) {
  253. return detail::process_client_socket(
  254. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  255. };
  256. asSocketStream(fds[0], [&](Stream &s0) {
  257. EXPECT_EQ(s0.socket(), fds[0]);
  258. EXPECT_TRUE(s0.wait_writable());
  259. EXPECT_EQ(0, close(fds[1]));
  260. EXPECT_FALSE(s0.wait_writable());
  261. return true;
  262. });
  263. EXPECT_EQ(0, close(fds[0]));
  264. }
  265. TEST(SocketStream, wait_writable_INET) {
  266. sockaddr_in addr;
  267. memset(&addr, 0, sizeof(addr));
  268. addr.sin_family = AF_INET;
  269. addr.sin_port = htons(PORT + 1);
  270. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  271. int disconnected_svr_sock = -1;
  272. std::thread svr{[&] {
  273. const int s = socket(AF_INET, SOCK_STREAM, 0);
  274. ASSERT_LE(0, s);
  275. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  276. ASSERT_EQ(0, listen(s, 1));
  277. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  281. std::thread cli{[&] {
  282. const int s = socket(AF_INET, SOCK_STREAM, 0);
  283. ASSERT_LE(0, s);
  284. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  285. ASSERT_EQ(0, close(s));
  286. }};
  287. cli.join();
  288. svr.join();
  289. ASSERT_NE(disconnected_svr_sock, -1);
  290. const auto asSocketStream = [&](socket_t fd,
  291. std::function<bool(Stream &)> func) {
  292. return detail::process_client_socket(
  293. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  294. };
  295. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  296. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  297. EXPECT_FALSE(ss.wait_writable());
  298. return true;
  299. });
  300. ASSERT_EQ(0, close(disconnected_svr_sock));
  301. }
  302. #endif // #ifndef _WIN32
  303. TEST(ClientTest, MoveConstructible) {
  304. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  305. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  306. }
  307. TEST(ClientTest, MoveAssignable) {
  308. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  309. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  310. }
  311. #ifdef _WIN32
  312. TEST(StartupTest, WSAStartup) {
  313. WSADATA wsaData;
  314. int ret = WSAStartup(0x0002, &wsaData);
  315. ASSERT_EQ(0, ret);
  316. }
  317. #endif
  318. TEST(DecodePathTest, PercentCharacter) {
  319. EXPECT_EQ(
  320. decode_path_component(
  321. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  322. U8("descrip=Gastos áéíóúñÑ 6"));
  323. }
  324. TEST(DecodePathTest, PercentCharacterNUL) {
  325. string expected;
  326. expected.push_back('x');
  327. expected.push_back('\0');
  328. expected.push_back('x');
  329. EXPECT_EQ(decode_path_component("x%00x"), expected);
  330. }
  331. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  332. string unescapedCharacters = "-_.!~*'()";
  333. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  334. }
  335. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  336. string reservedCharacters = ";,/?:@&=+$";
  337. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  338. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  339. }
  340. TEST(ClientQueryOrder, PreserveOrder) {
  341. // This test reproduces Issue #2259: client may reorder query parameters
  342. // when sending a GET request. The expected behavior is that the client
  343. // preserves the original query string order when the caller supplied it
  344. // as part of the path.
  345. Server svr;
  346. svr.Get("/", [&](const Request &req, Response &res) {
  347. // Echo back the raw target so the test can assert ordering
  348. res.set_content(req.target, "text/plain");
  349. });
  350. std::thread t{[&] { svr.listen(HOST, PORT); }};
  351. auto se = detail::scope_exit([&] {
  352. svr.stop();
  353. t.join();
  354. ASSERT_FALSE(svr.is_running());
  355. });
  356. svr.wait_until_ready();
  357. Client cli(HOST, PORT);
  358. ASSERT_TRUE(cli.is_valid());
  359. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  360. auto res = cli.Get(original);
  361. ASSERT_TRUE(res);
  362. // Expect the echoed target to exactly match the original path (order
  363. // preserved)
  364. EXPECT_EQ(res->body, original);
  365. }
  366. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  367. string chineseCharacters = U8("中国語");
  368. string russianCharacters = U8("дом");
  369. string brazilianCharacters = U8("óculos");
  370. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  371. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  372. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  373. "%D0%B4%D0%BE%D0%BC");
  374. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  375. }
  376. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  377. string unescapedCharacters = "-_.!~*'()";
  378. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  379. }
  380. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  381. string reservedCharacters = ";,/?:@&=+$";
  382. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  383. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  384. }
  385. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  386. string chineseCharacters = U8("中国語");
  387. string russianCharacters = U8("дом");
  388. string brazilianCharacters = U8("óculos");
  389. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  390. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  391. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  392. "%D0%B4%D0%BE%D0%BC");
  393. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  394. }
  395. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  396. // Issue #2082 use case: encoding path component with ampersand
  397. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  398. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  399. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  400. }
  401. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  402. string unescapedCharacters = "-_.!~*'()";
  403. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  404. }
  405. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  406. string reservedCharacters = ";,/?:@&=+$#";
  407. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  408. }
  409. TEST(EncodeUriTest, TestUTF8Characters) {
  410. string chineseCharacters = U8("中国語");
  411. string russianCharacters = U8("дом");
  412. string brazilianCharacters = U8("óculos");
  413. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  414. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  415. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  416. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  417. }
  418. TEST(EncodeUriTest, TestCompleteUri) {
  419. string uri =
  420. "https://example.com/path/to/resource?query=value&param=test#fragment";
  421. EXPECT_EQ(
  422. httplib::encode_uri(uri),
  423. "https://example.com/path/to/resource?query=value&param=test#fragment");
  424. }
  425. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  426. string uri =
  427. "https://example.com/path with spaces/file name.html?q=hello world";
  428. EXPECT_EQ(httplib::encode_uri(uri),
  429. "https://example.com/path%20with%20spaces/"
  430. "file%20name.html?q=hello%20world");
  431. }
  432. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  433. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  434. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  435. }
  436. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  437. string unescapedCharacters = "-_.!~*'()";
  438. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  439. }
  440. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  441. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  442. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  443. string encodedBrazilian = "%C3%B3culos";
  444. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  445. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  446. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  447. }
  448. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  449. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  451. "Piri Tommy Villiers - on & on");
  452. }
  453. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  454. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  455. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  456. }
  457. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  458. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  459. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  460. }
  461. TEST(DecodeUriTest, TestUTF8Characters) {
  462. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  463. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  464. string encodedBrazilian = "%C3%B3culos";
  465. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  466. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  467. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  468. }
  469. TEST(DecodeUriTest, TestCompleteUri) {
  470. string encodedUri = "https://example.com/path%20with%20spaces/"
  471. "file%20name.html?q=hello%20world";
  472. EXPECT_EQ(
  473. httplib::decode_uri(encodedUri),
  474. "https://example.com/path with spaces/file name.html?q=hello world");
  475. }
  476. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  477. string original =
  478. "https://example.com/path with spaces/file name.html?q=hello world";
  479. string encoded = httplib::encode_uri(original);
  480. string decoded = httplib::decode_uri(encoded);
  481. EXPECT_EQ(decoded, original);
  482. }
  483. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  484. string original = "Piri Tommy Villiers - on & on";
  485. string encoded = httplib::encode_uri_component(original);
  486. string decoded = httplib::decode_uri_component(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(TrimTests, TrimStringTests) {
  490. EXPECT_EQ("abc", detail::trim_copy("abc"));
  491. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  492. EXPECT_TRUE(detail::trim_copy("").empty());
  493. }
  494. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  495. // Simple case without quality values
  496. std::vector<std::string> result1;
  497. EXPECT_TRUE(detail::parse_accept_header(
  498. "text/html,application/json,text/plain", result1));
  499. EXPECT_EQ(result1.size(), 3U);
  500. EXPECT_EQ(result1[0], "text/html");
  501. EXPECT_EQ(result1[1], "application/json");
  502. EXPECT_EQ(result1[2], "text/plain");
  503. // With quality values
  504. std::vector<std::string> result2;
  505. EXPECT_TRUE(detail::parse_accept_header(
  506. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  507. EXPECT_EQ(result2.size(), 3U);
  508. EXPECT_EQ(result2[0], "application/json"); // highest q value
  509. EXPECT_EQ(result2[1], "text/html");
  510. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  511. }
  512. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  513. // Mixed with and without quality values
  514. std::vector<std::string> result;
  515. EXPECT_TRUE(detail::parse_accept_header(
  516. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  517. EXPECT_EQ(result.size(), 3U);
  518. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  519. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  520. EXPECT_EQ(result[2], "application/json"); // q=0.5
  521. }
  522. TEST(ParseAcceptHeaderTest, EdgeCases) {
  523. // Empty header
  524. std::vector<std::string> empty_result;
  525. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  526. EXPECT_TRUE(empty_result.empty());
  527. // Single type
  528. std::vector<std::string> single_result;
  529. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  530. EXPECT_EQ(single_result.size(), 1U);
  531. EXPECT_EQ(single_result[0], "application/json");
  532. // Wildcard types
  533. std::vector<std::string> wildcard_result;
  534. EXPECT_TRUE(detail::parse_accept_header(
  535. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  536. EXPECT_EQ(wildcard_result.size(), 3U);
  537. EXPECT_EQ(wildcard_result[0], "application/json");
  538. EXPECT_EQ(wildcard_result[1], "text/*");
  539. EXPECT_EQ(wildcard_result[2], "*/*");
  540. }
  541. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  542. // Common browser Accept header
  543. std::vector<std::string> browser_result;
  544. EXPECT_TRUE(
  545. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  546. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  547. browser_result));
  548. EXPECT_EQ(browser_result.size(), 6U);
  549. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  550. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  551. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  552. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  553. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  554. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  555. // API client header
  556. std::vector<std::string> api_result;
  557. EXPECT_TRUE(detail::parse_accept_header(
  558. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  559. api_result));
  560. EXPECT_EQ(api_result.size(), 3U);
  561. EXPECT_EQ(api_result[0], "application/json");
  562. EXPECT_EQ(api_result[1], "application/xml");
  563. EXPECT_EQ(api_result[2], "text/plain");
  564. }
  565. TEST(ParseAcceptHeaderTest, SpecialCases) {
  566. // Quality value with 3 decimal places
  567. std::vector<std::string> decimal_result;
  568. EXPECT_TRUE(detail::parse_accept_header(
  569. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  570. EXPECT_EQ(decimal_result.size(), 2U);
  571. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  572. EXPECT_EQ(decimal_result[1], "text/html");
  573. // Zero quality (should still be included but with lowest priority)
  574. std::vector<std::string> zero_q_result;
  575. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  576. zero_q_result));
  577. EXPECT_EQ(zero_q_result.size(), 2U);
  578. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  579. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  580. // No spaces around commas
  581. std::vector<std::string> no_space_result;
  582. EXPECT_TRUE(detail::parse_accept_header(
  583. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  584. no_space_result));
  585. EXPECT_EQ(no_space_result.size(), 3U);
  586. EXPECT_EQ(no_space_result[0], "text/html");
  587. EXPECT_EQ(no_space_result[1], "application/json");
  588. EXPECT_EQ(no_space_result[2], "text/plain");
  589. }
  590. TEST(ParseAcceptHeaderTest, InvalidCases) {
  591. std::vector<std::string> result;
  592. // Invalid quality value (> 1.0)
  593. EXPECT_FALSE(
  594. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  595. // Invalid quality value (< 0.0)
  596. EXPECT_FALSE(
  597. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  598. // Invalid quality value (not a number)
  599. EXPECT_FALSE(detail::parse_accept_header(
  600. "text/html;q=invalid,application/json", result));
  601. // Empty quality value
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=,application/json", result));
  604. // Invalid media type format (no slash and not wildcard)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("invalidtype,application/json", result));
  607. // Empty media type
  608. result.clear();
  609. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  610. // Only commas
  611. result.clear();
  612. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  613. // Valid cases should still work
  614. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  615. EXPECT_EQ(result.size(), 1U);
  616. EXPECT_EQ(result[0], "*/*");
  617. EXPECT_TRUE(detail::parse_accept_header("*", result));
  618. EXPECT_EQ(result.size(), 1U);
  619. EXPECT_EQ(result[0], "*");
  620. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "text/*");
  623. }
  624. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  625. Server svr;
  626. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  627. EXPECT_EQ(req.accept_content_types.size(), 3U);
  628. EXPECT_EQ(req.accept_content_types[0], "application/json");
  629. EXPECT_EQ(req.accept_content_types[1], "text/html");
  630. EXPECT_EQ(req.accept_content_types[2], "*/*");
  631. res.set_content("ok", "text/plain");
  632. });
  633. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  634. EXPECT_TRUE(false);
  635. res.set_content("bad request", "text/plain");
  636. });
  637. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  638. auto se = detail::scope_exit([&] {
  639. svr.stop();
  640. listen_thread.join();
  641. ASSERT_FALSE(svr.is_running());
  642. });
  643. svr.wait_until_ready();
  644. Client cli("localhost", PORT);
  645. {
  646. auto res =
  647. cli.Get("/accept_ok",
  648. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  649. ASSERT_TRUE(res);
  650. EXPECT_EQ(StatusCode::OK_200, res->status);
  651. }
  652. {
  653. auto res = cli.Get("/accept_bad_request",
  654. {{"Accept", "text/html;q=abc,application/json"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  657. }
  658. }
  659. TEST(DivideTest, DivideStringTests) {
  660. auto divide = [](const std::string &str, char d) {
  661. std::string lhs;
  662. std::string rhs;
  663. detail::divide(str, d,
  664. [&](const char *lhs_data, std::size_t lhs_size,
  665. const char *rhs_data, std::size_t rhs_size) {
  666. lhs.assign(lhs_data, lhs_size);
  667. rhs.assign(rhs_data, rhs_size);
  668. });
  669. return std::make_pair(std::move(lhs), std::move(rhs));
  670. };
  671. {
  672. const auto res = divide("", '=');
  673. EXPECT_EQ(res.first, "");
  674. EXPECT_EQ(res.second, "");
  675. }
  676. {
  677. const auto res = divide("=", '=');
  678. EXPECT_EQ(res.first, "");
  679. EXPECT_EQ(res.second, "");
  680. }
  681. {
  682. const auto res = divide(" ", '=');
  683. EXPECT_EQ(res.first, " ");
  684. EXPECT_EQ(res.second, "");
  685. }
  686. {
  687. const auto res = divide("a", '=');
  688. EXPECT_EQ(res.first, "a");
  689. EXPECT_EQ(res.second, "");
  690. }
  691. {
  692. const auto res = divide("a=", '=');
  693. EXPECT_EQ(res.first, "a");
  694. EXPECT_EQ(res.second, "");
  695. }
  696. {
  697. const auto res = divide("=b", '=');
  698. EXPECT_EQ(res.first, "");
  699. EXPECT_EQ(res.second, "b");
  700. }
  701. {
  702. const auto res = divide("a=b", '=');
  703. EXPECT_EQ(res.first, "a");
  704. EXPECT_EQ(res.second, "b");
  705. }
  706. {
  707. const auto res = divide("a=b=", '=');
  708. EXPECT_EQ(res.first, "a");
  709. EXPECT_EQ(res.second, "b=");
  710. }
  711. {
  712. const auto res = divide("a=b=c", '=');
  713. EXPECT_EQ(res.first, "a");
  714. EXPECT_EQ(res.second, "b=c");
  715. }
  716. }
  717. TEST(SplitTest, ParseQueryString) {
  718. string s = "key1=val1&key2=val2&key3=val3";
  719. Params dic;
  720. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  721. [&](const char *b, const char *e) {
  722. string key, val;
  723. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  724. if (key.empty()) {
  725. key.assign(b2, e2);
  726. } else {
  727. val.assign(b2, e2);
  728. }
  729. });
  730. dic.emplace(key, val);
  731. });
  732. EXPECT_EQ("val1", dic.find("key1")->second);
  733. EXPECT_EQ("val2", dic.find("key2")->second);
  734. EXPECT_EQ("val3", dic.find("key3")->second);
  735. }
  736. TEST(SplitTest, ParseInvalidQueryTests) {
  737. {
  738. string s = " ";
  739. Params dict;
  740. detail::parse_query_text(s, dict);
  741. EXPECT_TRUE(dict.empty());
  742. }
  743. {
  744. string s = " = =";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. }
  750. TEST(ParseQueryTest, ParseQueryString) {
  751. {
  752. std::string s = "key1=val1&key2=val2&key3=val3";
  753. Params dic;
  754. detail::parse_query_text(s, dic);
  755. EXPECT_EQ("val1", dic.find("key1")->second);
  756. EXPECT_EQ("val2", dic.find("key2")->second);
  757. EXPECT_EQ("val3", dic.find("key3")->second);
  758. }
  759. {
  760. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  761. Params dic;
  762. detail::parse_query_text(s, dic);
  763. EXPECT_EQ("", dic.find("key1")->second);
  764. EXPECT_EQ("val1", dic.find("key2")->second);
  765. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  766. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  767. }
  768. }
  769. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  770. Params dic;
  771. EXPECT_EQ(detail::params_to_query_str(dic), "");
  772. dic.emplace("key1", "val1");
  773. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  774. dic.emplace("key2", "val2");
  775. dic.emplace("key3", "val3");
  776. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  777. }
  778. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  779. string content_type = "multipart/form-data; boundary=something";
  780. string boundary;
  781. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  782. EXPECT_TRUE(ret);
  783. EXPECT_EQ(boundary, "something");
  784. }
  785. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  786. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  787. string boundary;
  788. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  789. EXPECT_TRUE(ret);
  790. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  791. }
  792. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  793. string content_type =
  794. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  795. string boundary;
  796. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  797. EXPECT_TRUE(ret);
  798. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  799. }
  800. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  801. string content_type =
  802. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  803. string boundary;
  804. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  805. EXPECT_TRUE(ret);
  806. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  807. }
  808. TEST(GetHeaderValueTest, DefaultValue) {
  809. Headers headers = {{"Dummy", "Dummy"}};
  810. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  811. EXPECT_STREQ("text/plain", val);
  812. }
  813. TEST(GetHeaderValueTest, DefaultValueInt) {
  814. Headers headers = {{"Dummy", "Dummy"}};
  815. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  816. EXPECT_EQ(100ull, val);
  817. }
  818. TEST(GetHeaderValueTest, RegularValue) {
  819. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  820. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  821. EXPECT_STREQ("text/html", val);
  822. }
  823. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  824. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  825. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  826. EXPECT_STREQ("text/html", val);
  827. }
  828. TEST(GetHeaderValueTest, SetContent) {
  829. Response res;
  830. res.set_content("html", "text/html");
  831. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  832. res.set_content("text", "text/plain");
  833. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  834. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  835. }
  836. TEST(GetHeaderValueTest, RegularValueInt) {
  837. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  838. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  839. EXPECT_EQ(100ull, val);
  840. }
  841. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  842. Headers headers = {{"Content-Length", "x"}};
  843. auto is_invalid_value = false;
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  845. is_invalid_value);
  846. EXPECT_EQ(0ull, val);
  847. EXPECT_TRUE(is_invalid_value);
  848. }
  849. TEST(GetHeaderValueTest, Range) {
  850. {
  851. Headers headers = {make_range_header({{1, -1}})};
  852. auto val = detail::get_header_value(headers, "Range", 0, 0);
  853. EXPECT_STREQ("bytes=1-", val);
  854. }
  855. {
  856. Headers headers = {make_range_header({{-1, 1}})};
  857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  858. EXPECT_STREQ("bytes=-1", val);
  859. }
  860. {
  861. Headers headers = {make_range_header({{1, 10}})};
  862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  863. EXPECT_STREQ("bytes=1-10", val);
  864. }
  865. {
  866. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  868. EXPECT_STREQ("bytes=1-10, 100-", val);
  869. }
  870. {
  871. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  873. EXPECT_STREQ("bytes=1-10, 100-200", val);
  874. }
  875. {
  876. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  877. auto val = detail::get_header_value(headers, "Range", 0, 0);
  878. EXPECT_STREQ("bytes=0-0, -1", val);
  879. }
  880. }
  881. TEST(ParseHeaderValueTest, Range) {
  882. {
  883. Ranges ranges;
  884. auto ret = detail::parse_range_header("bytes=1-", ranges);
  885. EXPECT_TRUE(ret);
  886. EXPECT_EQ(1u, ranges.size());
  887. EXPECT_EQ(1u, ranges[0].first);
  888. EXPECT_EQ(-1, ranges[0].second);
  889. }
  890. {
  891. Ranges ranges;
  892. auto ret = detail::parse_range_header("bytes=-1", ranges);
  893. EXPECT_TRUE(ret);
  894. EXPECT_EQ(1u, ranges.size());
  895. EXPECT_EQ(-1, ranges[0].first);
  896. EXPECT_EQ(1u, ranges[0].second);
  897. }
  898. {
  899. Ranges ranges;
  900. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  901. EXPECT_TRUE(ret);
  902. EXPECT_EQ(1u, ranges.size());
  903. EXPECT_EQ(1u, ranges[0].first);
  904. EXPECT_EQ(10u, ranges[0].second);
  905. }
  906. {
  907. Ranges ranges;
  908. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  909. EXPECT_FALSE(ret);
  910. }
  911. {
  912. Ranges ranges;
  913. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  914. EXPECT_TRUE(ret);
  915. EXPECT_EQ(2u, ranges.size());
  916. EXPECT_EQ(1u, ranges[0].first);
  917. EXPECT_EQ(10u, ranges[0].second);
  918. EXPECT_EQ(100u, ranges[1].first);
  919. EXPECT_EQ(-1, ranges[1].second);
  920. }
  921. {
  922. Ranges ranges;
  923. auto ret =
  924. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  925. EXPECT_TRUE(ret);
  926. EXPECT_EQ(3u, ranges.size());
  927. EXPECT_EQ(1u, ranges[0].first);
  928. EXPECT_EQ(10u, ranges[0].second);
  929. EXPECT_EQ(100u, ranges[1].first);
  930. EXPECT_EQ(200u, ranges[1].second);
  931. EXPECT_EQ(300u, ranges[2].first);
  932. EXPECT_EQ(400u, ranges[2].second);
  933. }
  934. {
  935. Ranges ranges;
  936. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  949. EXPECT_TRUE(ranges.empty());
  950. }
  951. }
  952. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  953. Request req;
  954. req.set_header("Accept-Encoding", "gzip");
  955. Response res;
  956. res.set_header("Content-Type", "text/plain");
  957. auto ret = detail::encoding_type(req, res);
  958. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  959. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  960. #else
  961. EXPECT_TRUE(ret == detail::EncodingType::None);
  962. #endif
  963. }
  964. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  965. Request req;
  966. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  967. Response res;
  968. res.set_header("Content-Type", "text/plain");
  969. auto ret = detail::encoding_type(req, res);
  970. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  971. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  972. #elif CPPHTTPLIB_ZLIB_SUPPORT
  973. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  974. #elif CPPHTTPLIB_ZSTD_SUPPORT
  975. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  976. #else
  977. EXPECT_TRUE(ret == detail::EncodingType::None);
  978. #endif
  979. }
  980. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  981. Request req;
  982. req.set_header("Accept-Encoding",
  983. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  984. Response res;
  985. res.set_header("Content-Type", "text/plain");
  986. auto ret = detail::encoding_type(req, res);
  987. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  988. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  989. #elif CPPHTTPLIB_ZLIB_SUPPORT
  990. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  991. #elif CPPHTTPLIB_ZSTD_SUPPORT
  992. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  993. #else
  994. EXPECT_TRUE(ret == detail::EncodingType::None);
  995. #endif
  996. }
  997. TEST(BufferStreamTest, read) {
  998. detail::BufferStream strm1;
  999. Stream &strm = strm1;
  1000. EXPECT_EQ(5, strm.write("hello"));
  1001. char buf[512];
  1002. EXPECT_EQ(2, strm.read(buf, 2));
  1003. EXPECT_EQ('h', buf[0]);
  1004. EXPECT_EQ('e', buf[1]);
  1005. EXPECT_EQ(2, strm.read(buf, 2));
  1006. EXPECT_EQ('l', buf[0]);
  1007. EXPECT_EQ('l', buf[1]);
  1008. EXPECT_EQ(1, strm.read(buf, 1));
  1009. EXPECT_EQ('o', buf[0]);
  1010. EXPECT_EQ(0, strm.read(buf, 1));
  1011. }
  1012. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1013. auto host = "www.httpwatch.com";
  1014. auto ip = hosted_at(host);
  1015. EXPECT_EQ("23.96.13.243", ip);
  1016. std::vector<std::string> addrs;
  1017. hosted_at(host, addrs);
  1018. EXPECT_EQ(1u, addrs.size());
  1019. }
  1020. #if 0 // It depends on each test environment...
  1021. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1022. auto host = "www.youtube.com";
  1023. std::vector<std::string> addrs;
  1024. hosted_at(host, addrs);
  1025. EXPECT_EQ(20u, addrs.size());
  1026. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1027. EXPECT_TRUE(it != addrs.end());
  1028. }
  1029. #endif
  1030. class ChunkedEncodingTest : public ::testing::Test {
  1031. protected:
  1032. ChunkedEncodingTest()
  1033. : cli_(HOST, PORT)
  1034. #ifdef CPPHTTPLIB_SSL_ENABLED
  1035. ,
  1036. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1037. #endif
  1038. {
  1039. cli_.set_connection_timeout(2);
  1040. #ifdef CPPHTTPLIB_SSL_ENABLED
  1041. cli_.enable_server_certificate_verification(false);
  1042. #endif
  1043. }
  1044. virtual void SetUp() {
  1045. read_file("./image.jpg", image_data_);
  1046. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1047. res.set_content("Hello World!", "text/plain");
  1048. });
  1049. svr_.Get(
  1050. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1051. res.set_chunked_content_provider(
  1052. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1053. size_t remaining = image_data_.size() - offset;
  1054. if (remaining == 0) {
  1055. sink.done();
  1056. } else {
  1057. constexpr size_t CHUNK_SIZE = 1024;
  1058. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1059. sink.write(&image_data_[offset], send_size);
  1060. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1061. }
  1062. return true;
  1063. });
  1064. });
  1065. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1066. svr_.wait_until_ready();
  1067. }
  1068. virtual void TearDown() {
  1069. svr_.stop();
  1070. if (!request_threads_.empty()) {
  1071. std::this_thread::sleep_for(std::chrono::seconds(1));
  1072. for (auto &t : request_threads_) {
  1073. t.join();
  1074. }
  1075. }
  1076. t_.join();
  1077. }
  1078. #ifdef CPPHTTPLIB_SSL_ENABLED
  1079. SSLClient cli_;
  1080. SSLServer svr_;
  1081. #else
  1082. Client cli_;
  1083. Server svr_;
  1084. #endif
  1085. thread t_;
  1086. std::vector<thread> request_threads_;
  1087. std::string image_data_;
  1088. };
  1089. TEST_F(ChunkedEncodingTest, NormalGet) {
  1090. auto res = cli_.Get("/chunked");
  1091. ASSERT_TRUE(res);
  1092. std::string out;
  1093. read_file("./image.jpg", out);
  1094. EXPECT_EQ(StatusCode::OK_200, res->status);
  1095. EXPECT_EQ(out, res->body);
  1096. }
  1097. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1098. std::string body;
  1099. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1100. body.append(data, data_length);
  1101. return true;
  1102. });
  1103. ASSERT_TRUE(res);
  1104. std::string out;
  1105. read_file("./image.jpg", out);
  1106. EXPECT_EQ(StatusCode::OK_200, res->status);
  1107. EXPECT_EQ(out, body);
  1108. }
  1109. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1110. std::string body;
  1111. auto res = cli_.Get(
  1112. "/chunked",
  1113. [&](const Response &response) {
  1114. EXPECT_EQ(StatusCode::OK_200, response.status);
  1115. return true;
  1116. },
  1117. [&](const char *data, size_t data_length) {
  1118. body.append(data, data_length);
  1119. return true;
  1120. });
  1121. ASSERT_TRUE(res);
  1122. std::string out;
  1123. read_file("./image.jpg", out);
  1124. EXPECT_EQ(StatusCode::OK_200, res->status);
  1125. EXPECT_EQ(out, body);
  1126. }
  1127. TEST(RangeTest, FromHTTPBin_Online) {
  1128. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1129. auto host = "httpcan.org";
  1130. auto path = std::string{"/range/32"};
  1131. #else
  1132. auto host = "nghttp2.org";
  1133. auto path = std::string{"/httpbin/range/32"};
  1134. #endif
  1135. #ifdef CPPHTTPLIB_SSL_ENABLED
  1136. auto port = 443;
  1137. SSLClient cli(host, port);
  1138. #else
  1139. auto port = 80;
  1140. Client cli(host, port);
  1141. #endif
  1142. cli.set_connection_timeout(5);
  1143. {
  1144. auto res = cli.Get(path);
  1145. ASSERT_TRUE(res);
  1146. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1147. EXPECT_EQ(StatusCode::OK_200, res->status);
  1148. }
  1149. {
  1150. Headers headers = {make_range_header({{1, -1}})};
  1151. auto res = cli.Get(path, headers);
  1152. ASSERT_TRUE(res);
  1153. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1154. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1155. }
  1156. {
  1157. Headers headers = {make_range_header({{1, 10}})};
  1158. auto res = cli.Get(path, headers);
  1159. ASSERT_TRUE(res);
  1160. EXPECT_EQ("bcdefghijk", res->body);
  1161. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1162. }
  1163. {
  1164. Headers headers = {make_range_header({{0, 31}})};
  1165. auto res = cli.Get(path, headers);
  1166. ASSERT_TRUE(res);
  1167. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1168. EXPECT_EQ(StatusCode::OK_200, res->status);
  1169. }
  1170. {
  1171. Headers headers = {make_range_header({{0, -1}})};
  1172. auto res = cli.Get(path, headers);
  1173. ASSERT_TRUE(res);
  1174. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. }
  1177. {
  1178. Headers headers = {make_range_header({{0, 32}})};
  1179. auto res = cli.Get(path, headers);
  1180. ASSERT_TRUE(res);
  1181. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1182. }
  1183. }
  1184. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1185. auto host = "unresolvableaddress.local";
  1186. auto path = std::string{"/"};
  1187. #ifdef CPPHTTPLIB_SSL_ENABLED
  1188. auto port = 443;
  1189. SSLClient cli(host, port);
  1190. #else
  1191. auto port = 80;
  1192. Client cli(host, port);
  1193. #endif
  1194. cli.set_connection_timeout(1);
  1195. {
  1196. auto res = cli.Get(path);
  1197. ASSERT_FALSE(res);
  1198. }
  1199. std::this_thread::sleep_for(std::chrono::seconds(8));
  1200. }
  1201. TEST(ConnectionErrorTest, InvalidHost) {
  1202. auto host = "-abcde.com";
  1203. #ifdef CPPHTTPLIB_SSL_ENABLED
  1204. auto port = 443;
  1205. SSLClient cli(host, port);
  1206. #else
  1207. auto port = 80;
  1208. Client cli(host, port);
  1209. #endif
  1210. cli.set_connection_timeout(std::chrono::seconds(2));
  1211. auto res = cli.Get("/");
  1212. ASSERT_TRUE(!res);
  1213. EXPECT_EQ(Error::Connection, res.error());
  1214. }
  1215. TEST(ConnectionErrorTest, InvalidHost2) {
  1216. auto host = "httpcan.org/";
  1217. #ifdef CPPHTTPLIB_SSL_ENABLED
  1218. SSLClient cli(host);
  1219. #else
  1220. Client cli(host);
  1221. #endif
  1222. cli.set_connection_timeout(std::chrono::seconds(2));
  1223. auto res = cli.Get("/");
  1224. ASSERT_TRUE(!res);
  1225. EXPECT_EQ(Error::Connection, res.error());
  1226. }
  1227. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1228. auto host = "httpcan.org/";
  1229. #ifdef CPPHTTPLIB_SSL_ENABLED
  1230. SSLClient cli(host);
  1231. #else
  1232. Client cli(host);
  1233. #endif
  1234. cli.set_connection_timeout(std::chrono::seconds(2));
  1235. auto res = cli.Get("/");
  1236. ASSERT_TRUE(!res);
  1237. stringstream s;
  1238. s << "error code: " << res.error();
  1239. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1240. }
  1241. TEST(ConnectionErrorTest, InvalidPort) {
  1242. auto host = "localhost";
  1243. auto port = 44380;
  1244. #ifdef CPPHTTPLIB_SSL_ENABLED
  1245. SSLClient cli(host, port);
  1246. #else
  1247. Client cli(host, port);
  1248. #endif
  1249. cli.set_connection_timeout(std::chrono::seconds(2));
  1250. auto res = cli.Get("/");
  1251. ASSERT_TRUE(!res);
  1252. EXPECT_TRUE(Error::Connection == res.error() ||
  1253. Error::ConnectionTimeout == res.error());
  1254. }
  1255. TEST(ConnectionErrorTest, Timeout_Online) {
  1256. auto host = "google.com";
  1257. #ifdef CPPHTTPLIB_SSL_ENABLED
  1258. auto port = 44380;
  1259. SSLClient cli(host, port);
  1260. #else
  1261. auto port = 8080;
  1262. Client cli(host, port);
  1263. #endif
  1264. cli.set_connection_timeout(std::chrono::seconds(2));
  1265. // only probe one address type so that the error reason
  1266. // correlates to the timed-out IPv4, not the unsupported
  1267. // IPv6 connection attempt
  1268. cli.set_address_family(AF_INET);
  1269. auto res = cli.Get("/");
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1272. }
  1273. TEST(CancelTest, NoCancel_Online) {
  1274. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1275. auto host = "httpcan.org";
  1276. auto path = std::string{"/range/32"};
  1277. #else
  1278. auto host = "nghttp2.org";
  1279. auto path = std::string{"/httpbin/range/32"};
  1280. #endif
  1281. #ifdef CPPHTTPLIB_SSL_ENABLED
  1282. auto port = 443;
  1283. SSLClient cli(host, port);
  1284. #else
  1285. auto port = 80;
  1286. Client cli(host, port);
  1287. #endif
  1288. cli.set_connection_timeout(std::chrono::seconds(5));
  1289. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1290. ASSERT_TRUE(res);
  1291. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1292. EXPECT_EQ(StatusCode::OK_200, res->status);
  1293. }
  1294. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1295. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1296. auto host = "httpcan.org";
  1297. auto path = std::string{"/range/32"};
  1298. #else
  1299. auto host = "nghttp2.org";
  1300. auto path = std::string{"/httpbin/range/32"};
  1301. #endif
  1302. #ifdef CPPHTTPLIB_SSL_ENABLED
  1303. auto port = 443;
  1304. SSLClient cli(host, port);
  1305. #else
  1306. auto port = 80;
  1307. Client cli(host, port);
  1308. #endif
  1309. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1310. cli.set_connection_timeout(std::chrono::seconds(5));
  1311. ASSERT_TRUE(!res);
  1312. EXPECT_EQ(Error::Canceled, res.error());
  1313. }
  1314. TEST(CancelTest, WithCancelLargePayload_Online) {
  1315. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1316. auto host = "httpcan.org";
  1317. auto path = std::string{"/range/65536"};
  1318. #else
  1319. auto host = "nghttp2.org";
  1320. auto path = std::string{"/httpbin/range/65536"};
  1321. #endif
  1322. #ifdef CPPHTTPLIB_SSL_ENABLED
  1323. auto port = 443;
  1324. SSLClient cli(host, port);
  1325. #else
  1326. auto port = 80;
  1327. Client cli(host, port);
  1328. #endif
  1329. cli.set_connection_timeout(std::chrono::seconds(5));
  1330. uint32_t count = 0;
  1331. auto res =
  1332. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1333. ASSERT_TRUE(!res);
  1334. EXPECT_EQ(Error::Canceled, res.error());
  1335. }
  1336. TEST(CancelTest, NoCancelPost) {
  1337. Server svr;
  1338. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content("Hello World!", "text/plain");
  1340. });
  1341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1342. auto se = detail::scope_exit([&] {
  1343. svr.stop();
  1344. thread.join();
  1345. ASSERT_FALSE(svr.is_running());
  1346. });
  1347. svr.wait_until_ready();
  1348. Client cli(HOST, PORT);
  1349. cli.set_connection_timeout(std::chrono::seconds(5));
  1350. auto res =
  1351. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1352. "application/json", [](uint64_t, uint64_t) { return true; });
  1353. ASSERT_TRUE(res);
  1354. EXPECT_EQ("Hello World!", res->body);
  1355. EXPECT_EQ(StatusCode::OK_200, res->status);
  1356. }
  1357. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1358. Server svr;
  1359. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1360. res.set_content("Hello World!", "text/plain");
  1361. });
  1362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1363. auto se = detail::scope_exit([&] {
  1364. svr.stop();
  1365. thread.join();
  1366. ASSERT_FALSE(svr.is_running());
  1367. });
  1368. svr.wait_until_ready();
  1369. Client cli(HOST, PORT);
  1370. cli.set_connection_timeout(std::chrono::seconds(5));
  1371. auto res =
  1372. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1373. "application/json", [](uint64_t, uint64_t) { return false; });
  1374. ASSERT_TRUE(!res);
  1375. EXPECT_EQ(Error::Canceled, res.error());
  1376. }
  1377. TEST(CancelTest, WithCancelLargePayloadPost) {
  1378. Server svr;
  1379. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1380. res.set_content(LARGE_DATA, "text/plain");
  1381. });
  1382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. thread.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, PORT);
  1390. cli.set_connection_timeout(std::chrono::seconds(5));
  1391. auto res =
  1392. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1393. "application/json", [](uint64_t, uint64_t) { return false; });
  1394. ASSERT_TRUE(!res);
  1395. EXPECT_EQ(Error::Canceled, res.error());
  1396. }
  1397. TEST(CancelTest, NoCancelPut) {
  1398. Server svr;
  1399. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1400. res.set_content("Hello World!", "text/plain");
  1401. });
  1402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1403. auto se = detail::scope_exit([&] {
  1404. svr.stop();
  1405. thread.join();
  1406. ASSERT_FALSE(svr.is_running());
  1407. });
  1408. svr.wait_until_ready();
  1409. Client cli(HOST, PORT);
  1410. cli.set_connection_timeout(std::chrono::seconds(5));
  1411. auto res =
  1412. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1413. "application/json", [](uint64_t, uint64_t) { return true; });
  1414. ASSERT_TRUE(res);
  1415. EXPECT_EQ("Hello World!", res->body);
  1416. EXPECT_EQ(StatusCode::OK_200, res->status);
  1417. }
  1418. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1419. Server svr;
  1420. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1421. res.set_content("Hello World!", "text/plain");
  1422. });
  1423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1424. auto se = detail::scope_exit([&] {
  1425. svr.stop();
  1426. thread.join();
  1427. ASSERT_FALSE(svr.is_running());
  1428. });
  1429. svr.wait_until_ready();
  1430. Client cli(HOST, PORT);
  1431. cli.set_connection_timeout(std::chrono::seconds(5));
  1432. auto res =
  1433. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1434. "application/json", [](uint64_t, uint64_t) { return false; });
  1435. ASSERT_TRUE(!res);
  1436. EXPECT_EQ(Error::Canceled, res.error());
  1437. }
  1438. TEST(CancelTest, WithCancelLargePayloadPut) {
  1439. Server svr;
  1440. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1441. res.set_content(LARGE_DATA, "text/plain");
  1442. });
  1443. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. thread.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. Client cli(HOST, PORT);
  1451. cli.set_connection_timeout(std::chrono::seconds(5));
  1452. auto res =
  1453. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1454. "application/json", [](uint64_t, uint64_t) { return false; });
  1455. ASSERT_TRUE(!res);
  1456. EXPECT_EQ(Error::Canceled, res.error());
  1457. }
  1458. TEST(CancelTest, NoCancelPatch) {
  1459. Server svr;
  1460. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content("Hello World!", "text/plain");
  1462. });
  1463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1464. auto se = detail::scope_exit([&] {
  1465. svr.stop();
  1466. thread.join();
  1467. ASSERT_FALSE(svr.is_running());
  1468. });
  1469. svr.wait_until_ready();
  1470. Client cli(HOST, PORT);
  1471. cli.set_connection_timeout(std::chrono::seconds(5));
  1472. auto res =
  1473. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1474. "application/json", [](uint64_t, uint64_t) { return true; });
  1475. ASSERT_TRUE(res);
  1476. EXPECT_EQ("Hello World!", res->body);
  1477. EXPECT_EQ(StatusCode::OK_200, res->status);
  1478. }
  1479. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1480. Server svr;
  1481. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1482. res.set_content("Hello World!", "text/plain");
  1483. });
  1484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1485. auto se = detail::scope_exit([&] {
  1486. svr.stop();
  1487. thread.join();
  1488. ASSERT_FALSE(svr.is_running());
  1489. });
  1490. svr.wait_until_ready();
  1491. Client cli(HOST, PORT);
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. auto res =
  1494. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1495. "application/json", [](uint64_t, uint64_t) { return false; });
  1496. ASSERT_TRUE(!res);
  1497. EXPECT_EQ(Error::Canceled, res.error());
  1498. }
  1499. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1500. Server svr;
  1501. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content(LARGE_DATA, "text/plain");
  1503. });
  1504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1505. auto se = detail::scope_exit([&] {
  1506. svr.stop();
  1507. thread.join();
  1508. ASSERT_FALSE(svr.is_running());
  1509. });
  1510. svr.wait_until_ready();
  1511. Client cli(HOST, PORT);
  1512. cli.set_connection_timeout(std::chrono::seconds(5));
  1513. auto res =
  1514. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1515. "application/json", [](uint64_t, uint64_t) { return false; });
  1516. ASSERT_TRUE(!res);
  1517. EXPECT_EQ(Error::Canceled, res.error());
  1518. }
  1519. TEST(CancelTest, NoCancelDelete) {
  1520. Server svr;
  1521. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1522. res.set_content("Hello World!", "text/plain");
  1523. });
  1524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1525. auto se = detail::scope_exit([&] {
  1526. svr.stop();
  1527. thread.join();
  1528. ASSERT_FALSE(svr.is_running());
  1529. });
  1530. svr.wait_until_ready();
  1531. Client cli(HOST, PORT);
  1532. cli.set_connection_timeout(std::chrono::seconds(5));
  1533. auto res =
  1534. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1535. "application/json", [](uint64_t, uint64_t) { return true; });
  1536. ASSERT_TRUE(res);
  1537. EXPECT_EQ("Hello World!", res->body);
  1538. EXPECT_EQ(StatusCode::OK_200, res->status);
  1539. }
  1540. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1541. Server svr;
  1542. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1543. res.set_content("Hello World!", "text/plain");
  1544. });
  1545. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1546. auto se = detail::scope_exit([&] {
  1547. svr.stop();
  1548. thread.join();
  1549. ASSERT_FALSE(svr.is_running());
  1550. });
  1551. svr.wait_until_ready();
  1552. Client cli(HOST, PORT);
  1553. cli.set_connection_timeout(std::chrono::seconds(5));
  1554. auto res =
  1555. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1556. "application/json", [](uint64_t, uint64_t) { return false; });
  1557. ASSERT_TRUE(!res);
  1558. EXPECT_EQ(Error::Canceled, res.error());
  1559. }
  1560. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1561. Server svr;
  1562. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1563. res.set_content(LARGE_DATA, "text/plain");
  1564. });
  1565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1566. auto se = detail::scope_exit([&] {
  1567. svr.stop();
  1568. thread.join();
  1569. ASSERT_FALSE(svr.is_running());
  1570. });
  1571. svr.wait_until_ready();
  1572. Client cli(HOST, PORT);
  1573. cli.set_connection_timeout(std::chrono::seconds(5));
  1574. auto res =
  1575. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1576. "application/json", [](uint64_t, uint64_t) { return false; });
  1577. ASSERT_TRUE(!res);
  1578. EXPECT_EQ(Error::Canceled, res.error());
  1579. }
  1580. static std::string remove_whitespace(const std::string &input) {
  1581. std::string output;
  1582. output.reserve(input.size());
  1583. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1584. [](unsigned char c) { return !std::isspace(c); });
  1585. return output;
  1586. }
  1587. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1588. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1589. auto host = "httpcan.org";
  1590. auto path = std::string{"/basic-auth/hello/world"};
  1591. #else
  1592. auto host = "nghttp2.org";
  1593. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1594. #endif
  1595. #ifdef CPPHTTPLIB_SSL_ENABLED
  1596. auto port = 443;
  1597. SSLClient cli(host, port);
  1598. #else
  1599. auto port = 80;
  1600. Client cli(host, port);
  1601. #endif
  1602. {
  1603. auto res = cli.Get(path);
  1604. ASSERT_TRUE(res);
  1605. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1606. }
  1607. {
  1608. auto res =
  1609. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1610. ASSERT_TRUE(res);
  1611. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1612. remove_whitespace(res->body));
  1613. EXPECT_EQ(StatusCode::OK_200, res->status);
  1614. }
  1615. {
  1616. cli.set_basic_auth("hello", "world");
  1617. auto res = cli.Get(path);
  1618. ASSERT_TRUE(res);
  1619. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1620. remove_whitespace(res->body));
  1621. EXPECT_EQ(StatusCode::OK_200, res->status);
  1622. }
  1623. {
  1624. cli.set_basic_auth("hello", "bad");
  1625. auto res = cli.Get(path);
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1628. }
  1629. {
  1630. cli.set_basic_auth("bad", "world");
  1631. auto res = cli.Get(path);
  1632. ASSERT_TRUE(res);
  1633. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1634. }
  1635. }
  1636. #ifdef CPPHTTPLIB_SSL_ENABLED
  1637. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1638. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1639. auto host = "httpcan.org";
  1640. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1641. auto paths = std::vector<std::string>{
  1642. "/digest-auth/auth/hello/world/MD5",
  1643. "/digest-auth/auth/hello/world/SHA-256",
  1644. "/digest-auth/auth/hello/world/SHA-512",
  1645. };
  1646. #else
  1647. auto host = "nghttp2.org";
  1648. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1649. auto paths = std::vector<std::string>{
  1650. "/httpbin/digest-auth/auth/hello/world/MD5",
  1651. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1652. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1653. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1654. };
  1655. #endif
  1656. auto port = 443;
  1657. SSLClient cli(host, port);
  1658. {
  1659. auto res = cli.Get(unauth_path);
  1660. ASSERT_TRUE(res);
  1661. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1662. }
  1663. {
  1664. cli.set_digest_auth("hello", "world");
  1665. for (const auto &path : paths) {
  1666. auto res = cli.Get(path.c_str());
  1667. ASSERT_TRUE(res);
  1668. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1669. std::string algo(path.substr(path.rfind('/') + 1));
  1670. EXPECT_EQ(
  1671. remove_whitespace("{\"algorithm\":\"" + algo +
  1672. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1673. remove_whitespace(res->body));
  1674. #else
  1675. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1676. remove_whitespace(res->body));
  1677. #endif
  1678. EXPECT_EQ(StatusCode::OK_200, res->status);
  1679. }
  1680. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1681. cli.set_digest_auth("hello", "bad");
  1682. for (const auto &path : paths) {
  1683. auto res = cli.Get(path.c_str());
  1684. ASSERT_TRUE(res);
  1685. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1686. }
  1687. #endif
  1688. }
  1689. }
  1690. #endif
  1691. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1692. auto host = "google.com";
  1693. auto another_host = "example.com";
  1694. auto wrong_ip = "0.0.0.0";
  1695. #ifdef CPPHTTPLIB_SSL_ENABLED
  1696. SSLClient cli(host);
  1697. #else
  1698. Client cli(host);
  1699. #endif
  1700. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1701. auto res = cli.Get("/");
  1702. ASSERT_TRUE(res);
  1703. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1704. }
  1705. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1706. auto host = "google.com";
  1707. auto wrong_ip = "0.0.0.0";
  1708. #ifdef CPPHTTPLIB_SSL_ENABLED
  1709. SSLClient cli(host);
  1710. #else
  1711. Client cli(host);
  1712. #endif
  1713. cli.set_hostname_addr_map({{host, wrong_ip}});
  1714. auto res = cli.Get("/");
  1715. ASSERT_TRUE(!res);
  1716. EXPECT_EQ(Error::Connection, res.error());
  1717. }
  1718. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1719. auto host = "nghttp2.org";
  1720. #ifdef CPPHTTPLIB_SSL_ENABLED
  1721. SSLClient cli(host);
  1722. #else
  1723. Client cli(host);
  1724. #endif
  1725. cli.set_follow_location(true);
  1726. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1727. ASSERT_TRUE(res);
  1728. EXPECT_EQ(StatusCode::OK_200, res->status);
  1729. }
  1730. TEST(RedirectTest, Redirect_Online) {
  1731. auto host = "nghttp2.org";
  1732. #ifdef CPPHTTPLIB_SSL_ENABLED
  1733. SSLClient cli(host);
  1734. #else
  1735. Client cli(host);
  1736. #endif
  1737. cli.set_follow_location(true);
  1738. auto res = cli.Get("/httpbin/redirect/3");
  1739. ASSERT_TRUE(res);
  1740. EXPECT_EQ(StatusCode::OK_200, res->status);
  1741. }
  1742. TEST(RelativeRedirectTest, Redirect_Online) {
  1743. auto host = "nghttp2.org";
  1744. #ifdef CPPHTTPLIB_SSL_ENABLED
  1745. SSLClient cli(host);
  1746. #else
  1747. Client cli(host);
  1748. #endif
  1749. cli.set_follow_location(true);
  1750. auto res = cli.Get("/httpbin/relative-redirect/3");
  1751. ASSERT_TRUE(res);
  1752. EXPECT_EQ(StatusCode::OK_200, res->status);
  1753. }
  1754. TEST(TooManyRedirectTest, Redirect_Online) {
  1755. auto host = "nghttp2.org";
  1756. #ifdef CPPHTTPLIB_SSL_ENABLED
  1757. SSLClient cli(host);
  1758. #else
  1759. Client cli(host);
  1760. #endif
  1761. cli.set_follow_location(true);
  1762. auto res = cli.Get("/httpbin/redirect/21");
  1763. ASSERT_TRUE(!res);
  1764. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1765. }
  1766. #ifdef CPPHTTPLIB_SSL_ENABLED
  1767. TEST(YahooRedirectTest, Redirect_Online) {
  1768. Client cli("yahoo.com");
  1769. auto res = cli.Get("/");
  1770. ASSERT_TRUE(res);
  1771. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1772. cli.set_follow_location(true);
  1773. res = cli.Get("/");
  1774. ASSERT_TRUE(res);
  1775. EXPECT_EQ(StatusCode::OK_200, res->status);
  1776. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1777. }
  1778. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1779. #define REDIR_HOST "httpbingo.org"
  1780. #define REDIR_PATH "/redirect-to"
  1781. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1782. SSLClient cli(REDIR_HOST);
  1783. cli.set_follow_location(true);
  1784. auto res =
  1785. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1786. ASSERT_TRUE(res);
  1787. EXPECT_EQ(StatusCode::OK_200, res->status);
  1788. }
  1789. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1790. SSLClient cli(REDIR_HOST);
  1791. cli.set_follow_location(true);
  1792. Params params;
  1793. params.emplace("url", "http://example.com");
  1794. params.emplace("status_code", "302");
  1795. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1796. ASSERT_TRUE(res);
  1797. EXPECT_EQ(StatusCode::OK_200, res->status);
  1798. }
  1799. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1800. SSLClient cli(REDIR_HOST);
  1801. cli.set_follow_location(true);
  1802. Params params;
  1803. params.emplace("url", "http://example.com");
  1804. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1805. ASSERT_TRUE(res);
  1806. EXPECT_EQ(StatusCode::OK_200, res->status);
  1807. }
  1808. TEST(UrlWithSpace, Redirect_Online) {
  1809. SSLClient cli("edge.forgecdn.net");
  1810. cli.set_follow_location(true);
  1811. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1812. ASSERT_TRUE(res);
  1813. EXPECT_EQ(StatusCode::OK_200, res->status);
  1814. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1815. }
  1816. #endif
  1817. #if !defined(_WIN32) && !defined(_WIN64)
  1818. TEST(ReceiveSignals, Signal) {
  1819. auto setupSignalHandlers = []() {
  1820. struct sigaction act;
  1821. sigemptyset(&act.sa_mask);
  1822. act.sa_flags = SA_SIGINFO;
  1823. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1824. switch (sig) {
  1825. case SIGINT:
  1826. default: break;
  1827. }
  1828. };
  1829. ::sigaction(SIGINT, &act, nullptr);
  1830. };
  1831. Server svr;
  1832. int port = 0;
  1833. auto thread = std::thread([&]() {
  1834. setupSignalHandlers();
  1835. port = svr.bind_to_any_port(HOST);
  1836. svr.listen_after_bind();
  1837. });
  1838. auto se = detail::scope_exit([&] {
  1839. svr.stop();
  1840. thread.join();
  1841. ASSERT_FALSE(svr.is_running());
  1842. });
  1843. svr.wait_until_ready();
  1844. ASSERT_TRUE(svr.is_running());
  1845. pthread_kill(thread.native_handle(), SIGINT);
  1846. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1847. ASSERT_TRUE(svr.is_running());
  1848. }
  1849. #endif
  1850. TEST(RedirectToDifferentPort, Redirect) {
  1851. Server svr1;
  1852. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1853. res.set_content("Hello World!", "text/plain");
  1854. });
  1855. int svr1_port = 0;
  1856. auto thread1 = std::thread([&]() {
  1857. svr1_port = svr1.bind_to_any_port(HOST);
  1858. svr1.listen_after_bind();
  1859. });
  1860. Server svr2;
  1861. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1862. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1863. });
  1864. int svr2_port = 0;
  1865. auto thread2 = std::thread([&]() {
  1866. svr2_port = svr2.bind_to_any_port(HOST);
  1867. svr2.listen_after_bind();
  1868. });
  1869. auto se = detail::scope_exit([&] {
  1870. svr2.stop();
  1871. thread2.join();
  1872. svr1.stop();
  1873. thread1.join();
  1874. ASSERT_FALSE(svr2.is_running());
  1875. ASSERT_FALSE(svr1.is_running());
  1876. });
  1877. svr1.wait_until_ready();
  1878. svr2.wait_until_ready();
  1879. Client cli("localhost", svr2_port);
  1880. cli.set_follow_location(true);
  1881. auto res = cli.Get("/2");
  1882. ASSERT_TRUE(res);
  1883. EXPECT_EQ(StatusCode::OK_200, res->status);
  1884. EXPECT_EQ("Hello World!", res->body);
  1885. }
  1886. TEST(RedirectFromPageWithContent, Redirect) {
  1887. Server svr;
  1888. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1889. res.set_content("___", "text/plain");
  1890. res.set_redirect("/2");
  1891. });
  1892. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1893. res.set_content("Hello World!", "text/plain");
  1894. });
  1895. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1896. auto se = detail::scope_exit([&] {
  1897. svr.stop();
  1898. th.join();
  1899. ASSERT_FALSE(svr.is_running());
  1900. });
  1901. svr.wait_until_ready();
  1902. {
  1903. Client cli("localhost", PORT);
  1904. cli.set_follow_location(true);
  1905. std::string body;
  1906. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1907. body.append(data, data_length);
  1908. return true;
  1909. });
  1910. ASSERT_TRUE(res);
  1911. EXPECT_EQ(StatusCode::OK_200, res->status);
  1912. EXPECT_EQ("Hello World!", body);
  1913. }
  1914. {
  1915. Client cli("localhost", PORT);
  1916. std::string body;
  1917. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1918. body.append(data, data_length);
  1919. return true;
  1920. });
  1921. ASSERT_TRUE(res);
  1922. EXPECT_EQ(StatusCode::Found_302, res->status);
  1923. EXPECT_EQ("___", body);
  1924. }
  1925. }
  1926. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1927. Server svr;
  1928. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1929. res.set_content("___", "text/plain");
  1930. // res.set_redirect("/2");
  1931. res.set_redirect("http://[::1]:1234/2");
  1932. });
  1933. svr.Get("/2", [&](const Request &req, Response &res) {
  1934. auto host_header = req.headers.find("Host");
  1935. ASSERT_TRUE(host_header != req.headers.end());
  1936. EXPECT_EQ("[::1]:1234", host_header->second);
  1937. res.set_content("Hello World!", "text/plain");
  1938. });
  1939. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1940. auto se = detail::scope_exit([&] {
  1941. svr.stop();
  1942. th.join();
  1943. ASSERT_FALSE(svr.is_running());
  1944. });
  1945. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1946. // actually starts anything, so the condition !svr.is_running() will
  1947. // always remain true, and the loop never stops.
  1948. // This basically counts how many milliseconds have passed since the
  1949. // call to svr.listen(), and if after 5 seconds nothing started yet
  1950. // aborts the test.
  1951. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1952. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1953. ASSERT_LT(milliseconds, 5000U);
  1954. }
  1955. {
  1956. Client cli("http://[::1]:1234");
  1957. cli.set_follow_location(true);
  1958. std::string body;
  1959. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1960. body.append(data, data_length);
  1961. return true;
  1962. });
  1963. ASSERT_TRUE(res);
  1964. EXPECT_EQ(StatusCode::OK_200, res->status);
  1965. EXPECT_EQ("Hello World!", body);
  1966. }
  1967. {
  1968. Client cli("http://[::1]:1234");
  1969. std::string body;
  1970. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1971. body.append(data, data_length);
  1972. return true;
  1973. });
  1974. ASSERT_TRUE(res);
  1975. EXPECT_EQ(StatusCode::Found_302, res->status);
  1976. EXPECT_EQ("___", body);
  1977. }
  1978. }
  1979. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1980. Server svr;
  1981. svr.Get("/foo", [](const Request &req, Response &res) {
  1982. auto a = req.params.find("a");
  1983. if (a != req.params.end()) {
  1984. res.set_content((*a).second, "text/plain");
  1985. res.status = StatusCode::OK_200;
  1986. } else {
  1987. res.status = StatusCode::BadRequest_400;
  1988. }
  1989. });
  1990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1991. auto se = detail::scope_exit([&] {
  1992. svr.stop();
  1993. thread.join();
  1994. ASSERT_FALSE(svr.is_running());
  1995. });
  1996. svr.wait_until_ready();
  1997. {
  1998. Client cli(HOST, PORT);
  1999. cli.set_path_encode(false);
  2000. auto res = cli.Get("/foo?a=explicitly+encoded");
  2001. ASSERT_TRUE(res);
  2002. EXPECT_EQ(StatusCode::OK_200, res->status);
  2003. // This expects it back with a space, as the `+` won't have been
  2004. // url-encoded, and server-side the params get decoded turning `+`
  2005. // into spaces.
  2006. EXPECT_EQ("explicitly encoded", res->body);
  2007. }
  2008. }
  2009. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2010. Server svr;
  2011. svr.Get("/", [](const Request &req, Response &) {
  2012. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2013. });
  2014. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2015. auto se = detail::scope_exit([&] {
  2016. svr.stop();
  2017. thread.join();
  2018. ASSERT_FALSE(svr.is_running());
  2019. });
  2020. svr.wait_until_ready();
  2021. {
  2022. Client cli(HOST, PORT);
  2023. cli.set_path_encode(false);
  2024. auto res = cli.Get("/?something=%0A");
  2025. ASSERT_TRUE(res);
  2026. EXPECT_EQ(StatusCode::OK_200, res->status);
  2027. }
  2028. }
  2029. TEST(BindServerTest, DISABLED_BindDualStack) {
  2030. Server svr;
  2031. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2032. res.set_content("Hello World!", "text/plain");
  2033. });
  2034. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2035. auto se = detail::scope_exit([&] {
  2036. svr.stop();
  2037. thread.join();
  2038. ASSERT_FALSE(svr.is_running());
  2039. });
  2040. svr.wait_until_ready();
  2041. {
  2042. Client cli("127.0.0.1", PORT);
  2043. auto res = cli.Get("/1");
  2044. ASSERT_TRUE(res);
  2045. EXPECT_EQ(StatusCode::OK_200, res->status);
  2046. EXPECT_EQ("Hello World!", res->body);
  2047. }
  2048. {
  2049. Client cli("::1", PORT);
  2050. auto res = cli.Get("/1");
  2051. ASSERT_TRUE(res);
  2052. EXPECT_EQ(StatusCode::OK_200, res->status);
  2053. EXPECT_EQ("Hello World!", res->body);
  2054. }
  2055. }
  2056. TEST(BindServerTest, BindAndListenSeparately) {
  2057. Server svr;
  2058. int port = svr.bind_to_any_port("0.0.0.0");
  2059. ASSERT_TRUE(svr.is_valid());
  2060. ASSERT_TRUE(port > 0);
  2061. svr.stop();
  2062. }
  2063. #ifdef CPPHTTPLIB_SSL_ENABLED
  2064. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2066. CLIENT_CA_CERT_DIR);
  2067. int port = svr.bind_to_any_port("0.0.0.0");
  2068. ASSERT_TRUE(svr.is_valid());
  2069. ASSERT_TRUE(port > 0);
  2070. svr.stop();
  2071. }
  2072. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2073. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2074. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2075. int port = svr.bind_to_any_port("0.0.0.0");
  2076. ASSERT_TRUE(svr.is_valid());
  2077. ASSERT_TRUE(port > 0);
  2078. svr.stop();
  2079. }
  2080. TEST(BindServerTest, UpdateCertsPem) {
  2081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2082. int port = svr.bind_to_any_port("0.0.0.0");
  2083. ASSERT_TRUE(svr.is_valid());
  2084. ASSERT_TRUE(port > 0);
  2085. // Read PEM files
  2086. std::string cert_pem, key_pem, ca_pem;
  2087. read_file(SERVER_CERT_FILE, cert_pem);
  2088. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2089. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2090. // Update server certificates using PEM API
  2091. ASSERT_TRUE(
  2092. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2093. ASSERT_TRUE(svr.is_valid());
  2094. svr.stop();
  2095. }
  2096. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2097. // Start server with client CA (enables client auth)
  2098. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2099. ASSERT_TRUE(svr.is_valid());
  2100. bool handler_called = false;
  2101. svr.Get("/test", [&](const Request &req, Response &res) {
  2102. handler_called = true;
  2103. // Verify client certificate is present
  2104. auto cert = req.peer_cert();
  2105. EXPECT_TRUE(static_cast<bool>(cert));
  2106. res.set_content("ok", "text/plain");
  2107. });
  2108. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2109. auto se = detail::scope_exit([&] {
  2110. svr.stop();
  2111. t.join();
  2112. ASSERT_FALSE(svr.is_running());
  2113. });
  2114. svr.wait_until_ready();
  2115. // Read PEM files
  2116. std::string cert_pem, key_pem, ca_pem;
  2117. read_file(SERVER_CERT_FILE, cert_pem);
  2118. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2119. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2120. // Update server certificates and client CA using PEM API while server running
  2121. ASSERT_TRUE(
  2122. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2123. // Connect with client certificate
  2124. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2125. cli.enable_server_certificate_verification(false);
  2126. cli.set_connection_timeout(30);
  2127. auto res = cli.Get("/test");
  2128. ASSERT_TRUE(res);
  2129. ASSERT_EQ(StatusCode::OK_200, res->status);
  2130. ASSERT_TRUE(handler_called);
  2131. EXPECT_EQ("ok", res->body);
  2132. }
  2133. #endif
  2134. TEST(ErrorHandlerTest, ContentLength) {
  2135. Server svr;
  2136. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2137. res.status = StatusCode::OK_200;
  2138. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2139. "text/html"); // <= Content-Length still 13
  2140. });
  2141. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2142. res.set_content("Hello World!\n", "text/plain");
  2143. res.status = 524;
  2144. });
  2145. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2146. auto se = detail::scope_exit([&] {
  2147. svr.stop();
  2148. thread.join();
  2149. ASSERT_FALSE(svr.is_running());
  2150. });
  2151. svr.wait_until_ready();
  2152. {
  2153. Client cli(HOST, PORT);
  2154. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2155. ASSERT_TRUE(res);
  2156. EXPECT_EQ(StatusCode::OK_200, res->status);
  2157. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2158. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2159. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2160. }
  2161. }
  2162. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2163. TEST(ExceptionTest, WithoutExceptionHandler) {
  2164. Server svr;
  2165. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2166. throw std::runtime_error("exception...");
  2167. });
  2168. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2169. throw std::runtime_error("exception\r\n...");
  2170. });
  2171. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2172. auto se = detail::scope_exit([&] {
  2173. svr.stop();
  2174. listen_thread.join();
  2175. ASSERT_FALSE(svr.is_running());
  2176. });
  2177. svr.wait_until_ready();
  2178. Client cli("localhost", PORT);
  2179. {
  2180. auto res = cli.Get("/exception");
  2181. ASSERT_TRUE(res);
  2182. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2183. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2184. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2185. }
  2186. {
  2187. auto res = cli.Get("/unknown");
  2188. ASSERT_TRUE(res);
  2189. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2190. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2191. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2192. }
  2193. }
  2194. TEST(ExceptionTest, WithExceptionHandler) {
  2195. Server svr;
  2196. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2197. std::exception_ptr ep) {
  2198. EXPECT_FALSE(ep == nullptr);
  2199. try {
  2200. std::rethrow_exception(ep);
  2201. } catch (std::exception &e) {
  2202. EXPECT_EQ("abc", std::string(e.what()));
  2203. } catch (...) {}
  2204. res.status = StatusCode::InternalServerError_500;
  2205. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2206. "text/html"); // <= Content-Length still 13 at this point
  2207. });
  2208. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2209. res.set_content("Hello World!\n", "text/plain");
  2210. throw std::runtime_error("abc");
  2211. });
  2212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2213. auto se = detail::scope_exit([&] {
  2214. svr.stop();
  2215. thread.join();
  2216. ASSERT_FALSE(svr.is_running());
  2217. });
  2218. svr.wait_until_ready();
  2219. for (size_t i = 0; i < 10; i++) {
  2220. Client cli(HOST, PORT);
  2221. for (size_t j = 0; j < 100; j++) {
  2222. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2223. ASSERT_TRUE(res);
  2224. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2225. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2226. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2227. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2228. }
  2229. cli.set_keep_alive(true);
  2230. for (size_t j = 0; j < 100; j++) {
  2231. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2232. ASSERT_TRUE(res);
  2233. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2234. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2235. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2236. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2237. }
  2238. }
  2239. }
  2240. TEST(ExceptionTest, AndErrorHandler) {
  2241. Server svr;
  2242. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2243. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2244. });
  2245. svr.set_exception_handler(
  2246. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2247. EXPECT_FALSE(ep == nullptr);
  2248. try {
  2249. std::rethrow_exception(ep);
  2250. } catch (std::exception &e) {
  2251. res.set_content(e.what(), "text/html");
  2252. } catch (...) {}
  2253. res.status = StatusCode::InternalServerError_500;
  2254. });
  2255. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2256. throw std::runtime_error("EXCEPTION");
  2257. });
  2258. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2259. res.set_content("ERROR", "text/html");
  2260. res.status = StatusCode::InternalServerError_500;
  2261. });
  2262. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2263. auto se = detail::scope_exit([&] {
  2264. svr.stop();
  2265. thread.join();
  2266. ASSERT_FALSE(svr.is_running());
  2267. });
  2268. svr.wait_until_ready();
  2269. Client cli(HOST, PORT);
  2270. {
  2271. auto res = cli.Get("/exception");
  2272. ASSERT_TRUE(res);
  2273. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2274. EXPECT_EQ("EXCEPTION", res->body);
  2275. }
  2276. {
  2277. auto res = cli.Get("/error");
  2278. ASSERT_TRUE(res);
  2279. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2280. EXPECT_EQ("ERROR", res->body);
  2281. }
  2282. {
  2283. auto res = cli.Get("/invalid");
  2284. ASSERT_TRUE(res);
  2285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2286. EXPECT_EQ("NOT_FOUND", res->body);
  2287. }
  2288. }
  2289. #endif
  2290. TEST(NoContentTest, ContentLength) {
  2291. Server svr;
  2292. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2293. res.status = StatusCode::NoContent_204;
  2294. });
  2295. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2296. auto se = detail::scope_exit([&] {
  2297. svr.stop();
  2298. thread.join();
  2299. ASSERT_FALSE(svr.is_running());
  2300. });
  2301. svr.wait_until_ready();
  2302. {
  2303. Client cli(HOST, PORT);
  2304. auto res = cli.Get("/hi");
  2305. ASSERT_TRUE(res);
  2306. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2307. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2308. }
  2309. }
  2310. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2311. #ifdef CPPHTTPLIB_SSL_ENABLED
  2312. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2313. ASSERT_TRUE(svr.is_valid());
  2314. #else
  2315. Server svr;
  2316. #endif
  2317. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2318. if (req.path == "/routing_handler") {
  2319. res.set_header("PRE_ROUTING", "on");
  2320. res.set_content("Routing Handler", "text/plain");
  2321. return httplib::Server::HandlerResponse::Handled;
  2322. }
  2323. return httplib::Server::HandlerResponse::Unhandled;
  2324. });
  2325. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2326. res.set_content("Error", "text/html");
  2327. });
  2328. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2329. if (req.path == "/routing_handler") {
  2330. res.set_header("POST_ROUTING", "on");
  2331. }
  2332. });
  2333. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2334. res.set_content("Hello World!\n", "text/plain");
  2335. });
  2336. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2337. auto se = detail::scope_exit([&] {
  2338. svr.stop();
  2339. thread.join();
  2340. ASSERT_FALSE(svr.is_running());
  2341. });
  2342. svr.wait_until_ready();
  2343. {
  2344. #ifdef CPPHTTPLIB_SSL_ENABLED
  2345. SSLClient cli(HOST, PORT);
  2346. cli.enable_server_certificate_verification(false);
  2347. #else
  2348. Client cli(HOST, PORT);
  2349. #endif
  2350. auto res = cli.Get("/routing_handler");
  2351. ASSERT_TRUE(res);
  2352. EXPECT_EQ(StatusCode::OK_200, res->status);
  2353. EXPECT_EQ("Routing Handler", res->body);
  2354. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2355. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2356. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2357. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2358. }
  2359. {
  2360. #ifdef CPPHTTPLIB_SSL_ENABLED
  2361. SSLClient cli(HOST, PORT);
  2362. cli.enable_server_certificate_verification(false);
  2363. #else
  2364. Client cli(HOST, PORT);
  2365. #endif
  2366. auto res = cli.Get("/hi");
  2367. ASSERT_TRUE(res);
  2368. EXPECT_EQ(StatusCode::OK_200, res->status);
  2369. EXPECT_EQ("Hello World!\n", res->body);
  2370. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2371. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2372. }
  2373. {
  2374. #ifdef CPPHTTPLIB_SSL_ENABLED
  2375. SSLClient cli(HOST, PORT);
  2376. cli.enable_server_certificate_verification(false);
  2377. #else
  2378. Client cli(HOST, PORT);
  2379. #endif
  2380. auto res = cli.Get("/aaa");
  2381. ASSERT_TRUE(res);
  2382. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2383. EXPECT_EQ("Error", res->body);
  2384. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2385. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2386. }
  2387. }
  2388. TEST(RequestHandlerTest, PreRequestHandler) {
  2389. auto route_path = "/user/:user";
  2390. Server svr;
  2391. svr.Get("/hi", [](const Request &, Response &res) {
  2392. res.set_content("hi", "text/plain");
  2393. });
  2394. svr.Get(route_path, [](const Request &req, Response &res) {
  2395. res.set_content(req.path_params.at("user"), "text/plain");
  2396. });
  2397. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2398. if (req.matched_route == route_path) {
  2399. auto user = req.path_params.at("user");
  2400. if (user != "john") {
  2401. res.status = StatusCode::Forbidden_403;
  2402. res.set_content("error", "text/html");
  2403. return Server::HandlerResponse::Handled;
  2404. }
  2405. }
  2406. return Server::HandlerResponse::Unhandled;
  2407. });
  2408. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2409. auto se = detail::scope_exit([&] {
  2410. svr.stop();
  2411. thread.join();
  2412. ASSERT_FALSE(svr.is_running());
  2413. });
  2414. svr.wait_until_ready();
  2415. Client cli(HOST, PORT);
  2416. {
  2417. auto res = cli.Get("/hi");
  2418. ASSERT_TRUE(res);
  2419. EXPECT_EQ(StatusCode::OK_200, res->status);
  2420. EXPECT_EQ("hi", res->body);
  2421. }
  2422. {
  2423. auto res = cli.Get("/user/john");
  2424. ASSERT_TRUE(res);
  2425. EXPECT_EQ(StatusCode::OK_200, res->status);
  2426. EXPECT_EQ("john", res->body);
  2427. }
  2428. {
  2429. auto res = cli.Get("/user/invalid-user");
  2430. ASSERT_TRUE(res);
  2431. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2432. EXPECT_EQ("error", res->body);
  2433. }
  2434. }
  2435. TEST(InvalidFormatTest, StatusCode) {
  2436. Server svr;
  2437. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2438. res.set_content("Hello World!\n", "text/plain");
  2439. res.status = 9999; // Status should be a three-digit code...
  2440. });
  2441. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2442. auto se = detail::scope_exit([&] {
  2443. svr.stop();
  2444. thread.join();
  2445. ASSERT_FALSE(svr.is_running());
  2446. });
  2447. svr.wait_until_ready();
  2448. {
  2449. Client cli(HOST, PORT);
  2450. auto res = cli.Get("/hi");
  2451. ASSERT_FALSE(res);
  2452. }
  2453. }
  2454. TEST(URLFragmentTest, WithFragment) {
  2455. Server svr;
  2456. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2457. EXPECT_TRUE(req.target == "/hi");
  2458. });
  2459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2460. auto se = detail::scope_exit([&] {
  2461. svr.stop();
  2462. thread.join();
  2463. ASSERT_FALSE(svr.is_running());
  2464. });
  2465. svr.wait_until_ready();
  2466. {
  2467. Client cli(HOST, PORT);
  2468. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2469. EXPECT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::OK_200, res->status);
  2471. res = cli.Get("/hi%23key1=val1=key2=val2");
  2472. EXPECT_TRUE(res);
  2473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2474. }
  2475. }
  2476. TEST(HeaderWriter, SetHeaderWriter) {
  2477. Server svr;
  2478. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2479. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2480. return detail::write_headers(strm, hdrs);
  2481. });
  2482. svr.Get("/hi", [](const Request &req, Response &res) {
  2483. auto it = req.headers.find("CustomClientHeader");
  2484. EXPECT_TRUE(it != req.headers.end());
  2485. EXPECT_EQ(it->second, "CustomClientValue");
  2486. res.set_content("Hello World!\n", "text/plain");
  2487. });
  2488. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2489. auto se = detail::scope_exit([&] {
  2490. svr.stop();
  2491. thread.join();
  2492. ASSERT_FALSE(svr.is_running());
  2493. });
  2494. svr.wait_until_ready();
  2495. {
  2496. Client cli(HOST, PORT);
  2497. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2498. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2499. return detail::write_headers(strm, hdrs);
  2500. });
  2501. auto res = cli.Get("/hi");
  2502. EXPECT_TRUE(res);
  2503. EXPECT_EQ(StatusCode::OK_200, res->status);
  2504. auto it = res->headers.find("CustomServerHeader");
  2505. EXPECT_TRUE(it != res->headers.end());
  2506. EXPECT_EQ(it->second, "CustomServerValue");
  2507. }
  2508. }
  2509. class ServerTest : public ::testing::Test {
  2510. protected:
  2511. ServerTest()
  2512. : cli_(HOST, PORT)
  2513. #ifdef CPPHTTPLIB_SSL_ENABLED
  2514. ,
  2515. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2516. #endif
  2517. {
  2518. #ifdef CPPHTTPLIB_SSL_ENABLED
  2519. cli_.enable_server_certificate_verification(false);
  2520. #endif
  2521. }
  2522. virtual void SetUp() {
  2523. svr_.set_mount_point("/", "./www");
  2524. svr_.set_mount_point("/mount", "./www2");
  2525. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2526. svr_.Get("/hi",
  2527. [&](const Request & /*req*/, Response &res) {
  2528. res.set_content("Hello World!", "text/plain");
  2529. })
  2530. .Get("/file_content",
  2531. [&](const Request & /*req*/, Response &res) {
  2532. res.set_file_content("./www/dir/test.html");
  2533. })
  2534. .Get("/file_content_with_content_type",
  2535. [&](const Request & /*req*/, Response &res) {
  2536. res.set_file_content("./www/file", "text/plain");
  2537. })
  2538. .Get("/invalid_file_content",
  2539. [&](const Request & /*req*/, Response &res) {
  2540. res.set_file_content("./www/dir/invalid_file_path");
  2541. })
  2542. .Get("/http_response_splitting",
  2543. [&](const Request & /*req*/, Response &res) {
  2544. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2545. EXPECT_EQ(0U, res.headers.size());
  2546. EXPECT_FALSE(res.has_header("a"));
  2547. res.set_header("a", "1\nSet-Cookie: a=1");
  2548. EXPECT_EQ(0U, res.headers.size());
  2549. EXPECT_FALSE(res.has_header("a"));
  2550. res.set_header("a", "1\rSet-Cookie: a=1");
  2551. EXPECT_EQ(0U, res.headers.size());
  2552. EXPECT_FALSE(res.has_header("a"));
  2553. res.set_header("a\r\nb", "0");
  2554. EXPECT_EQ(0U, res.headers.size());
  2555. EXPECT_FALSE(res.has_header("a"));
  2556. res.set_header("a\rb", "0");
  2557. EXPECT_EQ(0U, res.headers.size());
  2558. EXPECT_FALSE(res.has_header("a"));
  2559. res.set_header("a\nb", "0");
  2560. EXPECT_EQ(0U, res.headers.size());
  2561. EXPECT_FALSE(res.has_header("a"));
  2562. res.set_redirect("1\r\nSet-Cookie: a=1");
  2563. EXPECT_EQ(0U, res.headers.size());
  2564. EXPECT_FALSE(res.has_header("Location"));
  2565. })
  2566. .Get("/slow",
  2567. [&](const Request & /*req*/, Response &res) {
  2568. std::this_thread::sleep_for(std::chrono::seconds(2));
  2569. res.set_content("slow", "text/plain");
  2570. })
  2571. #if 0
  2572. .Post("/slowpost",
  2573. [&](const Request & /*req*/, Response &res) {
  2574. std::this_thread::sleep_for(std::chrono::seconds(2));
  2575. res.set_content("slow", "text/plain");
  2576. })
  2577. #endif
  2578. .Get("/remote_addr",
  2579. [&](const Request &req, Response &res) {
  2580. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2581. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2582. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2583. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2584. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2585. #endif
  2586. res.set_content(req.remote_addr, "text/plain");
  2587. })
  2588. .Get("/local_addr",
  2589. [&](const Request &req, Response &res) {
  2590. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2591. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2592. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2593. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2594. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2595. #endif
  2596. auto local_addr = req.local_addr;
  2597. auto local_port = std::to_string(req.local_port);
  2598. res.set_content(local_addr.append(":").append(local_port),
  2599. "text/plain");
  2600. })
  2601. .Get("/endwith%",
  2602. [&](const Request & /*req*/, Response &res) {
  2603. res.set_content("Hello World!", "text/plain");
  2604. })
  2605. .Get("/a\\+\\+b",
  2606. [&](const Request &req, Response &res) {
  2607. ASSERT_TRUE(req.has_param("a +b"));
  2608. auto val = req.get_param_value("a +b");
  2609. res.set_content(val, "text/plain");
  2610. })
  2611. .Get("/", [&](const Request & /*req*/,
  2612. Response &res) { res.set_redirect("/hi"); })
  2613. .Post("/1",
  2614. [](const Request & /*req*/, Response &res) {
  2615. res.set_redirect("/2", StatusCode::SeeOther_303);
  2616. })
  2617. .Get("/2",
  2618. [](const Request & /*req*/, Response &res) {
  2619. res.set_content("redirected.", "text/plain");
  2620. res.status = StatusCode::OK_200;
  2621. })
  2622. .Post("/person",
  2623. [&](const Request &req, Response &res) {
  2624. if (req.has_param("name") && req.has_param("note")) {
  2625. persons_[req.get_param_value("name")] =
  2626. req.get_param_value("note");
  2627. } else {
  2628. res.status = StatusCode::BadRequest_400;
  2629. }
  2630. })
  2631. .Put("/person",
  2632. [&](const Request &req, Response &res) {
  2633. if (req.has_param("name") && req.has_param("note")) {
  2634. persons_[req.get_param_value("name")] =
  2635. req.get_param_value("note");
  2636. } else {
  2637. res.status = StatusCode::BadRequest_400;
  2638. }
  2639. })
  2640. .Get("/person/(.*)",
  2641. [&](const Request &req, Response &res) {
  2642. string name = req.matches[1];
  2643. if (persons_.find(name) != persons_.end()) {
  2644. auto note = persons_[name];
  2645. res.set_content(note, "text/plain");
  2646. } else {
  2647. res.status = StatusCode::NotFound_404;
  2648. }
  2649. })
  2650. .Delete("/person",
  2651. [&](const Request &req, Response &res) {
  2652. if (req.has_param("name")) {
  2653. string name = req.get_param_value("name");
  2654. if (persons_.find(name) != persons_.end()) {
  2655. persons_.erase(name);
  2656. res.set_content("DELETED", "text/plain");
  2657. } else {
  2658. res.status = StatusCode::NotFound_404;
  2659. }
  2660. } else {
  2661. res.status = StatusCode::BadRequest_400;
  2662. }
  2663. })
  2664. .Post("/x-www-form-urlencoded-json",
  2665. [&](const Request &req, Response &res) {
  2666. auto json = req.get_param_value("json");
  2667. ASSERT_EQ(JSON_DATA, json);
  2668. res.set_content(json, "appliation/json");
  2669. res.status = StatusCode::OK_200;
  2670. })
  2671. .Get("/streamed-chunked",
  2672. [&](const Request & /*req*/, Response &res) {
  2673. res.set_chunked_content_provider(
  2674. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2675. sink.os << "123";
  2676. sink.os << "456";
  2677. sink.os << "789";
  2678. sink.done();
  2679. return true;
  2680. });
  2681. })
  2682. .Get("/streamed-chunked-with-prohibited-trailer",
  2683. [&](const Request & /*req*/, Response &res) {
  2684. auto i = new int(0);
  2685. // Declare both a prohibited trailer (Content-Length) and an
  2686. // allowed one
  2687. res.set_header("Trailer", "Content-Length, X-Allowed");
  2688. res.set_chunked_content_provider(
  2689. "text/plain",
  2690. [i](size_t /*offset*/, DataSink &sink) {
  2691. switch (*i) {
  2692. case 0: sink.os << "123"; break;
  2693. case 1: sink.os << "456"; break;
  2694. case 2: sink.os << "789"; break;
  2695. case 3: {
  2696. sink.done_with_trailer(
  2697. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2698. } break;
  2699. }
  2700. (*i)++;
  2701. return true;
  2702. },
  2703. [i](bool success) {
  2704. EXPECT_TRUE(success);
  2705. delete i;
  2706. });
  2707. })
  2708. .Get("/streamed-chunked2",
  2709. [&](const Request & /*req*/, Response &res) {
  2710. auto i = new int(0);
  2711. res.set_chunked_content_provider(
  2712. "text/plain",
  2713. [i](size_t /*offset*/, DataSink &sink) {
  2714. switch (*i) {
  2715. case 0: sink.os << "123"; break;
  2716. case 1: sink.os << "456"; break;
  2717. case 2: sink.os << "789"; break;
  2718. case 3: sink.done(); break;
  2719. }
  2720. (*i)++;
  2721. return true;
  2722. },
  2723. [i](bool success) {
  2724. EXPECT_TRUE(success);
  2725. delete i;
  2726. });
  2727. })
  2728. .Get("/streamed-chunked-with-trailer",
  2729. [&](const Request & /*req*/, Response &res) {
  2730. auto i = new int(0);
  2731. res.set_header("Trailer", "Dummy1, Dummy2");
  2732. res.set_chunked_content_provider(
  2733. "text/plain",
  2734. [i](size_t /*offset*/, DataSink &sink) {
  2735. switch (*i) {
  2736. case 0: sink.os << "123"; break;
  2737. case 1: sink.os << "456"; break;
  2738. case 2: sink.os << "789"; break;
  2739. case 3: {
  2740. sink.done_with_trailer(
  2741. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2742. } break;
  2743. }
  2744. (*i)++;
  2745. return true;
  2746. },
  2747. [i](bool success) {
  2748. EXPECT_TRUE(success);
  2749. delete i;
  2750. });
  2751. })
  2752. .Get("/streamed",
  2753. [&](const Request & /*req*/, Response &res) {
  2754. res.set_content_provider(
  2755. 6, "text/plain",
  2756. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2757. sink.os << (offset < 3 ? "a" : "b");
  2758. return true;
  2759. });
  2760. })
  2761. .Get("/streamed-with-range",
  2762. [&](const Request &req, Response &res) {
  2763. auto data = new std::string("abcdefg");
  2764. res.set_content_provider(
  2765. data->size(), "text/plain",
  2766. [data](size_t offset, size_t length, DataSink &sink) {
  2767. size_t DATA_CHUNK_SIZE = 4;
  2768. const auto &d = *data;
  2769. auto out_len =
  2770. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2771. auto ret =
  2772. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2773. EXPECT_TRUE(ret);
  2774. return true;
  2775. },
  2776. [data, &req](bool success) {
  2777. EXPECT_EQ(success, !req.has_param("error"));
  2778. delete data;
  2779. });
  2780. })
  2781. .Get("/streamed-cancel",
  2782. [&](const Request & /*req*/, Response &res) {
  2783. res.set_content_provider(
  2784. size_t(-1), "text/plain",
  2785. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2786. sink.os << "data_chunk";
  2787. return true;
  2788. });
  2789. })
  2790. .Get("/regex-with-delimiter",
  2791. [&](const Request &req, Response & /*res*/) {
  2792. ASSERT_TRUE(req.has_param("key"));
  2793. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2794. })
  2795. .Get("/with-range",
  2796. [&](const Request & /*req*/, Response &res) {
  2797. res.set_content("abcdefg", "text/plain");
  2798. })
  2799. .Get("/test-start-time",
  2800. [&](const Request &req, Response & /*res*/) {
  2801. EXPECT_NE(req.start_time_,
  2802. std::chrono::steady_clock::time_point::min());
  2803. })
  2804. .Get("/with-range-customized-response",
  2805. [&](const Request & /*req*/, Response &res) {
  2806. res.status = StatusCode::BadRequest_400;
  2807. res.set_content(JSON_DATA, "application/json");
  2808. })
  2809. .Post("/chunked",
  2810. [&](const Request &req, Response & /*res*/) {
  2811. EXPECT_EQ(req.body, "dechunked post body");
  2812. })
  2813. .Post("/large-chunked",
  2814. [&](const Request &req, Response & /*res*/) {
  2815. std::string expected(6 * 30 * 1024u, 'a');
  2816. EXPECT_EQ(req.body, expected);
  2817. })
  2818. .Post("/multipart",
  2819. [&](const Request &req, Response & /*res*/) {
  2820. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2821. req.form.get_field_count("text2") +
  2822. req.form.get_field_count("file3") +
  2823. req.form.get_field_count("file4"));
  2824. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2825. req.form.get_file_count("file2"));
  2826. ASSERT_TRUE(!req.form.has_file("???"));
  2827. ASSERT_TRUE(!req.form.has_field("???"));
  2828. ASSERT_TRUE(req.body.empty());
  2829. {
  2830. const auto &text = req.form.get_field("text1");
  2831. EXPECT_EQ("text default", text);
  2832. }
  2833. {
  2834. const auto &text = req.form.get_field("text2");
  2835. EXPECT_EQ("aωb", text);
  2836. }
  2837. {
  2838. const auto &file = req.form.get_file("file1");
  2839. EXPECT_EQ("hello.txt", file.filename);
  2840. EXPECT_EQ("text/plain", file.content_type);
  2841. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2842. }
  2843. {
  2844. const auto &file = req.form.get_file("file2");
  2845. EXPECT_EQ("world.json", file.filename);
  2846. EXPECT_EQ("application/json", file.content_type);
  2847. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2848. }
  2849. {
  2850. const auto &text = req.form.get_field("file3");
  2851. EXPECT_EQ(0u, text.size());
  2852. }
  2853. {
  2854. const auto &text = req.form.get_field("file4");
  2855. EXPECT_EQ(0u, text.size());
  2856. }
  2857. })
  2858. .Post("/multipart/multi_file_values",
  2859. [&](const Request &req, Response & /*res*/) {
  2860. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2861. req.form.get_field_count("multi_text1"));
  2862. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2863. ASSERT_TRUE(!req.form.has_file("???"));
  2864. ASSERT_TRUE(!req.form.has_field("???"));
  2865. ASSERT_TRUE(req.body.empty());
  2866. {
  2867. const auto &text = req.form.get_field("text");
  2868. EXPECT_EQ("default text", text);
  2869. }
  2870. {
  2871. const auto &text1_values = req.form.get_fields("multi_text1");
  2872. EXPECT_EQ(2u, text1_values.size());
  2873. EXPECT_EQ("aaaaa", text1_values[0]);
  2874. EXPECT_EQ("bbbbb", text1_values[1]);
  2875. }
  2876. {
  2877. const auto &file1_values = req.form.get_files("multi_file1");
  2878. EXPECT_EQ(2u, file1_values.size());
  2879. auto file1 = file1_values[0];
  2880. EXPECT_EQ(file1.filename, "hello.txt");
  2881. EXPECT_EQ(file1.content_type, "text/plain");
  2882. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2883. auto file2 = file1_values[1];
  2884. EXPECT_EQ(file2.filename, "world.json");
  2885. EXPECT_EQ(file2.content_type, "application/json");
  2886. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2887. }
  2888. })
  2889. .Post("/empty",
  2890. [&](const Request &req, Response &res) {
  2891. EXPECT_EQ(req.body, "");
  2892. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2893. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2894. res.set_content("empty", "text/plain");
  2895. })
  2896. .Post("/empty-no-content-type",
  2897. [&](const Request &req, Response &res) {
  2898. EXPECT_EQ(req.body, "");
  2899. EXPECT_FALSE(req.has_header("Content-Type"));
  2900. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2901. res.set_content("empty-no-content-type", "text/plain");
  2902. })
  2903. .Post("/path-only",
  2904. [&](const Request &req, Response &res) {
  2905. EXPECT_EQ(req.body, "");
  2906. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2907. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2908. res.set_content("path-only", "text/plain");
  2909. })
  2910. .Post("/path-headers-only",
  2911. [&](const Request &req, Response &res) {
  2912. EXPECT_EQ(req.body, "");
  2913. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2914. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2915. EXPECT_EQ("world", req.get_header_value("hello"));
  2916. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2917. res.set_content("path-headers-only", "text/plain");
  2918. })
  2919. .Post("/post-large",
  2920. [&](const Request &req, Response &res) {
  2921. EXPECT_EQ(req.body, LARGE_DATA);
  2922. res.set_content(req.body, "text/plain");
  2923. })
  2924. .Post("/post-loopback",
  2925. [&](const Request &, Response &res,
  2926. ContentReader const &content_reader) {
  2927. std::string body;
  2928. content_reader([&](const char *data, size_t data_length) {
  2929. body.append(data, data_length);
  2930. return true;
  2931. });
  2932. res.set_content(body, "text/plain");
  2933. })
  2934. .Put("/put-loopback",
  2935. [&](const Request &, Response &res,
  2936. ContentReader const &content_reader) {
  2937. std::string body;
  2938. content_reader([&](const char *data, size_t data_length) {
  2939. body.append(data, data_length);
  2940. return true;
  2941. });
  2942. res.set_content(body, "text/plain");
  2943. })
  2944. .Patch("/patch-loopback",
  2945. [&](const Request &, Response &res,
  2946. ContentReader const &content_reader) {
  2947. std::string body;
  2948. content_reader([&](const char *data, size_t data_length) {
  2949. body.append(data, data_length);
  2950. return true;
  2951. });
  2952. res.set_content(body, "text/plain");
  2953. })
  2954. .Put("/empty-no-content-type",
  2955. [&](const Request &req, Response &res) {
  2956. EXPECT_EQ(req.body, "");
  2957. EXPECT_FALSE(req.has_header("Content-Type"));
  2958. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2959. res.set_content("empty-no-content-type", "text/plain");
  2960. })
  2961. .Put("/put",
  2962. [&](const Request &req, Response &res) {
  2963. EXPECT_EQ(req.body, "PUT");
  2964. res.set_content(req.body, "text/plain");
  2965. })
  2966. .Put("/put-large",
  2967. [&](const Request &req, Response &res) {
  2968. EXPECT_EQ(req.body, LARGE_DATA);
  2969. res.set_content(req.body, "text/plain");
  2970. })
  2971. .Patch("/patch",
  2972. [&](const Request &req, Response &res) {
  2973. EXPECT_EQ(req.body, "PATCH");
  2974. res.set_content(req.body, "text/plain");
  2975. })
  2976. .Delete("/delete",
  2977. [&](const Request & /*req*/, Response &res) {
  2978. res.set_content("DELETE", "text/plain");
  2979. })
  2980. .Delete("/delete-body",
  2981. [&](const Request &req, Response &res) {
  2982. EXPECT_EQ(req.body, "content");
  2983. res.set_content(req.body, "text/plain");
  2984. })
  2985. .Options(R"(\*)",
  2986. [&](const Request & /*req*/, Response &res) {
  2987. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2988. })
  2989. .Get("/request-target",
  2990. [&](const Request &req, Response & /*res*/) {
  2991. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2992. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2993. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2994. })
  2995. .Get("/long-query-value",
  2996. [&](const Request &req, Response & /*res*/) {
  2997. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2998. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2999. })
  3000. .Get("/too-long-query-value",
  3001. [&](const Request &req, Response & /*res*/) {
  3002. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3003. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3004. })
  3005. .Get("/array-param",
  3006. [&](const Request &req, Response & /*res*/) {
  3007. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3008. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3009. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3010. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3011. })
  3012. .Post("/validate-no-multiple-headers",
  3013. [&](const Request &req, Response & /*res*/) {
  3014. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3015. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3016. })
  3017. .Post("/content_receiver",
  3018. [&](const Request &req, Response &res,
  3019. const ContentReader &content_reader) {
  3020. if (req.is_multipart_form_data()) {
  3021. std::vector<FormData> items;
  3022. content_reader(
  3023. [&](const FormData &file) {
  3024. items.push_back(file);
  3025. return true;
  3026. },
  3027. [&](const char *data, size_t data_length) {
  3028. items.back().content.append(data, data_length);
  3029. return true;
  3030. });
  3031. EXPECT_EQ(5u, items.size());
  3032. {
  3033. const auto &file = get_file_value(items, "text1");
  3034. EXPECT_TRUE(file.filename.empty());
  3035. EXPECT_EQ("text default", file.content);
  3036. }
  3037. {
  3038. const auto &file = get_file_value(items, "text2");
  3039. EXPECT_TRUE(file.filename.empty());
  3040. EXPECT_EQ("aωb", file.content);
  3041. }
  3042. {
  3043. const auto &file = get_file_value(items, "file1");
  3044. EXPECT_EQ("hello.txt", file.filename);
  3045. EXPECT_EQ("text/plain", file.content_type);
  3046. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3047. }
  3048. {
  3049. const auto &file = get_file_value(items, "file2");
  3050. EXPECT_EQ("world.json", file.filename);
  3051. EXPECT_EQ("application/json", file.content_type);
  3052. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3053. }
  3054. {
  3055. const auto &file = get_file_value(items, "file3");
  3056. EXPECT_TRUE(file.filename.empty());
  3057. EXPECT_EQ("application/octet-stream", file.content_type);
  3058. EXPECT_EQ(0u, file.content.size());
  3059. }
  3060. } else {
  3061. std::string body;
  3062. content_reader([&](const char *data, size_t data_length) {
  3063. EXPECT_EQ(7U, data_length);
  3064. body.append(data, data_length);
  3065. return true;
  3066. });
  3067. EXPECT_EQ(body, "content");
  3068. res.set_content(body, "text/plain");
  3069. }
  3070. })
  3071. .Put("/content_receiver",
  3072. [&](const Request & /*req*/, Response &res,
  3073. const ContentReader &content_reader) {
  3074. std::string body;
  3075. content_reader([&](const char *data, size_t data_length) {
  3076. body.append(data, data_length);
  3077. return true;
  3078. });
  3079. EXPECT_EQ(body, "content");
  3080. res.set_content(body, "text/plain");
  3081. })
  3082. .Patch("/content_receiver",
  3083. [&](const Request & /*req*/, Response &res,
  3084. const ContentReader &content_reader) {
  3085. std::string body;
  3086. content_reader([&](const char *data, size_t data_length) {
  3087. body.append(data, data_length);
  3088. return true;
  3089. });
  3090. EXPECT_EQ(body, "content");
  3091. res.set_content(body, "text/plain");
  3092. })
  3093. .Post("/query-string-and-body",
  3094. [&](const Request &req, Response & /*res*/) {
  3095. ASSERT_TRUE(req.has_param("key"));
  3096. EXPECT_EQ(req.get_param_value("key"), "value");
  3097. EXPECT_EQ(req.body, "content");
  3098. })
  3099. .Get("/last-request",
  3100. [&](const Request &req, Response & /*res*/) {
  3101. EXPECT_EQ("close", req.get_header_value("Connection"));
  3102. })
  3103. .Get(R"(/redirect/(\d+))",
  3104. [&](const Request &req, Response &res) {
  3105. auto num = std::stoi(req.matches[1]) + 1;
  3106. std::string url = "/redirect/" + std::to_string(num);
  3107. res.set_redirect(url);
  3108. })
  3109. .Post("/binary",
  3110. [&](const Request &req, Response &res) {
  3111. EXPECT_EQ(4U, req.body.size());
  3112. EXPECT_EQ("application/octet-stream",
  3113. req.get_header_value("Content-Type"));
  3114. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3115. res.set_content(req.body, "application/octet-stream");
  3116. })
  3117. .Put("/binary",
  3118. [&](const Request &req, Response &res) {
  3119. EXPECT_EQ(4U, req.body.size());
  3120. EXPECT_EQ("application/octet-stream",
  3121. req.get_header_value("Content-Type"));
  3122. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3123. res.set_content(req.body, "application/octet-stream");
  3124. })
  3125. .Patch("/binary",
  3126. [&](const Request &req, Response &res) {
  3127. EXPECT_EQ(4U, req.body.size());
  3128. EXPECT_EQ("application/octet-stream",
  3129. req.get_header_value("Content-Type"));
  3130. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3131. res.set_content(req.body, "application/octet-stream");
  3132. })
  3133. .Delete("/binary",
  3134. [&](const Request &req, Response &res) {
  3135. EXPECT_EQ(4U, req.body.size());
  3136. EXPECT_EQ("application/octet-stream",
  3137. req.get_header_value("Content-Type"));
  3138. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3139. res.set_content(req.body, "application/octet-stream");
  3140. })
  3141. .Get("/issue1772",
  3142. [&](const Request & /*req*/, Response &res) {
  3143. res.status = 401;
  3144. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3145. })
  3146. .Delete("/issue609",
  3147. [](const httplib::Request &, httplib::Response &res,
  3148. const httplib::ContentReader &) {
  3149. res.set_content("ok", "text/plain");
  3150. })
  3151. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3152. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3153. .Get("/compress",
  3154. [&](const Request & /*req*/, Response &res) {
  3155. res.set_content(
  3156. "12345678901234567890123456789012345678901234567890123456789"
  3157. "01234567890123456789012345678901234567890",
  3158. "text/plain");
  3159. })
  3160. .Get("/nocompress",
  3161. [&](const Request & /*req*/, Response &res) {
  3162. res.set_content(
  3163. "12345678901234567890123456789012345678901234567890123456789"
  3164. "01234567890123456789012345678901234567890",
  3165. "application/octet-stream");
  3166. })
  3167. .Post("/compress-multipart",
  3168. [&](const Request &req, Response & /*res*/) {
  3169. EXPECT_EQ(2u, req.form.fields.size());
  3170. ASSERT_TRUE(!req.form.has_field("???"));
  3171. {
  3172. const auto &text = req.form.get_field("key1");
  3173. EXPECT_EQ("test", text);
  3174. }
  3175. {
  3176. const auto &text = req.form.get_field("key2");
  3177. EXPECT_EQ("--abcdefg123", text);
  3178. }
  3179. })
  3180. #endif
  3181. ;
  3182. persons_["john"] = "programmer";
  3183. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3184. svr_.wait_until_ready();
  3185. }
  3186. virtual void TearDown() {
  3187. svr_.stop();
  3188. if (!request_threads_.empty()) {
  3189. std::this_thread::sleep_for(std::chrono::seconds(1));
  3190. for (auto &t : request_threads_) {
  3191. t.join();
  3192. }
  3193. }
  3194. t_.join();
  3195. }
  3196. map<string, string> persons_;
  3197. #ifdef CPPHTTPLIB_SSL_ENABLED
  3198. SSLClient cli_;
  3199. SSLServer svr_;
  3200. #else
  3201. Client cli_;
  3202. Server svr_;
  3203. #endif
  3204. thread t_;
  3205. std::vector<thread> request_threads_;
  3206. };
  3207. TEST_F(ServerTest, GetMethod200) {
  3208. auto res = cli_.Get("/hi");
  3209. ASSERT_TRUE(res);
  3210. EXPECT_EQ("HTTP/1.1", res->version);
  3211. EXPECT_EQ(StatusCode::OK_200, res->status);
  3212. EXPECT_EQ("OK", res->reason);
  3213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3214. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3215. EXPECT_EQ("Hello World!", res->body);
  3216. }
  3217. TEST_F(ServerTest, GetEmptyFile) {
  3218. auto res = cli_.Get("/empty_file");
  3219. ASSERT_TRUE(res);
  3220. EXPECT_EQ(StatusCode::OK_200, res->status);
  3221. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3222. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3223. EXPECT_EQ("", res->body);
  3224. }
  3225. TEST_F(ServerTest, GetFileContent) {
  3226. auto res = cli_.Get("/file_content");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3230. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3231. EXPECT_EQ("test.html", res->body);
  3232. }
  3233. TEST_F(ServerTest, GetFileContentWithRange) {
  3234. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3235. ASSERT_TRUE(res);
  3236. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3237. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3238. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3239. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3240. EXPECT_EQ("est", res->body);
  3241. }
  3242. TEST_F(ServerTest, GetFileContentWithContentType) {
  3243. auto res = cli_.Get("/file_content_with_content_type");
  3244. ASSERT_TRUE(res);
  3245. EXPECT_EQ(StatusCode::OK_200, res->status);
  3246. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3247. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3248. EXPECT_EQ("file\n", res->body);
  3249. }
  3250. TEST_F(ServerTest, GetInvalidFileContent) {
  3251. auto res = cli_.Get("/invalid_file_content");
  3252. ASSERT_TRUE(res);
  3253. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3254. }
  3255. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3256. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3257. ASSERT_TRUE(res);
  3258. EXPECT_EQ("HTTP/1.1", res->version);
  3259. EXPECT_EQ(StatusCode::OK_200, res->status);
  3260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3261. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3262. EXPECT_EQ("Hello World!", res->body);
  3263. }
  3264. TEST_F(ServerTest, GetMethod302) {
  3265. auto res = cli_.Get("/");
  3266. ASSERT_TRUE(res);
  3267. EXPECT_EQ(StatusCode::Found_302, res->status);
  3268. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3269. }
  3270. TEST_F(ServerTest, GetMethod302Redirect) {
  3271. cli_.set_follow_location(true);
  3272. auto res = cli_.Get("/");
  3273. ASSERT_TRUE(res);
  3274. EXPECT_EQ(StatusCode::OK_200, res->status);
  3275. EXPECT_EQ("Hello World!", res->body);
  3276. EXPECT_EQ("/hi", res->location);
  3277. }
  3278. TEST_F(ServerTest, GetMethod404) {
  3279. auto res = cli_.Get("/invalid");
  3280. ASSERT_TRUE(res);
  3281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3282. }
  3283. TEST_F(ServerTest, HeadMethod200) {
  3284. auto res = cli_.Head("/hi");
  3285. ASSERT_TRUE(res);
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3288. EXPECT_TRUE(res->body.empty());
  3289. }
  3290. TEST_F(ServerTest, HeadMethod200Static) {
  3291. auto res = cli_.Head("/mount/dir/index.html");
  3292. ASSERT_TRUE(res);
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3295. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3296. EXPECT_TRUE(res->body.empty());
  3297. }
  3298. TEST_F(ServerTest, HeadMethod404) {
  3299. auto res = cli_.Head("/invalid");
  3300. ASSERT_TRUE(res);
  3301. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3302. EXPECT_TRUE(res->body.empty());
  3303. }
  3304. TEST_F(ServerTest, GetMethodPersonJohn) {
  3305. auto res = cli_.Get("/person/john");
  3306. ASSERT_TRUE(res);
  3307. EXPECT_EQ(StatusCode::OK_200, res->status);
  3308. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3309. EXPECT_EQ("programmer", res->body);
  3310. }
  3311. TEST_F(ServerTest, PostMethod1) {
  3312. auto res = cli_.Get("/person/john1");
  3313. ASSERT_TRUE(res);
  3314. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3315. res = cli_.Post("/person", "name=john1&note=coder",
  3316. "application/x-www-form-urlencoded");
  3317. ASSERT_TRUE(res);
  3318. ASSERT_EQ(StatusCode::OK_200, res->status);
  3319. res = cli_.Get("/person/john1");
  3320. ASSERT_TRUE(res);
  3321. ASSERT_EQ(StatusCode::OK_200, res->status);
  3322. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3323. ASSERT_EQ("coder", res->body);
  3324. }
  3325. TEST_F(ServerTest, PostMethod2) {
  3326. auto res = cli_.Get("/person/john2");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3329. Params params;
  3330. params.emplace("name", "john2");
  3331. params.emplace("note", "coder");
  3332. res = cli_.Post("/person", params);
  3333. ASSERT_TRUE(res);
  3334. ASSERT_EQ(StatusCode::OK_200, res->status);
  3335. res = cli_.Get("/person/john2");
  3336. ASSERT_TRUE(res);
  3337. ASSERT_EQ(StatusCode::OK_200, res->status);
  3338. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3339. ASSERT_EQ("coder", res->body);
  3340. }
  3341. TEST_F(ServerTest, PutMethod3) {
  3342. auto res = cli_.Get("/person/john3");
  3343. ASSERT_TRUE(res);
  3344. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3345. Params params;
  3346. params.emplace("name", "john3");
  3347. params.emplace("note", "coder");
  3348. res = cli_.Put("/person", params);
  3349. ASSERT_TRUE(res);
  3350. ASSERT_EQ(StatusCode::OK_200, res->status);
  3351. res = cli_.Get("/person/john3");
  3352. ASSERT_TRUE(res);
  3353. ASSERT_EQ(StatusCode::OK_200, res->status);
  3354. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3355. ASSERT_EQ("coder", res->body);
  3356. }
  3357. TEST_F(ServerTest, DeleteMethod1) {
  3358. auto res = cli_.Get("/person/john4");
  3359. ASSERT_TRUE(res);
  3360. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3361. Params params;
  3362. params.emplace("name", "john4");
  3363. params.emplace("note", "coder");
  3364. res = cli_.Post("/person", params);
  3365. ASSERT_TRUE(res);
  3366. ASSERT_EQ(StatusCode::OK_200, res->status);
  3367. res = cli_.Get("/person/john4");
  3368. ASSERT_TRUE(res);
  3369. ASSERT_EQ(StatusCode::OK_200, res->status);
  3370. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3371. ASSERT_EQ("coder", res->body);
  3372. Params delete_params;
  3373. delete_params.emplace("name", "john4");
  3374. res = cli_.Delete("/person", delete_params);
  3375. ASSERT_TRUE(res);
  3376. ASSERT_EQ(StatusCode::OK_200, res->status);
  3377. ASSERT_EQ("DELETED", res->body);
  3378. res = cli_.Get("/person/john4");
  3379. ASSERT_TRUE(res);
  3380. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3381. }
  3382. TEST_F(ServerTest, DeleteMethod2) {
  3383. auto res = cli_.Get("/person/john5");
  3384. ASSERT_TRUE(res);
  3385. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3386. Params params;
  3387. params.emplace("name", "john5");
  3388. params.emplace("note", "developer");
  3389. res = cli_.Post("/person", params);
  3390. ASSERT_TRUE(res);
  3391. ASSERT_EQ(StatusCode::OK_200, res->status);
  3392. res = cli_.Get("/person/john5");
  3393. ASSERT_TRUE(res);
  3394. ASSERT_EQ(StatusCode::OK_200, res->status);
  3395. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3396. ASSERT_EQ("developer", res->body);
  3397. Params delete_params;
  3398. delete_params.emplace("name", "john5");
  3399. Headers headers;
  3400. headers.emplace("Custom-Header", "test-value");
  3401. res = cli_.Delete("/person", headers, delete_params);
  3402. ASSERT_TRUE(res);
  3403. ASSERT_EQ(StatusCode::OK_200, res->status);
  3404. ASSERT_EQ("DELETED", res->body);
  3405. res = cli_.Get("/person/john5");
  3406. ASSERT_TRUE(res);
  3407. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3408. }
  3409. TEST_F(ServerTest, DeleteMethod3) {
  3410. auto res = cli_.Get("/person/john6");
  3411. ASSERT_TRUE(res);
  3412. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3413. Params params;
  3414. params.emplace("name", "john6");
  3415. params.emplace("note", "tester");
  3416. res = cli_.Post("/person", params);
  3417. ASSERT_TRUE(res);
  3418. ASSERT_EQ(StatusCode::OK_200, res->status);
  3419. res = cli_.Get("/person/john6");
  3420. ASSERT_TRUE(res);
  3421. ASSERT_EQ(StatusCode::OK_200, res->status);
  3422. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3423. ASSERT_EQ("tester", res->body);
  3424. Params delete_params;
  3425. delete_params.emplace("name", "john6");
  3426. Headers headers;
  3427. headers.emplace("Custom-Header", "test-value");
  3428. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3429. ASSERT_TRUE(res);
  3430. ASSERT_EQ(StatusCode::OK_200, res->status);
  3431. ASSERT_EQ("DELETED", res->body);
  3432. res = cli_.Get("/person/john6");
  3433. ASSERT_TRUE(res);
  3434. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3435. }
  3436. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3437. Params params;
  3438. params.emplace("json", JSON_DATA);
  3439. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3440. ASSERT_TRUE(res);
  3441. ASSERT_EQ(StatusCode::OK_200, res->status);
  3442. ASSERT_EQ(JSON_DATA, res->body);
  3443. }
  3444. TEST_F(ServerTest, PostEmptyContent) {
  3445. auto res = cli_.Post("/empty", "", "text/plain");
  3446. ASSERT_TRUE(res);
  3447. ASSERT_EQ(StatusCode::OK_200, res->status);
  3448. ASSERT_EQ("empty", res->body);
  3449. }
  3450. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3451. auto res = cli_.Post("/empty-no-content-type");
  3452. ASSERT_TRUE(res);
  3453. ASSERT_EQ(StatusCode::OK_200, res->status);
  3454. ASSERT_EQ("empty-no-content-type", res->body);
  3455. }
  3456. TEST_F(ServerTest, PostPathOnly) {
  3457. auto res = cli_.Post("/path-only");
  3458. ASSERT_TRUE(res);
  3459. ASSERT_EQ(StatusCode::OK_200, res->status);
  3460. ASSERT_EQ("path-only", res->body);
  3461. }
  3462. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3463. auto res = cli_.Post("/path-headers-only",
  3464. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3465. ASSERT_TRUE(res);
  3466. ASSERT_EQ(StatusCode::OK_200, res->status);
  3467. ASSERT_EQ("path-headers-only", res->body);
  3468. }
  3469. TEST_F(ServerTest, PostLarge) {
  3470. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3471. ASSERT_TRUE(res);
  3472. ASSERT_EQ(StatusCode::OK_200, res->status);
  3473. EXPECT_EQ(LARGE_DATA, res->body);
  3474. }
  3475. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3476. auto res = cli_.Put("/empty-no-content-type");
  3477. ASSERT_TRUE(res);
  3478. ASSERT_EQ(StatusCode::OK_200, res->status);
  3479. ASSERT_EQ("empty-no-content-type", res->body);
  3480. }
  3481. TEST_F(ServerTest, GetMethodDir) {
  3482. auto res = cli_.Get("/dir/");
  3483. ASSERT_TRUE(res);
  3484. EXPECT_EQ(StatusCode::OK_200, res->status);
  3485. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3486. auto body = R"(<html>
  3487. <head>
  3488. </head>
  3489. <body>
  3490. <a href="/dir/test.html">Test</a>
  3491. <a href="/hi">hi</a>
  3492. </body>
  3493. </html>
  3494. )";
  3495. EXPECT_EQ(body, res->body);
  3496. }
  3497. TEST_F(ServerTest, GetMethodDirTest) {
  3498. auto res = cli_.Get("/dir/test.html");
  3499. ASSERT_TRUE(res);
  3500. EXPECT_EQ(StatusCode::OK_200, res->status);
  3501. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3502. EXPECT_EQ("test.html", res->body);
  3503. }
  3504. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3505. auto res = cli_.Get("/dir/../dir/test.html");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(StatusCode::OK_200, res->status);
  3508. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3509. EXPECT_EQ("test.html", res->body);
  3510. }
  3511. TEST_F(ServerTest, GetMethodInvalidPath) {
  3512. auto res = cli_.Get("/dir/../test.html");
  3513. ASSERT_TRUE(res);
  3514. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3515. }
  3516. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3517. auto res = cli_.Get("/../www/dir/test.html");
  3518. ASSERT_TRUE(res);
  3519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3520. }
  3521. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3522. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3523. ASSERT_TRUE(res);
  3524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3525. }
  3526. TEST_F(ServerTest, GetMethodDirMountTest) {
  3527. auto res = cli_.Get("/mount/dir/test.html");
  3528. ASSERT_TRUE(res);
  3529. EXPECT_EQ(StatusCode::OK_200, res->status);
  3530. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3531. EXPECT_EQ("test.html", res->body);
  3532. }
  3533. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3534. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3535. ASSERT_TRUE(res);
  3536. EXPECT_EQ(StatusCode::OK_200, res->status);
  3537. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3538. EXPECT_EQ("test.html", res->body);
  3539. }
  3540. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3541. auto res = cli_.Get("/mount/dir/../test.html");
  3542. ASSERT_TRUE(res);
  3543. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3544. }
  3545. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3546. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3547. ASSERT_TRUE(res);
  3548. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3549. }
  3550. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3551. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3552. ASSERT_TRUE(res);
  3553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3554. }
  3555. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3556. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3559. }
  3560. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3561. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3562. ASSERT_TRUE(res);
  3563. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3564. }
  3565. TEST_F(ServerTest, PostMethod303) {
  3566. auto res = cli_.Post("/1", "body", "text/plain");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3569. EXPECT_EQ("/2", res->get_header_value("Location"));
  3570. }
  3571. TEST_F(ServerTest, PostMethod303Redirect) {
  3572. cli_.set_follow_location(true);
  3573. auto res = cli_.Post("/1", "body", "text/plain");
  3574. ASSERT_TRUE(res);
  3575. EXPECT_EQ(StatusCode::OK_200, res->status);
  3576. EXPECT_EQ("redirected.", res->body);
  3577. EXPECT_EQ("/2", res->location);
  3578. }
  3579. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3580. auto res = cli_.Get("/dir/test.abcde");
  3581. ASSERT_TRUE(res);
  3582. EXPECT_EQ(StatusCode::OK_200, res->status);
  3583. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3584. EXPECT_EQ("abcde", res->body);
  3585. }
  3586. TEST_F(ServerTest, StaticFileRange) {
  3587. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3588. ASSERT_TRUE(res);
  3589. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3590. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3591. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3592. EXPECT_EQ(true, res->has_header("Content-Range"));
  3593. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3594. EXPECT_EQ(std::string("cd"), res->body);
  3595. }
  3596. TEST_F(ServerTest, StaticFileRanges) {
  3597. auto res =
  3598. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3599. ASSERT_TRUE(res);
  3600. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3601. EXPECT_TRUE(
  3602. res->get_header_value("Content-Type")
  3603. .find(
  3604. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3605. 0);
  3606. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3607. }
  3608. TEST_F(ServerTest, StaticFileRangeHead) {
  3609. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3610. ASSERT_TRUE(res);
  3611. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3612. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3613. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3614. EXPECT_EQ(true, res->has_header("Content-Range"));
  3615. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3616. }
  3617. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3618. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3619. ASSERT_TRUE(res);
  3620. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3621. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3622. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3623. EXPECT_EQ(true, res->has_header("Content-Range"));
  3624. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3625. res->get_header_value("Content-Range"));
  3626. EXPECT_EQ("LAST\n", res->body);
  3627. }
  3628. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3629. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3630. ASSERT_TRUE(res);
  3631. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3633. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3634. EXPECT_EQ(true, res->has_header("Content-Range"));
  3635. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3636. }
  3637. TEST_F(ServerTest, StaticFileBigFile) {
  3638. auto res = cli_.Get("/dir/1MB.txt");
  3639. ASSERT_TRUE(res);
  3640. EXPECT_EQ(StatusCode::OK_200, res->status);
  3641. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3642. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3643. }
  3644. TEST_F(ServerTest, InvalidBaseDirMount) {
  3645. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3646. }
  3647. TEST_F(ServerTest, Binary) {
  3648. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3649. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3650. "application/octet-stream");
  3651. ASSERT_TRUE(res);
  3652. ASSERT_EQ(StatusCode::OK_200, res->status);
  3653. ASSERT_EQ(4U, res->body.size());
  3654. res = cli_.Put("/binary", binary.data(), binary.size(),
  3655. "application/octet-stream");
  3656. ASSERT_TRUE(res);
  3657. ASSERT_EQ(StatusCode::OK_200, res->status);
  3658. ASSERT_EQ(4U, res->body.size());
  3659. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3660. "application/octet-stream");
  3661. ASSERT_TRUE(res);
  3662. ASSERT_EQ(StatusCode::OK_200, res->status);
  3663. ASSERT_EQ(4U, res->body.size());
  3664. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3665. "application/octet-stream");
  3666. ASSERT_TRUE(res);
  3667. ASSERT_EQ(StatusCode::OK_200, res->status);
  3668. ASSERT_EQ(4U, res->body.size());
  3669. }
  3670. TEST_F(ServerTest, BinaryString) {
  3671. auto binary = std::string("\x00\x01\x02\x03", 4);
  3672. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::OK_200, res->status);
  3675. ASSERT_EQ(4U, res->body.size());
  3676. res = cli_.Put("/binary", binary, "application/octet-stream");
  3677. ASSERT_TRUE(res);
  3678. ASSERT_EQ(StatusCode::OK_200, res->status);
  3679. ASSERT_EQ(4U, res->body.size());
  3680. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3681. ASSERT_TRUE(res);
  3682. ASSERT_EQ(StatusCode::OK_200, res->status);
  3683. ASSERT_EQ(4U, res->body.size());
  3684. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3685. ASSERT_TRUE(res);
  3686. ASSERT_EQ(StatusCode::OK_200, res->status);
  3687. ASSERT_EQ(4U, res->body.size());
  3688. }
  3689. TEST_F(ServerTest, EmptyRequest) {
  3690. auto res = cli_.Get("");
  3691. ASSERT_TRUE(!res);
  3692. EXPECT_EQ(Error::Connection, res.error());
  3693. }
  3694. TEST_F(ServerTest, LongRequest) {
  3695. std::string request;
  3696. for (size_t i = 0; i < 545; i++) {
  3697. request += "/TooLongRequest";
  3698. }
  3699. request += "OK";
  3700. auto res = cli_.Get(request.c_str());
  3701. ASSERT_TRUE(res);
  3702. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3703. }
  3704. TEST_F(ServerTest, TooLongRequest) {
  3705. std::string request;
  3706. for (size_t i = 0; i < 546; i++) {
  3707. request += "/TooLongRequest";
  3708. }
  3709. request += "_NG";
  3710. auto start = std::chrono::high_resolution_clock::now();
  3711. cli_.set_keep_alive(true);
  3712. auto res = cli_.Get(request.c_str());
  3713. auto end = std::chrono::high_resolution_clock::now();
  3714. auto elapsed =
  3715. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3716. .count();
  3717. ASSERT_TRUE(res);
  3718. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3719. EXPECT_LE(elapsed, 100);
  3720. EXPECT_EQ("close", res->get_header_value("Connection"));
  3721. EXPECT_FALSE(cli_.is_socket_open());
  3722. }
  3723. TEST_F(ServerTest, AlmostTooLongRequest) {
  3724. // test for #2046 - URI length check shouldn't include other content on req
  3725. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3726. // leading /, space, HTTP/1.1)
  3727. std::string request =
  3728. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3729. auto res = cli_.Get(request.c_str());
  3730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3731. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3732. }
  3733. TEST_F(ServerTest, LongHeader) {
  3734. Request req;
  3735. req.method = "GET";
  3736. req.path = "/hi";
  3737. std::string host_and_port;
  3738. host_and_port += HOST;
  3739. host_and_port += ":";
  3740. host_and_port += std::to_string(PORT);
  3741. req.headers.emplace("Host", host_and_port.c_str());
  3742. req.headers.emplace("Accept", "*/*");
  3743. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3744. req.headers.emplace(
  3745. "Header-Name",
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3774. "@@@@@@@@@@@@@@@@");
  3775. auto res = std::make_shared<Response>();
  3776. auto error = Error::Success;
  3777. auto ret = cli_.send(req, *res, error);
  3778. ASSERT_TRUE(ret);
  3779. EXPECT_EQ(StatusCode::OK_200, res->status);
  3780. }
  3781. TEST_F(ServerTest, LongQueryValue) {
  3782. auto start = std::chrono::high_resolution_clock::now();
  3783. cli_.set_keep_alive(true);
  3784. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3785. auto end = std::chrono::high_resolution_clock::now();
  3786. auto elapsed =
  3787. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3788. .count();
  3789. ASSERT_TRUE(res);
  3790. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3791. EXPECT_LE(elapsed, 100);
  3792. EXPECT_EQ("close", res->get_header_value("Connection"));
  3793. EXPECT_FALSE(cli_.is_socket_open());
  3794. }
  3795. TEST_F(ServerTest, TooLongQueryValue) {
  3796. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3797. ASSERT_FALSE(res);
  3798. EXPECT_EQ(Error::Read, res.error());
  3799. }
  3800. TEST_F(ServerTest, TooLongHeader) {
  3801. Request req;
  3802. req.method = "GET";
  3803. req.path = "/hi";
  3804. std::string host_and_port;
  3805. host_and_port += HOST;
  3806. host_and_port += ":";
  3807. host_and_port += std::to_string(PORT);
  3808. req.headers.emplace("Host", host_and_port.c_str());
  3809. req.headers.emplace("Accept", "*/*");
  3810. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3811. req.headers.emplace(
  3812. "Header-Name",
  3813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3821. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3822. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3823. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3824. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3841. "@@@@@@@@@@@@@@@@@");
  3842. auto res = std::make_shared<Response>();
  3843. auto error = Error::Success;
  3844. auto ret = cli_.send(req, *res, error);
  3845. ASSERT_TRUE(ret);
  3846. EXPECT_EQ(StatusCode::OK_200, res->status);
  3847. }
  3848. TEST_F(ServerTest, HeaderCountAtLimit) {
  3849. // Test with headers just under the 100 limit
  3850. httplib::Headers headers;
  3851. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3852. // This should keep us just under the 100 header limit
  3853. for (int i = 0; i < 95; i++) {
  3854. std::string name = "X-Test-Header-" + std::to_string(i);
  3855. std::string value = "value" + std::to_string(i);
  3856. headers.emplace(name, value);
  3857. }
  3858. // This should work fine as we're under the limit
  3859. auto res = cli_.Get("/hi", headers);
  3860. EXPECT_TRUE(res);
  3861. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3862. }
  3863. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3864. // Test with many headers to exceed the 100 limit
  3865. httplib::Headers headers;
  3866. // Add 150 headers to definitely exceed the 100 limit
  3867. for (int i = 0; i < 150; i++) {
  3868. std::string name = "X-Test-Header-" + std::to_string(i);
  3869. std::string value = "value" + std::to_string(i);
  3870. headers.emplace(name, value);
  3871. }
  3872. // This should fail due to exceeding header count limit
  3873. cli_.set_keep_alive(true);
  3874. auto res = cli_.Get("/hi", headers);
  3875. // The request should either fail or return 400 Bad Request
  3876. if (res) {
  3877. // If we get a response, it should be 400 Bad Request
  3878. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3879. } else {
  3880. // Or the request should fail entirely
  3881. EXPECT_FALSE(res);
  3882. }
  3883. EXPECT_EQ("close", res->get_header_value("Connection"));
  3884. EXPECT_FALSE(cli_.is_socket_open());
  3885. }
  3886. TEST_F(ServerTest, PercentEncoding) {
  3887. auto res = cli_.Get("/e%6edwith%");
  3888. ASSERT_TRUE(res);
  3889. EXPECT_EQ(StatusCode::OK_200, res->status);
  3890. }
  3891. TEST_F(ServerTest, PercentEncodingUnicode) {
  3892. auto res = cli_.Get("/e%u006edwith%");
  3893. ASSERT_TRUE(res);
  3894. EXPECT_EQ(StatusCode::OK_200, res->status);
  3895. }
  3896. TEST_F(ServerTest, InvalidPercentEncoding) {
  3897. auto res = cli_.Get("/%endwith%");
  3898. ASSERT_TRUE(res);
  3899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3900. }
  3901. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3902. auto res = cli_.Get("/%uendwith%");
  3903. ASSERT_TRUE(res);
  3904. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3905. }
  3906. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3907. auto res = cli_.Get("/hello?aaa=bbb%");
  3908. ASSERT_TRUE(res);
  3909. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3910. }
  3911. TEST_F(ServerTest, PlusSignEncoding) {
  3912. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3913. ASSERT_TRUE(res);
  3914. EXPECT_EQ(StatusCode::OK_200, res->status);
  3915. EXPECT_EQ("a +b", res->body);
  3916. }
  3917. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3918. // This test simulates a potential DoS attack using many headers
  3919. // to verify our security fix prevents memory exhaustion
  3920. httplib::Headers attack_headers;
  3921. // Attempt to add many headers like an attacker would (200 headers to far
  3922. // exceed limit)
  3923. for (int i = 0; i < 200; i++) {
  3924. std::string name = "X-Attack-Header-" + std::to_string(i);
  3925. std::string value = "attack_payload_" + std::to_string(i);
  3926. attack_headers.emplace(name, value);
  3927. }
  3928. // Try to POST with excessive headers
  3929. cli_.set_keep_alive(true);
  3930. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3931. // Should either fail or return 400 Bad Request due to security limit
  3932. if (res) {
  3933. // If we get a response, it should be 400 Bad Request
  3934. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3935. } else {
  3936. // Request failed, which is the expected behavior for DoS protection
  3937. EXPECT_FALSE(res);
  3938. }
  3939. EXPECT_EQ("close", res->get_header_value("Connection"));
  3940. EXPECT_FALSE(cli_.is_socket_open());
  3941. }
  3942. TEST_F(ServerTest, MultipartFormData) {
  3943. UploadFormDataItems items = {
  3944. {"text1", "text default", "", ""},
  3945. {"text2", "aωb", "", ""},
  3946. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3947. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3948. {"file3", "", "", "application/octet-stream"},
  3949. {"file4", "", "", " application/json tmp-string "}};
  3950. auto res = cli_.Post("/multipart", items);
  3951. ASSERT_TRUE(res);
  3952. EXPECT_EQ(StatusCode::OK_200, res->status);
  3953. }
  3954. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3955. UploadFormDataItems items = {
  3956. {"text", "default text", "", ""},
  3957. {"multi_text1", "aaaaa", "", ""},
  3958. {"multi_text1", "bbbbb", "", ""},
  3959. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3960. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3961. "application/json"},
  3962. };
  3963. auto res = cli_.Post("/multipart/multi_file_values", items);
  3964. ASSERT_TRUE(res);
  3965. EXPECT_EQ(StatusCode::OK_200, res->status);
  3966. }
  3967. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3968. auto res = cli_.Get("/hi");
  3969. ASSERT_TRUE(res);
  3970. EXPECT_EQ(StatusCode::OK_200, res->status);
  3971. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3972. EXPECT_EQ("Hello World!", res->body);
  3973. }
  3974. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3975. Request req;
  3976. req.method = "POST";
  3977. req.path = "/chunked";
  3978. std::string host_and_port;
  3979. host_and_port += HOST;
  3980. host_and_port += ":";
  3981. host_and_port += std::to_string(PORT);
  3982. req.headers.emplace("Host", host_and_port.c_str());
  3983. req.headers.emplace("Accept", "*/*");
  3984. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3985. req.headers.emplace("Content-Type", "text/plain");
  3986. req.headers.emplace("Content-Length", "0");
  3987. req.headers.emplace(
  3988. "Transfer-Encoding",
  3989. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3990. // Client does not chunk, so make a chunked body manually.
  3991. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3992. auto res = std::make_shared<Response>();
  3993. auto error = Error::Success;
  3994. auto ret = cli_.send(req, *res, error);
  3995. ASSERT_TRUE(ret);
  3996. EXPECT_EQ(StatusCode::OK_200, res->status);
  3997. }
  3998. TEST_F(ServerTest, GetStreamed2) {
  3999. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4000. ASSERT_TRUE(res);
  4001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4002. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4003. EXPECT_EQ(true, res->has_header("Content-Range"));
  4004. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4005. EXPECT_EQ(std::string("ab"), res->body);
  4006. }
  4007. TEST_F(ServerTest, GetStreamed) {
  4008. auto res = cli_.Get("/streamed");
  4009. ASSERT_TRUE(res);
  4010. EXPECT_EQ(StatusCode::OK_200, res->status);
  4011. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4012. EXPECT_EQ(std::string("aaabbb"), res->body);
  4013. }
  4014. TEST_F(ServerTest, GetStreamedWithRange1) {
  4015. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4016. ASSERT_TRUE(res);
  4017. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4018. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4019. EXPECT_EQ(true, res->has_header("Content-Range"));
  4020. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4021. EXPECT_EQ(std::string("def"), res->body);
  4022. }
  4023. TEST_F(ServerTest, GetStreamedWithRange2) {
  4024. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4025. ASSERT_TRUE(res);
  4026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4027. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4028. EXPECT_EQ(true, res->has_header("Content-Range"));
  4029. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4030. EXPECT_EQ(std::string("bcdefg"), res->body);
  4031. }
  4032. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4033. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4034. ASSERT_TRUE(res);
  4035. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4036. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4037. EXPECT_EQ(true, res->has_header("Content-Range"));
  4038. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4039. EXPECT_EQ(std::string("efg"), res->body);
  4040. }
  4041. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4042. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4043. ASSERT_TRUE(res);
  4044. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4045. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4046. EXPECT_EQ(false, res->has_header("Content-Range"));
  4047. EXPECT_EQ(0U, res->body.size());
  4048. }
  4049. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4050. auto res = cli_.Get("/streamed-with-range",
  4051. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4052. "92233720368547758079223372036854775807"}});
  4053. ASSERT_TRUE(res);
  4054. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4055. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4056. EXPECT_EQ(false, res->has_header("Content-Range"));
  4057. EXPECT_EQ(0U, res->body.size());
  4058. }
  4059. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4060. auto res = cli_.Get(
  4061. "/with-range",
  4062. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4063. {"Accept-Encoding", ""}});
  4064. ASSERT_TRUE(res);
  4065. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4066. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4067. EXPECT_EQ(true, res->has_header("Content-Range"));
  4068. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4069. EXPECT_EQ(std::string("abcdefg"), res->body);
  4070. }
  4071. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4072. auto res = cli_.Get("/with-range", {
  4073. {"Range", "bytes=0-"},
  4074. {"Accept-Encoding", ""},
  4075. });
  4076. ASSERT_TRUE(res);
  4077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4078. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4079. EXPECT_EQ(true, res->has_header("Content-Range"));
  4080. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4081. EXPECT_EQ(std::string("abcdefg"), res->body);
  4082. }
  4083. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4084. auto res =
  4085. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4086. ASSERT_TRUE(res);
  4087. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4088. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4089. EXPECT_EQ(false, res->has_header("Content-Range"));
  4090. EXPECT_EQ(267U, res->body.size());
  4091. // Check that both range contents are present
  4092. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4093. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4094. // Check that Content-Range headers are present for both ranges
  4095. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4096. std::string::npos);
  4097. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4098. std::string::npos);
  4099. }
  4100. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4101. Ranges ranges;
  4102. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4103. ranges.emplace_back(0, -1);
  4104. }
  4105. auto res =
  4106. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4107. ASSERT_TRUE(res);
  4108. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4109. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4110. EXPECT_EQ(false, res->has_header("Content-Range"));
  4111. EXPECT_EQ(0U, res->body.size());
  4112. }
  4113. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4114. auto res =
  4115. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4116. ASSERT_TRUE(res);
  4117. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4118. EXPECT_EQ(5U, res->body.size());
  4119. // Check that overlapping ranges are coalesced into a single range
  4120. EXPECT_EQ("bcdef", res->body);
  4121. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4122. // Should be single range, not multipart
  4123. EXPECT_TRUE(res->has_header("Content-Range"));
  4124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4125. }
  4126. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4127. auto res =
  4128. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4131. EXPECT_EQ(268U, res->body.size());
  4132. // Check that both range contents are present
  4133. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4134. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4135. // Check that Content-Range headers are present for both ranges
  4136. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4137. std::string::npos);
  4138. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4139. std::string::npos);
  4140. }
  4141. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4142. auto res =
  4143. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4144. ASSERT_TRUE(res);
  4145. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4146. EXPECT_EQ(269U, res->body.size());
  4147. // Check that both duplicate range contents are present
  4148. size_t first_abc = res->body.find("abc\r\n");
  4149. EXPECT_TRUE(first_abc != std::string::npos);
  4150. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4151. EXPECT_TRUE(second_abc != std::string::npos);
  4152. // Check that Content-Range headers are present for both ranges
  4153. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4154. EXPECT_TRUE(first_range != std::string::npos);
  4155. size_t second_range =
  4156. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4157. EXPECT_TRUE(second_range != std::string::npos);
  4158. }
  4159. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4160. auto res = cli_.Get("/streamed-with-range?error",
  4161. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4162. ASSERT_TRUE(res);
  4163. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4164. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4165. EXPECT_EQ(false, res->has_header("Content-Range"));
  4166. EXPECT_EQ(0U, res->body.size());
  4167. }
  4168. TEST_F(ServerTest, GetStreamedEndless) {
  4169. uint64_t offset = 0;
  4170. auto res = cli_.Get("/streamed-cancel",
  4171. [&](const char * /*data*/, uint64_t data_length) {
  4172. if (offset < 100) {
  4173. offset += data_length;
  4174. return true;
  4175. }
  4176. return false;
  4177. });
  4178. ASSERT_TRUE(!res);
  4179. EXPECT_EQ(Error::Canceled, res.error());
  4180. }
  4181. TEST_F(ServerTest, ClientStop) {
  4182. std::atomic_size_t count{4};
  4183. std::vector<std::thread> threads;
  4184. for (auto i = count.load(); i != 0; --i) {
  4185. threads.emplace_back([&]() {
  4186. auto res = cli_.Get("/streamed-cancel",
  4187. [&](const char *, uint64_t) { return true; });
  4188. --count;
  4189. ASSERT_TRUE(!res);
  4190. EXPECT_TRUE(res.error() == Error::Canceled ||
  4191. res.error() == Error::Read || res.error() == Error::Write);
  4192. });
  4193. }
  4194. std::this_thread::sleep_for(std::chrono::seconds(2));
  4195. while (count != 0) {
  4196. cli_.stop();
  4197. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4198. }
  4199. for (auto &t : threads) {
  4200. t.join();
  4201. }
  4202. }
  4203. TEST_F(ServerTest, GetWithRange1) {
  4204. auto res = cli_.Get("/with-range", {
  4205. make_range_header({{3, 5}}),
  4206. {"Accept-Encoding", ""},
  4207. });
  4208. ASSERT_TRUE(res);
  4209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4210. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4211. EXPECT_EQ(true, res->has_header("Content-Range"));
  4212. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4213. EXPECT_EQ(std::string("def"), res->body);
  4214. }
  4215. TEST_F(ServerTest, GetWithRange2) {
  4216. auto res = cli_.Get("/with-range", {
  4217. make_range_header({{1, -1}}),
  4218. {"Accept-Encoding", ""},
  4219. });
  4220. ASSERT_TRUE(res);
  4221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4222. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4223. EXPECT_EQ(true, res->has_header("Content-Range"));
  4224. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4225. EXPECT_EQ(std::string("bcdefg"), res->body);
  4226. }
  4227. TEST_F(ServerTest, GetWithRange3) {
  4228. auto res = cli_.Get("/with-range", {
  4229. make_range_header({{0, 0}}),
  4230. {"Accept-Encoding", ""},
  4231. });
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4234. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4235. EXPECT_EQ(true, res->has_header("Content-Range"));
  4236. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4237. EXPECT_EQ(std::string("a"), res->body);
  4238. }
  4239. TEST_F(ServerTest, GetWithRange4) {
  4240. auto res = cli_.Get("/with-range", {
  4241. make_range_header({{-1, 2}}),
  4242. {"Accept-Encoding", ""},
  4243. });
  4244. ASSERT_TRUE(res);
  4245. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4246. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4247. EXPECT_EQ(true, res->has_header("Content-Range"));
  4248. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4249. EXPECT_EQ(std::string("fg"), res->body);
  4250. }
  4251. TEST_F(ServerTest, GetWithRange5) {
  4252. auto res = cli_.Get("/with-range", {
  4253. make_range_header({{0, 5}}),
  4254. {"Accept-Encoding", ""},
  4255. });
  4256. ASSERT_TRUE(res);
  4257. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4258. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4259. EXPECT_EQ(true, res->has_header("Content-Range"));
  4260. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4261. EXPECT_EQ(std::string("abcdef"), res->body);
  4262. }
  4263. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4264. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4265. ASSERT_TRUE(res);
  4266. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4267. }
  4268. TEST_F(ServerTest, GetWithRangeMultipart) {
  4269. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4270. ASSERT_TRUE(res);
  4271. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4272. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4273. EXPECT_EQ(false, res->has_header("Content-Range"));
  4274. EXPECT_EQ(267U, res->body.size());
  4275. }
  4276. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4277. auto res =
  4278. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4281. }
  4282. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4283. auto res = cli_.Get("/with-range-customized-response",
  4284. {{make_range_header({{1, 2}})}});
  4285. ASSERT_TRUE(res);
  4286. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4287. EXPECT_EQ(true, res->has_header("Content-Length"));
  4288. EXPECT_EQ(false, res->has_header("Content-Range"));
  4289. EXPECT_EQ(JSON_DATA, res->body);
  4290. }
  4291. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4292. auto res = cli_.Get("/with-range-customized-response",
  4293. {{make_range_header({{1, 2}, {4, 5}})}});
  4294. ASSERT_TRUE(res);
  4295. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4296. EXPECT_EQ(true, res->has_header("Content-Length"));
  4297. EXPECT_EQ(false, res->has_header("Content-Range"));
  4298. EXPECT_EQ(JSON_DATA, res->body);
  4299. }
  4300. TEST_F(ServerTest, Issue1772) {
  4301. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4304. }
  4305. TEST_F(ServerTest, Issue609) {
  4306. auto res = cli_.Delete("/issue609");
  4307. ASSERT_TRUE(res);
  4308. EXPECT_EQ(StatusCode::OK_200, res->status);
  4309. EXPECT_EQ(std::string("ok"), res->body);
  4310. }
  4311. TEST_F(ServerTest, GetStreamedChunked) {
  4312. auto res = cli_.Get("/streamed-chunked");
  4313. ASSERT_TRUE(res);
  4314. EXPECT_EQ(StatusCode::OK_200, res->status);
  4315. EXPECT_EQ(std::string("123456789"), res->body);
  4316. }
  4317. TEST_F(ServerTest, GetStreamedChunked2) {
  4318. auto res = cli_.Get("/streamed-chunked2");
  4319. ASSERT_TRUE(res);
  4320. EXPECT_EQ(StatusCode::OK_200, res->status);
  4321. EXPECT_EQ(std::string("123456789"), res->body);
  4322. }
  4323. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4324. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. EXPECT_EQ(std::string("123456789"), res->body);
  4328. EXPECT_TRUE(res->has_header("Trailer"));
  4329. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4330. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4331. // Trailers are now stored separately from headers (security fix)
  4332. EXPECT_EQ(2U, res->trailers.size());
  4333. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4334. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4335. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4336. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4337. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4338. // Verify trailers are NOT in headers (security verification)
  4339. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4340. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4341. }
  4342. TEST_F(ServerTest, LargeChunkedPost) {
  4343. Request req;
  4344. req.method = "POST";
  4345. req.path = "/large-chunked";
  4346. std::string host_and_port;
  4347. host_and_port += HOST;
  4348. host_and_port += ":";
  4349. host_and_port += std::to_string(PORT);
  4350. req.headers.emplace("Host", host_and_port.c_str());
  4351. req.headers.emplace("Accept", "*/*");
  4352. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4353. req.headers.emplace("Content-Type", "text/plain");
  4354. req.headers.emplace("Content-Length", "0");
  4355. req.headers.emplace("Transfer-Encoding", "chunked");
  4356. std::string long_string(30 * 1024u, 'a');
  4357. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4358. // Attempt to make a large enough post to exceed OS buffers, to test that
  4359. // the server handles short reads if the full chunk data isn't available.
  4360. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4361. auto res = std::make_shared<Response>();
  4362. auto error = Error::Success;
  4363. auto ret = cli_.send(req, *res, error);
  4364. ASSERT_TRUE(ret);
  4365. EXPECT_EQ(StatusCode::OK_200, res->status);
  4366. }
  4367. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4368. auto res = cli_.Get("/remote_addr");
  4369. ASSERT_TRUE(res);
  4370. EXPECT_EQ(StatusCode::OK_200, res->status);
  4371. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4372. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4373. }
  4374. TEST_F(ServerTest, GetMethodLocalAddr) {
  4375. auto res = cli_.Get("/local_addr");
  4376. ASSERT_TRUE(res);
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4379. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4380. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4381. }
  4382. TEST_F(ServerTest, HTTPResponseSplitting) {
  4383. auto res = cli_.Get("/http_response_splitting");
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::OK_200, res->status);
  4386. }
  4387. TEST_F(ServerTest, SlowRequest) {
  4388. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4389. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4390. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4391. }
  4392. #if 0
  4393. TEST_F(ServerTest, SlowPost) {
  4394. char buffer[64 * 1024];
  4395. memset(buffer, 0x42, sizeof(buffer));
  4396. auto res = cli_.Post(
  4397. "/slowpost", 64 * 1024 * 1024,
  4398. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4399. auto ret = sink.write(buffer, sizeof(buffer));
  4400. EXPECT_TRUE(ret);
  4401. return true;
  4402. },
  4403. "text/plain");
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::OK_200, res->status);
  4406. }
  4407. TEST_F(ServerTest, SlowPostFail) {
  4408. char buffer[64 * 1024];
  4409. memset(buffer, 0x42, sizeof(buffer));
  4410. cli_.set_write_timeout(std::chrono::seconds(0));
  4411. auto res = cli_.Post(
  4412. "/slowpost", 64 * 1024 * 1024,
  4413. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4414. sink.write(buffer, sizeof(buffer));
  4415. return true;
  4416. },
  4417. "text/plain");
  4418. ASSERT_TRUE(!res);
  4419. EXPECT_EQ(Error::Write, res.error());
  4420. }
  4421. #endif
  4422. TEST_F(ServerTest, Put) {
  4423. auto res = cli_.Put("/put", "PUT", "text/plain");
  4424. ASSERT_TRUE(res);
  4425. EXPECT_EQ(StatusCode::OK_200, res->status);
  4426. EXPECT_EQ("PUT", res->body);
  4427. }
  4428. TEST_F(ServerTest, PutWithContentProvider) {
  4429. auto res = cli_.Put(
  4430. "/put", 3,
  4431. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4432. sink.os << "PUT";
  4433. return true;
  4434. },
  4435. "text/plain");
  4436. ASSERT_TRUE(res);
  4437. EXPECT_EQ(StatusCode::OK_200, res->status);
  4438. EXPECT_EQ("PUT", res->body);
  4439. }
  4440. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4441. auto res = cli_.Post(
  4442. "/post", 42,
  4443. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4444. return false;
  4445. },
  4446. "text/plain");
  4447. ASSERT_TRUE(!res);
  4448. EXPECT_EQ(Error::Canceled, res.error());
  4449. }
  4450. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4451. auto res = cli_.Put(
  4452. "/put",
  4453. [](size_t /*offset*/, DataSink &sink) {
  4454. sink.os << "PUT";
  4455. sink.done();
  4456. return true;
  4457. },
  4458. "text/plain");
  4459. ASSERT_TRUE(res);
  4460. EXPECT_EQ(StatusCode::OK_200, res->status);
  4461. EXPECT_EQ("PUT", res->body);
  4462. }
  4463. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4464. auto res = cli_.Post(
  4465. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4466. "text/plain");
  4467. ASSERT_TRUE(!res);
  4468. EXPECT_EQ(Error::Canceled, res.error());
  4469. }
  4470. TEST_F(ServerTest, PostLoopBack) {
  4471. std::string body;
  4472. auto res = cli_.Post(
  4473. "/post-loopback", 9,
  4474. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4475. EXPECT_EQ(9u, length);
  4476. sink.write("123", 3);
  4477. sink.write("456", 3);
  4478. sink.write("789", 3);
  4479. return true;
  4480. },
  4481. "text/plain",
  4482. [&body](const char *data, size_t data_length) {
  4483. body.append(data, data_length);
  4484. return true;
  4485. });
  4486. ASSERT_TRUE(res);
  4487. EXPECT_EQ(StatusCode::OK_200, res->status);
  4488. EXPECT_EQ("123456789", body);
  4489. }
  4490. TEST_F(ServerTest, PutLoopBack) {
  4491. std::string body;
  4492. auto res = cli_.Put(
  4493. "/put-loopback", 9,
  4494. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4495. EXPECT_EQ(9u, length);
  4496. sink.write("123", 3);
  4497. sink.write("456", 3);
  4498. sink.write("789", 3);
  4499. return true;
  4500. },
  4501. "text/plain",
  4502. [&body](const char *data, size_t data_length) {
  4503. body.append(data, data_length);
  4504. return true;
  4505. });
  4506. ASSERT_TRUE(res);
  4507. EXPECT_EQ(StatusCode::OK_200, res->status);
  4508. EXPECT_EQ("123456789", body);
  4509. }
  4510. TEST_F(ServerTest, PatchLoopBack) {
  4511. std::string body;
  4512. auto res = cli_.Patch(
  4513. "/patch-loopback", 9,
  4514. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4515. EXPECT_EQ(9u, length);
  4516. sink.write("123", 3);
  4517. sink.write("456", 3);
  4518. sink.write("789", 3);
  4519. return true;
  4520. },
  4521. "text/plain",
  4522. [&body](const char *data, size_t data_length) {
  4523. body.append(data, data_length);
  4524. return true;
  4525. });
  4526. ASSERT_TRUE(res);
  4527. EXPECT_EQ(StatusCode::OK_200, res->status);
  4528. EXPECT_EQ("123456789", body);
  4529. }
  4530. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4531. std::string body;
  4532. auto res = cli_.Post(
  4533. "/post-loopback",
  4534. [](size_t /*offset*/, DataSink &sink) {
  4535. sink.write("123", 3);
  4536. sink.write("456", 3);
  4537. sink.write("789", 3);
  4538. sink.done();
  4539. return true;
  4540. },
  4541. "text/plain",
  4542. [&body](const char *data, size_t data_length) {
  4543. body.append(data, data_length);
  4544. return true;
  4545. });
  4546. ASSERT_TRUE(res);
  4547. EXPECT_EQ(StatusCode::OK_200, res->status);
  4548. EXPECT_EQ("123456789", body);
  4549. }
  4550. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4551. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4552. cli_.set_compress(true);
  4553. auto res = cli_.Put(
  4554. "/put", 3,
  4555. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4556. sink.os << "PUT";
  4557. return true;
  4558. },
  4559. "text/plain");
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ("PUT", res->body);
  4563. }
  4564. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4565. cli_.set_compress(true);
  4566. auto res = cli_.Post(
  4567. "/post", 42,
  4568. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4569. return false;
  4570. },
  4571. "text/plain");
  4572. ASSERT_TRUE(!res);
  4573. EXPECT_EQ(Error::Canceled, res.error());
  4574. }
  4575. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4576. cli_.set_compress(true);
  4577. auto res = cli_.Put(
  4578. "/put",
  4579. [](size_t /*offset*/, DataSink &sink) {
  4580. sink.os << "PUT";
  4581. sink.done();
  4582. return true;
  4583. },
  4584. "text/plain");
  4585. ASSERT_TRUE(res);
  4586. EXPECT_EQ(StatusCode::OK_200, res->status);
  4587. EXPECT_EQ("PUT", res->body);
  4588. }
  4589. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4590. cli_.set_compress(true);
  4591. auto res = cli_.Post(
  4592. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4593. "text/plain");
  4594. ASSERT_TRUE(!res);
  4595. EXPECT_EQ(Error::Canceled, res.error());
  4596. }
  4597. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4598. cli_.set_compress(true);
  4599. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. EXPECT_EQ(LARGE_DATA, res->body);
  4603. }
  4604. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4605. #ifdef CPPHTTPLIB_SSL_ENABLED
  4606. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4607. Client cli(s.c_str());
  4608. cli.enable_server_certificate_verification(false);
  4609. #else
  4610. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4611. Client cli(s.c_str());
  4612. #endif
  4613. cli.set_compress(true);
  4614. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4615. ASSERT_TRUE(res);
  4616. EXPECT_EQ(StatusCode::OK_200, res->status);
  4617. EXPECT_EQ(LARGE_DATA, res->body);
  4618. // The compressed size should be less than a 10th of the original. May vary
  4619. // depending on the zlib library.
  4620. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4621. static_cast<uint64_t>(10 * 1024 * 1024));
  4622. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4623. }
  4624. TEST_F(ServerTest, PutContentWithDeflate) {
  4625. cli_.set_compress(false);
  4626. Headers headers;
  4627. headers.emplace("Content-Encoding", "deflate");
  4628. // PUT in deflate format:
  4629. auto res = cli_.Put("/put", headers,
  4630. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4631. ASSERT_TRUE(res);
  4632. EXPECT_EQ(StatusCode::OK_200, res->status);
  4633. EXPECT_EQ("PUT", res->body);
  4634. }
  4635. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4636. Headers headers;
  4637. headers.emplace("Accept-Encoding", "gzip, deflate");
  4638. auto res = cli_.Get("/streamed-chunked", headers);
  4639. ASSERT_TRUE(res);
  4640. EXPECT_EQ(StatusCode::OK_200, res->status);
  4641. EXPECT_EQ(std::string("123456789"), res->body);
  4642. }
  4643. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4644. Headers headers;
  4645. headers.emplace("Accept-Encoding", "gzip, deflate");
  4646. auto res = cli_.Get("/streamed-chunked2", headers);
  4647. ASSERT_TRUE(res);
  4648. EXPECT_EQ(StatusCode::OK_200, res->status);
  4649. EXPECT_EQ(std::string("123456789"), res->body);
  4650. }
  4651. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4652. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4653. ASSERT_TRUE(res);
  4654. EXPECT_EQ(StatusCode::OK_200, res->status);
  4655. }
  4656. TEST(GzipDecompressor, ChunkedDecompression) {
  4657. std::string data;
  4658. for (size_t i = 0; i < 32 * 1024; ++i) {
  4659. data.push_back(static_cast<char>('a' + i % 26));
  4660. }
  4661. std::string compressed_data;
  4662. {
  4663. httplib::detail::gzip_compressor compressor;
  4664. bool result = compressor.compress(
  4665. data.data(), data.size(),
  4666. /*last=*/true,
  4667. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4668. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4669. compressed_data_size);
  4670. return true;
  4671. });
  4672. ASSERT_TRUE(result);
  4673. }
  4674. std::string decompressed_data;
  4675. {
  4676. httplib::detail::gzip_decompressor decompressor;
  4677. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4678. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4679. size_t chunk_size = 130;
  4680. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4681. chunk_begin += chunk_size) {
  4682. size_t current_chunk_size =
  4683. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4684. bool result = decompressor.decompress(
  4685. compressed_data.data() + chunk_begin, current_chunk_size,
  4686. [&](const char *decompressed_data_chunk,
  4687. size_t decompressed_data_chunk_size) {
  4688. decompressed_data.insert(decompressed_data.size(),
  4689. decompressed_data_chunk,
  4690. decompressed_data_chunk_size);
  4691. return true;
  4692. });
  4693. ASSERT_TRUE(result);
  4694. }
  4695. }
  4696. ASSERT_EQ(data, decompressed_data);
  4697. }
  4698. TEST(GzipDecompressor, DeflateDecompression) {
  4699. std::string original_text = "Raw deflate without gzip";
  4700. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4701. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4702. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4703. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4704. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4705. std::string decompressed_data;
  4706. {
  4707. httplib::detail::gzip_decompressor decompressor;
  4708. bool result = decompressor.decompress(
  4709. compressed_data.data(), compressed_data.size(),
  4710. [&](const char *decompressed_data_chunk,
  4711. size_t decompressed_data_chunk_size) {
  4712. decompressed_data.insert(decompressed_data.size(),
  4713. decompressed_data_chunk,
  4714. decompressed_data_chunk_size);
  4715. return true;
  4716. });
  4717. ASSERT_TRUE(result);
  4718. }
  4719. ASSERT_EQ(original_text, decompressed_data);
  4720. }
  4721. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4722. std::string original_text = "Raw deflate without gzip";
  4723. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4724. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4725. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4726. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4727. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4728. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4729. std::string decompressed_data;
  4730. {
  4731. httplib::detail::gzip_decompressor decompressor;
  4732. bool result = decompressor.decompress(
  4733. compressed_data.data(), compressed_data.size(),
  4734. [&](const char *decompressed_data_chunk,
  4735. size_t decompressed_data_chunk_size) {
  4736. decompressed_data.insert(decompressed_data.size(),
  4737. decompressed_data_chunk,
  4738. decompressed_data_chunk_size);
  4739. return true;
  4740. });
  4741. ASSERT_TRUE(result);
  4742. }
  4743. ASSERT_EQ(original_text, decompressed_data);
  4744. }
  4745. #ifdef _WIN32
  4746. TEST(GzipDecompressor, LargeRandomData) {
  4747. // prepare large random data that is difficult to be compressed and is
  4748. // expected to have large size even when compressed
  4749. std::random_device seed_gen;
  4750. std::mt19937 random(seed_gen());
  4751. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4752. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4753. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4754. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4755. // compress data over 4GiB
  4756. std::string compressed_data;
  4757. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4758. httplib::detail::gzip_compressor compressor;
  4759. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4760. data.size() * sizeof(std::uint32_t), true,
  4761. [&](const char *data, size_t size) {
  4762. compressed_data.insert(
  4763. compressed_data.size(), data, size);
  4764. return true;
  4765. });
  4766. ASSERT_TRUE(result);
  4767. // FIXME: compressed data size is expected to be greater than 4GiB,
  4768. // but there is no guarantee
  4769. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4770. // decompress data over 4GiB
  4771. std::string decompressed_data;
  4772. decompressed_data.reserve(data_size);
  4773. httplib::detail::gzip_decompressor decompressor;
  4774. result = decompressor.decompress(
  4775. compressed_data.data(), compressed_data.size(),
  4776. [&](const char *data, size_t size) {
  4777. decompressed_data.insert(decompressed_data.size(), data, size);
  4778. return true;
  4779. });
  4780. ASSERT_TRUE(result);
  4781. // compare
  4782. ASSERT_EQ(data_size, decompressed_data.size());
  4783. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4784. 0);
  4785. }
  4786. #endif
  4787. #endif
  4788. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4789. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4790. Headers headers;
  4791. headers.emplace("Accept-Encoding", "br");
  4792. auto res = cli_.Get("/streamed-chunked", headers);
  4793. ASSERT_TRUE(res);
  4794. EXPECT_EQ(StatusCode::OK_200, res->status);
  4795. EXPECT_EQ(std::string("123456789"), res->body);
  4796. }
  4797. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4798. Headers headers;
  4799. headers.emplace("Accept-Encoding", "br");
  4800. auto res = cli_.Get("/streamed-chunked2", headers);
  4801. ASSERT_TRUE(res);
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. EXPECT_EQ(std::string("123456789"), res->body);
  4804. }
  4805. #endif
  4806. TEST_F(ServerTest, Patch) {
  4807. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. EXPECT_EQ("PATCH", res->body);
  4811. }
  4812. TEST_F(ServerTest, Delete) {
  4813. auto res = cli_.Delete("/delete");
  4814. ASSERT_TRUE(res);
  4815. EXPECT_EQ(StatusCode::OK_200, res->status);
  4816. EXPECT_EQ("DELETE", res->body);
  4817. }
  4818. TEST_F(ServerTest, DeleteContentReceiver) {
  4819. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4820. ASSERT_TRUE(res);
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. EXPECT_EQ("content", res->body);
  4823. }
  4824. TEST_F(ServerTest, Options) {
  4825. auto res = cli_.Options("*");
  4826. ASSERT_TRUE(res);
  4827. EXPECT_EQ(StatusCode::OK_200, res->status);
  4828. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4829. EXPECT_TRUE(res->body.empty());
  4830. }
  4831. TEST_F(ServerTest, URL) {
  4832. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4833. ASSERT_TRUE(res);
  4834. EXPECT_EQ(StatusCode::OK_200, res->status);
  4835. }
  4836. TEST_F(ServerTest, ArrayParam) {
  4837. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. }
  4841. TEST_F(ServerTest, NoMultipleHeaders) {
  4842. Headers headers = {{"Content-Length", "5"}};
  4843. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4844. "text/plain");
  4845. ASSERT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::OK_200, res->status);
  4847. }
  4848. TEST_F(ServerTest, PostContentReceiver) {
  4849. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4850. ASSERT_TRUE(res);
  4851. ASSERT_EQ(StatusCode::OK_200, res->status);
  4852. ASSERT_EQ("content", res->body);
  4853. }
  4854. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4855. UploadFormDataItems items = {
  4856. {"text1", "text default", "", ""},
  4857. {"text2", "aωb", "", ""},
  4858. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4859. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4860. {"file3", "", "", "application/octet-stream"},
  4861. };
  4862. auto res = cli_.Post("/content_receiver", items);
  4863. ASSERT_TRUE(res);
  4864. EXPECT_EQ(StatusCode::OK_200, res->status);
  4865. }
  4866. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4867. UploadFormDataItems items = {
  4868. {"text1", "text default", "", ""},
  4869. {"text2", "aωb", "", ""},
  4870. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4871. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4872. {"file3", "", "", "application/octet-stream"},
  4873. };
  4874. auto boundary = std::string("+++++");
  4875. std::string body;
  4876. for (const auto &item : items) {
  4877. body += "--" + boundary + "\r\n";
  4878. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4879. if (!item.filename.empty()) {
  4880. body += "; filename=\"" + item.filename + "\"";
  4881. }
  4882. body += "\r\n";
  4883. if (!item.content_type.empty()) {
  4884. body += "Content-Type: " + item.content_type + "\r\n";
  4885. }
  4886. body += "\r\n";
  4887. body += item.content + "\r\n";
  4888. }
  4889. body += "--" + boundary + "--\r\n";
  4890. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4891. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4892. ASSERT_TRUE(res);
  4893. EXPECT_EQ(StatusCode::OK_200, res->status);
  4894. }
  4895. TEST_F(ServerTest, PostContentReceiverGzip) {
  4896. cli_.set_compress(true);
  4897. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4898. ASSERT_TRUE(res);
  4899. ASSERT_EQ(StatusCode::OK_200, res->status);
  4900. ASSERT_EQ("content", res->body);
  4901. }
  4902. TEST_F(ServerTest, PutContentReceiver) {
  4903. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4904. ASSERT_TRUE(res);
  4905. ASSERT_EQ(StatusCode::OK_200, res->status);
  4906. ASSERT_EQ("content", res->body);
  4907. }
  4908. TEST_F(ServerTest, PatchContentReceiver) {
  4909. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4910. ASSERT_TRUE(res);
  4911. ASSERT_EQ(StatusCode::OK_200, res->status);
  4912. ASSERT_EQ("content", res->body);
  4913. }
  4914. template <typename ClientType>
  4915. void TestWithHeadersAndContentReceiver(
  4916. ClientType &cli,
  4917. std::function<Result(ClientType &, const std::string &, const Headers &,
  4918. const std::string &, const std::string &,
  4919. ContentReceiver, DownloadProgress)>
  4920. request_func) {
  4921. Headers headers;
  4922. headers.emplace("X-Custom-Header", "test-value");
  4923. std::string received_body;
  4924. auto res = request_func(
  4925. cli, "/content_receiver", headers, "content", "application/json",
  4926. [&](const char *data, size_t data_length) {
  4927. received_body.append(data, data_length);
  4928. return true;
  4929. },
  4930. nullptr);
  4931. ASSERT_TRUE(res);
  4932. EXPECT_EQ(StatusCode::OK_200, res->status);
  4933. EXPECT_EQ("content", received_body);
  4934. }
  4935. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4936. #ifdef CPPHTTPLIB_SSL_ENABLED
  4937. using ClientT = SSLClient;
  4938. #else
  4939. using ClientT = Client;
  4940. #endif
  4941. TestWithHeadersAndContentReceiver<ClientT>(
  4942. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4943. const std::string &body, const std::string &content_type,
  4944. ContentReceiver receiver, DownloadProgress progress) {
  4945. return cli.Post(path, headers, body, content_type, receiver, progress);
  4946. });
  4947. }
  4948. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4949. #ifdef CPPHTTPLIB_SSL_ENABLED
  4950. using ClientT = SSLClient;
  4951. #else
  4952. using ClientT = Client;
  4953. #endif
  4954. TestWithHeadersAndContentReceiver<ClientT>(
  4955. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4956. const std::string &body, const std::string &content_type,
  4957. ContentReceiver receiver, DownloadProgress progress) {
  4958. return cli.Put(path, headers, body, content_type, receiver, progress);
  4959. });
  4960. }
  4961. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4962. #ifdef CPPHTTPLIB_SSL_ENABLED
  4963. using ClientT = SSLClient;
  4964. #else
  4965. using ClientT = Client;
  4966. #endif
  4967. TestWithHeadersAndContentReceiver<ClientT>(
  4968. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4969. const std::string &body, const std::string &content_type,
  4970. ContentReceiver receiver, DownloadProgress progress) {
  4971. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4972. });
  4973. }
  4974. template <typename ClientType>
  4975. void TestWithHeadersAndContentReceiverWithProgress(
  4976. ClientType &cli,
  4977. std::function<Result(ClientType &, const std::string &, const Headers &,
  4978. const std::string &, const std::string &,
  4979. ContentReceiver, DownloadProgress)>
  4980. request_func) {
  4981. Headers headers;
  4982. headers.emplace("X-Test-Header", "progress-test");
  4983. std::string received_body;
  4984. auto progress_called = false;
  4985. auto res = request_func(
  4986. cli, "/content_receiver", headers, "content", "text/plain",
  4987. [&](const char *data, size_t data_length) {
  4988. received_body.append(data, data_length);
  4989. return true;
  4990. },
  4991. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4992. progress_called = true;
  4993. return true;
  4994. });
  4995. ASSERT_TRUE(res);
  4996. EXPECT_EQ(StatusCode::OK_200, res->status);
  4997. EXPECT_EQ("content", received_body);
  4998. EXPECT_TRUE(progress_called);
  4999. }
  5000. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5001. #ifdef CPPHTTPLIB_SSL_ENABLED
  5002. using ClientT = SSLClient;
  5003. #else
  5004. using ClientT = Client;
  5005. #endif
  5006. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5007. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5008. const std::string &body, const std::string &content_type,
  5009. ContentReceiver receiver, DownloadProgress progress) {
  5010. return cli.Post(path, headers, body, content_type, receiver, progress);
  5011. });
  5012. }
  5013. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5014. #ifdef CPPHTTPLIB_SSL_ENABLED
  5015. using ClientT = SSLClient;
  5016. #else
  5017. using ClientT = Client;
  5018. #endif
  5019. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5020. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5021. const std::string &body, const std::string &content_type,
  5022. ContentReceiver receiver, DownloadProgress progress) {
  5023. return cli.Put(path, headers, body, content_type, receiver, progress);
  5024. });
  5025. }
  5026. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5027. #ifdef CPPHTTPLIB_SSL_ENABLED
  5028. using ClientT = SSLClient;
  5029. #else
  5030. using ClientT = Client;
  5031. #endif
  5032. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5033. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5034. const std::string &body, const std::string &content_type,
  5035. ContentReceiver receiver, DownloadProgress progress) {
  5036. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5037. });
  5038. }
  5039. template <typename ClientType>
  5040. void TestWithHeadersAndContentReceiverError(
  5041. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5042. const Headers &, const std::string &,
  5043. const std::string &, ContentReceiver)>
  5044. request_func) {
  5045. Headers headers;
  5046. headers.emplace("X-Error-Test", "true");
  5047. std::string received_body;
  5048. auto receiver_failed = false;
  5049. auto res =
  5050. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5051. [&](const char *data, size_t data_length) {
  5052. received_body.append(data, data_length);
  5053. receiver_failed = true;
  5054. return false;
  5055. });
  5056. ASSERT_FALSE(res);
  5057. EXPECT_TRUE(receiver_failed);
  5058. }
  5059. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5060. #ifdef CPPHTTPLIB_SSL_ENABLED
  5061. using ClientT = SSLClient;
  5062. #else
  5063. using ClientT = Client;
  5064. #endif
  5065. TestWithHeadersAndContentReceiverError<ClientT>(
  5066. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5067. const std::string &body, const std::string &content_type,
  5068. ContentReceiver receiver) {
  5069. return cli.Post(path, headers, body, content_type, receiver);
  5070. });
  5071. }
  5072. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5073. #ifdef CPPHTTPLIB_SSL_ENABLED
  5074. using ClientT = SSLClient;
  5075. #else
  5076. using ClientT = Client;
  5077. #endif
  5078. TestWithHeadersAndContentReceiverError<ClientT>(
  5079. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5080. const std::string &body, const std::string &content_type,
  5081. ContentReceiver receiver) {
  5082. return cli.Put(path, headers, body, content_type, receiver);
  5083. });
  5084. }
  5085. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5086. #ifdef CPPHTTPLIB_SSL_ENABLED
  5087. using ClientT = SSLClient;
  5088. #else
  5089. using ClientT = Client;
  5090. #endif
  5091. TestWithHeadersAndContentReceiverError<ClientT>(
  5092. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5093. const std::string &body, const std::string &content_type,
  5094. ContentReceiver receiver) {
  5095. return cli.Patch(path, headers, body, content_type, receiver);
  5096. });
  5097. }
  5098. TEST_F(ServerTest, PostQueryStringAndBody) {
  5099. auto res =
  5100. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5101. ASSERT_TRUE(res);
  5102. ASSERT_EQ(StatusCode::OK_200, res->status);
  5103. }
  5104. TEST_F(ServerTest, HTTP2Magic) {
  5105. Request req;
  5106. req.method = "PRI";
  5107. req.path = "*";
  5108. req.body = "SM";
  5109. auto res = std::make_shared<Response>();
  5110. auto error = Error::Success;
  5111. auto ret = cli_.send(req, *res, error);
  5112. ASSERT_TRUE(ret);
  5113. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5114. }
  5115. TEST_F(ServerTest, KeepAlive) {
  5116. auto res = cli_.Get("/hi");
  5117. ASSERT_TRUE(res);
  5118. EXPECT_EQ(StatusCode::OK_200, res->status);
  5119. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5120. EXPECT_EQ("Hello World!", res->body);
  5121. res = cli_.Get("/hi");
  5122. ASSERT_TRUE(res);
  5123. EXPECT_EQ(StatusCode::OK_200, res->status);
  5124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5125. EXPECT_EQ("Hello World!", res->body);
  5126. res = cli_.Get("/hi");
  5127. ASSERT_TRUE(res);
  5128. EXPECT_EQ(StatusCode::OK_200, res->status);
  5129. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5130. EXPECT_EQ("Hello World!", res->body);
  5131. res = cli_.Get("/not-exist");
  5132. ASSERT_TRUE(res);
  5133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5134. res = cli_.Post("/empty", "", "text/plain");
  5135. ASSERT_TRUE(res);
  5136. EXPECT_EQ(StatusCode::OK_200, res->status);
  5137. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5138. EXPECT_EQ("empty", res->body);
  5139. EXPECT_EQ("close", res->get_header_value("Connection"));
  5140. res = cli_.Post(
  5141. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5142. "text/plain");
  5143. ASSERT_TRUE(res);
  5144. EXPECT_EQ(StatusCode::OK_200, res->status);
  5145. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5146. EXPECT_EQ("empty", res->body);
  5147. cli_.set_keep_alive(false);
  5148. res = cli_.Get("/last-request");
  5149. ASSERT_TRUE(res);
  5150. EXPECT_EQ(StatusCode::OK_200, res->status);
  5151. EXPECT_EQ("close", res->get_header_value("Connection"));
  5152. }
  5153. TEST_F(ServerTest, TooManyRedirect) {
  5154. cli_.set_follow_location(true);
  5155. auto res = cli_.Get("/redirect/0");
  5156. ASSERT_TRUE(!res);
  5157. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5158. }
  5159. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5160. Request req;
  5161. req.method = "FOOBAR";
  5162. req.path = "/hi";
  5163. cli_.set_keep_alive(true);
  5164. auto res = cli_.send(req);
  5165. ASSERT_TRUE(res);
  5166. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5167. EXPECT_EQ("close", res->get_header_value("Connection"));
  5168. EXPECT_FALSE(cli_.is_socket_open());
  5169. }
  5170. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5171. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5172. TEST_F(ServerTest, Gzip) {
  5173. Headers headers;
  5174. headers.emplace("Accept-Encoding", "gzip, deflate");
  5175. auto res = cli_.Get("/compress", headers);
  5176. ASSERT_TRUE(res);
  5177. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5179. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5180. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5181. "7890123456789012345678901234567890",
  5182. res->body);
  5183. EXPECT_EQ(StatusCode::OK_200, res->status);
  5184. }
  5185. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5186. Headers headers;
  5187. headers.emplace("Accept-Encoding", "");
  5188. auto res = cli_.Get("/compress", headers);
  5189. ASSERT_TRUE(res);
  5190. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5191. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5192. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5193. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5194. "7890123456789012345678901234567890",
  5195. res->body);
  5196. EXPECT_EQ(StatusCode::OK_200, res->status);
  5197. }
  5198. TEST_F(ServerTest, GzipWithContentReceiver) {
  5199. Headers headers;
  5200. headers.emplace("Accept-Encoding", "gzip, deflate");
  5201. std::string body;
  5202. auto res = cli_.Get("/compress", headers,
  5203. [&](const char *data, uint64_t data_length) {
  5204. EXPECT_EQ(100U, data_length);
  5205. body.append(data, data_length);
  5206. return true;
  5207. });
  5208. ASSERT_TRUE(res);
  5209. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5211. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5212. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5213. "7890123456789012345678901234567890",
  5214. body);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. }
  5217. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5218. Headers headers;
  5219. headers.emplace("Accept-Encoding", "gzip, deflate");
  5220. cli_.set_decompress(false);
  5221. auto res = cli_.Get("/compress", headers);
  5222. ASSERT_TRUE(res);
  5223. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5225. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5226. EXPECT_EQ(33U, res->body.size());
  5227. EXPECT_EQ(StatusCode::OK_200, res->status);
  5228. }
  5229. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5230. Headers headers;
  5231. headers.emplace("Accept-Encoding", "");
  5232. std::string body;
  5233. auto res = cli_.Get("/compress", headers,
  5234. [&](const char *data, uint64_t data_length) {
  5235. EXPECT_EQ(100U, data_length);
  5236. body.append(data, data_length);
  5237. return true;
  5238. });
  5239. ASSERT_TRUE(res);
  5240. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5241. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5242. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5243. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5244. "7890123456789012345678901234567890",
  5245. body);
  5246. EXPECT_EQ(StatusCode::OK_200, res->status);
  5247. }
  5248. TEST_F(ServerTest, NoGzip) {
  5249. Headers headers;
  5250. headers.emplace("Accept-Encoding", "gzip, deflate");
  5251. auto res = cli_.Get("/nocompress", headers);
  5252. ASSERT_TRUE(res);
  5253. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5254. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5255. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5256. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5257. "7890123456789012345678901234567890",
  5258. res->body);
  5259. EXPECT_EQ(StatusCode::OK_200, res->status);
  5260. }
  5261. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5262. Headers headers;
  5263. headers.emplace("Accept-Encoding", "gzip, deflate");
  5264. std::string body;
  5265. auto res = cli_.Get("/nocompress", headers,
  5266. [&](const char *data, uint64_t data_length) {
  5267. EXPECT_EQ(100U, data_length);
  5268. body.append(data, data_length);
  5269. return true;
  5270. });
  5271. ASSERT_TRUE(res);
  5272. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5273. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5274. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5275. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5276. "7890123456789012345678901234567890",
  5277. body);
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. }
  5280. TEST_F(ServerTest, MultipartFormDataGzip) {
  5281. UploadFormDataItems items = {
  5282. {"key1", "test", "", ""},
  5283. {"key2", "--abcdefg123", "", ""},
  5284. };
  5285. cli_.set_compress(true);
  5286. auto res = cli_.Post("/compress-multipart", items);
  5287. ASSERT_TRUE(res);
  5288. EXPECT_EQ(StatusCode::OK_200, res->status);
  5289. }
  5290. #endif
  5291. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5292. TEST_F(ServerTest, Brotli) {
  5293. Headers headers;
  5294. headers.emplace("Accept-Encoding", "br");
  5295. auto res = cli_.Get("/compress", headers);
  5296. ASSERT_TRUE(res);
  5297. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5298. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5299. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5300. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5301. "7890123456789012345678901234567890",
  5302. res->body);
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. }
  5305. #endif
  5306. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5307. TEST_F(ServerTest, Zstd) {
  5308. Headers headers;
  5309. headers.emplace("Accept-Encoding", "zstd");
  5310. auto res = cli_.Get("/compress", headers);
  5311. ASSERT_TRUE(res);
  5312. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5313. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5314. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5315. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5316. "7890123456789012345678901234567890",
  5317. res->body);
  5318. EXPECT_EQ(StatusCode::OK_200, res->status);
  5319. }
  5320. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5321. Headers headers;
  5322. headers.emplace("Accept-Encoding", "");
  5323. auto res = cli_.Get("/compress", headers);
  5324. ASSERT_TRUE(res);
  5325. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5326. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5327. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5328. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5329. "7890123456789012345678901234567890",
  5330. res->body);
  5331. EXPECT_EQ(StatusCode::OK_200, res->status);
  5332. }
  5333. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5334. Headers headers;
  5335. headers.emplace("Accept-Encoding", "zstd");
  5336. std::string body;
  5337. auto res = cli_.Get("/compress", headers,
  5338. [&](const char *data, uint64_t data_length) {
  5339. EXPECT_EQ(100U, data_length);
  5340. body.append(data, data_length);
  5341. return true;
  5342. });
  5343. ASSERT_TRUE(res);
  5344. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5346. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5347. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5348. "7890123456789012345678901234567890",
  5349. body);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. }
  5352. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5353. Headers headers;
  5354. headers.emplace("Accept-Encoding", "zstd");
  5355. cli_.set_decompress(false);
  5356. auto res = cli_.Get("/compress", headers);
  5357. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5358. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5359. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5360. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5361. ASSERT_TRUE(res);
  5362. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5363. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5364. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5365. EXPECT_EQ(StatusCode::OK_200, res->status);
  5366. ASSERT_EQ(26U, res->body.size());
  5367. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5368. 0);
  5369. }
  5370. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5371. Headers headers;
  5372. headers.emplace("Accept-Encoding", "");
  5373. std::string body;
  5374. auto res = cli_.Get("/compress", headers,
  5375. [&](const char *data, uint64_t data_length) {
  5376. EXPECT_EQ(100U, data_length);
  5377. body.append(data, data_length);
  5378. return true;
  5379. });
  5380. ASSERT_TRUE(res);
  5381. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5382. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5383. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5384. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5385. "7890123456789012345678901234567890",
  5386. body);
  5387. EXPECT_EQ(StatusCode::OK_200, res->status);
  5388. }
  5389. TEST_F(ServerTest, NoZstd) {
  5390. Headers headers;
  5391. headers.emplace("Accept-Encoding", "zstd");
  5392. auto res = cli_.Get("/nocompress", headers);
  5393. ASSERT_TRUE(res);
  5394. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5395. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5396. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5397. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5398. "7890123456789012345678901234567890",
  5399. res->body);
  5400. EXPECT_EQ(StatusCode::OK_200, res->status);
  5401. }
  5402. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5403. Headers headers;
  5404. headers.emplace("Accept-Encoding", "zstd");
  5405. std::string body;
  5406. auto res = cli_.Get("/nocompress", headers,
  5407. [&](const char *data, uint64_t data_length) {
  5408. EXPECT_EQ(100U, data_length);
  5409. body.append(data, data_length);
  5410. return true;
  5411. });
  5412. ASSERT_TRUE(res);
  5413. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5414. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5415. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5416. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5417. "7890123456789012345678901234567890",
  5418. body);
  5419. EXPECT_EQ(StatusCode::OK_200, res->status);
  5420. }
  5421. // TODO: How to enable zstd ??
  5422. TEST_F(ServerTest, MultipartFormDataZstd) {
  5423. UploadFormDataItems items = {
  5424. {"key1", "test", "", ""},
  5425. {"key2", "--abcdefg123", "", ""},
  5426. };
  5427. Headers headers;
  5428. headers.emplace("Accept-Encoding", "zstd");
  5429. cli_.set_compress(true);
  5430. auto res = cli_.Post("/compress-multipart", headers, items);
  5431. ASSERT_TRUE(res);
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. }
  5434. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5435. Headers headers;
  5436. headers.emplace("Accept-Encoding", "zstd");
  5437. cli_.set_compress(true);
  5438. auto res = cli_.Put(
  5439. "/put", headers, 3,
  5440. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5441. sink.os << "PUT";
  5442. return true;
  5443. },
  5444. "text/plain");
  5445. ASSERT_TRUE(res);
  5446. EXPECT_EQ(StatusCode::OK_200, res->status);
  5447. EXPECT_EQ("PUT", res->body);
  5448. }
  5449. // Pre-compression logging tests
  5450. TEST_F(ServerTest, PreCompressionLogging) {
  5451. // Test data for compression (matches the actual /compress endpoint content)
  5452. const std::string test_content =
  5453. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5454. "3456789012345678901234567890";
  5455. // Variables to capture logging data
  5456. std::string pre_compression_body;
  5457. std::string pre_compression_content_type;
  5458. std::string pre_compression_content_encoding;
  5459. std::string post_compression_body;
  5460. std::string post_compression_content_type;
  5461. std::string post_compression_content_encoding;
  5462. // Set up pre-compression logger
  5463. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5464. const Response &res) {
  5465. pre_compression_body = res.body;
  5466. pre_compression_content_type = res.get_header_value("Content-Type");
  5467. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5468. });
  5469. // Set up post-compression logger
  5470. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5471. post_compression_body = res.body;
  5472. post_compression_content_type = res.get_header_value("Content-Type");
  5473. post_compression_content_encoding =
  5474. res.get_header_value("Content-Encoding");
  5475. });
  5476. // Test with gzip compression
  5477. Headers headers;
  5478. headers.emplace("Accept-Encoding", "gzip");
  5479. auto res = cli_.Get("/compress", headers);
  5480. // Verify response was compressed
  5481. ASSERT_TRUE(res);
  5482. EXPECT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5484. // Verify pre-compression logger captured uncompressed content
  5485. EXPECT_EQ(test_content, pre_compression_body);
  5486. EXPECT_EQ("text/plain", pre_compression_content_type);
  5487. EXPECT_TRUE(pre_compression_content_encoding
  5488. .empty()); // No encoding header before compression
  5489. // Verify post-compression logger captured compressed content
  5490. EXPECT_NE(test_content,
  5491. post_compression_body); // Should be different after compression
  5492. EXPECT_EQ("text/plain", post_compression_content_type);
  5493. EXPECT_EQ("gzip", post_compression_content_encoding);
  5494. // Verify compressed content is smaller
  5495. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5496. }
  5497. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5498. const std::string test_content =
  5499. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5500. "3456789012345678901234567890";
  5501. std::string pre_compression_body;
  5502. std::string post_compression_body;
  5503. svr_.set_pre_compression_logger(
  5504. [&](const Request & /*req*/, const Response &res) {
  5505. pre_compression_body = res.body;
  5506. });
  5507. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5508. post_compression_body = res.body;
  5509. });
  5510. Headers headers;
  5511. headers.emplace("Accept-Encoding", "br");
  5512. auto res = cli_.Get("/compress", headers);
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5516. // Verify pre-compression content is uncompressed
  5517. EXPECT_EQ(test_content, pre_compression_body);
  5518. // Verify post-compression content is compressed
  5519. EXPECT_NE(test_content, post_compression_body);
  5520. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5521. }
  5522. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5523. const std::string test_content =
  5524. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5525. "3456789012345678901234567890";
  5526. std::string pre_compression_body;
  5527. std::string post_compression_body;
  5528. svr_.set_pre_compression_logger(
  5529. [&](const Request & /*req*/, const Response &res) {
  5530. pre_compression_body = res.body;
  5531. });
  5532. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5533. post_compression_body = res.body;
  5534. });
  5535. // Request without compression (use /nocompress endpoint)
  5536. Headers headers;
  5537. auto res = cli_.Get("/nocompress", headers);
  5538. ASSERT_TRUE(res);
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5541. // Pre-compression logger should not be called when no compression is applied
  5542. EXPECT_TRUE(
  5543. pre_compression_body.empty()); // Pre-compression logger not called
  5544. EXPECT_EQ(
  5545. test_content,
  5546. post_compression_body); // Post-compression logger captures final content
  5547. }
  5548. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5549. const std::string test_content =
  5550. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5551. "3456789012345678901234567890";
  5552. std::string pre_compression_body;
  5553. bool pre_logger_called = false;
  5554. // Set only pre-compression logger
  5555. svr_.set_pre_compression_logger(
  5556. [&](const Request & /*req*/, const Response &res) {
  5557. pre_compression_body = res.body;
  5558. pre_logger_called = true;
  5559. });
  5560. Headers headers;
  5561. headers.emplace("Accept-Encoding", "gzip");
  5562. auto res = cli_.Get("/compress", headers);
  5563. ASSERT_TRUE(res);
  5564. EXPECT_EQ(StatusCode::OK_200, res->status);
  5565. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5566. // Verify pre-compression logger was called
  5567. EXPECT_TRUE(pre_logger_called);
  5568. EXPECT_EQ(test_content, pre_compression_body);
  5569. }
  5570. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5571. {
  5572. // Test with Expect: 100-continue header - success case
  5573. // Server returns 100 Continue, client sends body, server returns 200 OK
  5574. Request req;
  5575. req.method = "POST";
  5576. req.path = "/post-large";
  5577. req.set_header("Expect", "100-continue");
  5578. req.body = LARGE_DATA;
  5579. Response res;
  5580. auto error = Error::Success;
  5581. cli_.set_keep_alive(true);
  5582. auto ret = cli_.send(req, res, error);
  5583. EXPECT_TRUE(ret);
  5584. EXPECT_EQ(StatusCode::OK_200, res.status);
  5585. EXPECT_EQ(LARGE_DATA, res.body);
  5586. }
  5587. {
  5588. // Test with Expect: 100-continue header - error case
  5589. // Client should not send the body when server returns an error
  5590. Request req;
  5591. req.method = "POST";
  5592. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5593. req.set_header("Expect", "100-continue");
  5594. req.body = LARGE_DATA;
  5595. Response res;
  5596. auto error = Error::Success;
  5597. auto start = std::chrono::high_resolution_clock::now();
  5598. cli_.set_keep_alive(true);
  5599. auto ret = cli_.send(req, res, error);
  5600. auto end = std::chrono::high_resolution_clock::now();
  5601. auto elapsed =
  5602. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5603. .count();
  5604. // With Expect: 100-continue, request completes successfully but with error
  5605. EXPECT_TRUE(ret);
  5606. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5607. EXPECT_EQ("close", res.get_header_value("Connection"));
  5608. EXPECT_FALSE(cli_.is_socket_open());
  5609. EXPECT_LE(elapsed, 200);
  5610. }
  5611. {
  5612. // Send an extra GET request to ensure error recovery without hanging
  5613. Request req;
  5614. req.method = "GET";
  5615. req.path = "/hi";
  5616. auto start = std::chrono::high_resolution_clock::now();
  5617. auto res = cli_.send(req);
  5618. auto end = std::chrono::high_resolution_clock::now();
  5619. auto elapsed =
  5620. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5621. .count();
  5622. ASSERT_TRUE(res);
  5623. EXPECT_EQ(StatusCode::OK_200, res->status);
  5624. EXPECT_EQ("Hello World!", res->body);
  5625. EXPECT_LE(elapsed, 500);
  5626. }
  5627. }
  5628. TEST(ZstdDecompressor, ChunkedDecompression) {
  5629. std::string data;
  5630. for (size_t i = 0; i < 32 * 1024; ++i) {
  5631. data.push_back(static_cast<char>('a' + i % 26));
  5632. }
  5633. std::string compressed_data;
  5634. {
  5635. httplib::detail::zstd_compressor compressor;
  5636. bool result = compressor.compress(
  5637. data.data(), data.size(),
  5638. /*last=*/true,
  5639. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5640. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5641. compressed_data_size);
  5642. return true;
  5643. });
  5644. ASSERT_TRUE(result);
  5645. }
  5646. std::string decompressed_data;
  5647. {
  5648. httplib::detail::zstd_decompressor decompressor;
  5649. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5650. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5651. size_t chunk_size = 130;
  5652. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5653. chunk_begin += chunk_size) {
  5654. size_t current_chunk_size =
  5655. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5656. bool result = decompressor.decompress(
  5657. compressed_data.data() + chunk_begin, current_chunk_size,
  5658. [&](const char *decompressed_data_chunk,
  5659. size_t decompressed_data_chunk_size) {
  5660. decompressed_data.insert(decompressed_data.size(),
  5661. decompressed_data_chunk,
  5662. decompressed_data_chunk_size);
  5663. return true;
  5664. });
  5665. ASSERT_TRUE(result);
  5666. }
  5667. }
  5668. ASSERT_EQ(data, decompressed_data);
  5669. }
  5670. TEST(ZstdDecompressor, Decompress) {
  5671. std::string original_text = "Compressed with ZSTD";
  5672. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5673. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5674. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5675. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5676. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5677. std::string decompressed_data;
  5678. {
  5679. httplib::detail::zstd_decompressor decompressor;
  5680. bool result = decompressor.decompress(
  5681. compressed_data.data(), compressed_data.size(),
  5682. [&](const char *decompressed_data_chunk,
  5683. size_t decompressed_data_chunk_size) {
  5684. decompressed_data.insert(decompressed_data.size(),
  5685. decompressed_data_chunk,
  5686. decompressed_data_chunk_size);
  5687. return true;
  5688. });
  5689. ASSERT_TRUE(result);
  5690. }
  5691. ASSERT_EQ(original_text, decompressed_data);
  5692. }
  5693. #endif
  5694. // Sends a raw request to a server listening at HOST:PORT.
  5695. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5696. std::string *resp = nullptr) {
  5697. auto error = Error::Success;
  5698. auto client_sock = detail::create_client_socket(
  5699. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5700. /*connection_timeout_sec=*/5, 0,
  5701. /*read_timeout_sec=*/5, 0,
  5702. /*write_timeout_sec=*/5, 0, std::string(), error);
  5703. if (client_sock == INVALID_SOCKET) { return false; }
  5704. auto ret = detail::process_client_socket(
  5705. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5706. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5707. if (req.size() !=
  5708. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5709. return false;
  5710. }
  5711. char buf[512];
  5712. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5713. while (line_reader.getline()) {
  5714. if (resp) { *resp += line_reader.ptr(); }
  5715. }
  5716. return true;
  5717. });
  5718. detail::close_socket(client_sock);
  5719. return ret;
  5720. }
  5721. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5722. Server svr;
  5723. std::string header_value;
  5724. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5725. header_value = req.get_header_value("foo");
  5726. res.set_content("ok", "text/plain");
  5727. });
  5728. thread t = thread([&] { svr.listen(HOST, PORT); });
  5729. auto se = detail::scope_exit([&] {
  5730. svr.stop();
  5731. t.join();
  5732. ASSERT_FALSE(svr.is_running());
  5733. });
  5734. svr.wait_until_ready();
  5735. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5736. // like characters are not treated the same - use vertical tab and escape.
  5737. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5738. "foo: \t \v bar \x1B\t \r\n"
  5739. "Connection: close\r\n"
  5740. "\r\n";
  5741. std::string res;
  5742. ASSERT_TRUE(send_request(5, req, &res));
  5743. EXPECT_EQ(header_value, "");
  5744. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5745. }
  5746. // Sends a raw request and verifies that there isn't a crash or exception.
  5747. static void test_raw_request(const std::string &req,
  5748. std::string *out = nullptr) {
  5749. Server svr;
  5750. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5751. res.set_content("ok", "text/plain");
  5752. });
  5753. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5754. res.set_content("ok", "text/plain");
  5755. });
  5756. svr.Get("/header_field_value_check",
  5757. [&](const Request & /*req*/, Response &res) {
  5758. res.set_content("ok", "text/plain");
  5759. });
  5760. // Server read timeout must be longer than the client read timeout for the
  5761. // bug to reproduce, probably to force the server to process a request
  5762. // without a trailing blank line.
  5763. const time_t client_read_timeout_sec = 1;
  5764. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5765. bool listen_thread_ok = false;
  5766. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5767. auto se = detail::scope_exit([&] {
  5768. svr.stop();
  5769. t.join();
  5770. ASSERT_FALSE(svr.is_running());
  5771. EXPECT_TRUE(listen_thread_ok);
  5772. });
  5773. svr.wait_until_ready();
  5774. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5775. }
  5776. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5777. // A certain header line causes an exception if the header property is parsed
  5778. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5779. test_raw_request(
  5780. "GET /hi HTTP/1.1\r\n"
  5781. " : "
  5782. " "
  5783. " ");
  5784. }
  5785. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5786. // A certain header line causes an exception if the header property *name* is
  5787. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5788. // greedy matcher and requires backtracking when there are a lot of ":"
  5789. // characters.
  5790. // This occurs with libc++ but not libstdc++.
  5791. test_raw_request(
  5792. "GET /hi HTTP/1.1\r\n"
  5793. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5794. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5795. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5796. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5797. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5798. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5799. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5800. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5801. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5802. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5803. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5804. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5805. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5806. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5807. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5808. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5809. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5810. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5811. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5812. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5813. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5814. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5815. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5816. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5817. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5818. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5819. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5820. "&&&%%%");
  5821. }
  5822. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5823. // Make sure this doesn't crash the server.
  5824. // In a previous version of the header line regex, the "\r" rendered the line
  5825. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5826. // a new position where the leading white space ended and the field value
  5827. // began.
  5828. // The crash occurs with libc++ but not libstdc++.
  5829. test_raw_request("GET /hi HTTP/1.1\r\n"
  5830. "a:" +
  5831. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5832. "\r\n"
  5833. "\r\n");
  5834. }
  5835. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5836. std::string out;
  5837. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5838. "Content-Type: text/plain\r\n"
  5839. "Transfer-Encoding: chunked\r\n"
  5840. "\r\n"
  5841. "nothex\r\n",
  5842. &out);
  5843. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5844. }
  5845. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5846. std::string out;
  5847. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5848. "Content-Type: text/plain\r\n"
  5849. "Transfer-Encoding: chunked\r\n"
  5850. "\r\n"
  5851. "3\r\n"
  5852. "xyz\r\n"
  5853. "NaN\r\n",
  5854. &out);
  5855. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5856. }
  5857. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5858. std::string out;
  5859. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5860. "Content-Type: text/plain\r\n"
  5861. "Transfer-Encoding: chunked\r\n"
  5862. "\r\n"
  5863. // Length is too large for 64 bits.
  5864. "1ffffffffffffffff\r\n"
  5865. "xyz\r\n",
  5866. &out);
  5867. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5868. }
  5869. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5870. test_raw_request("GET /hi HTTP/1.1\r\n"
  5871. "Content-Type: text/plain\r\n\r");
  5872. }
  5873. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5874. std::string out;
  5875. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5876. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5877. }
  5878. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5879. Server svr;
  5880. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5881. EXPECT_TRUE(!req.remote_addr.empty());
  5882. });
  5883. thread t = thread([&] { svr.listen(HOST, PORT); });
  5884. auto se = detail::scope_exit([&] {
  5885. svr.stop();
  5886. t.join();
  5887. ASSERT_FALSE(svr.is_running());
  5888. });
  5889. svr.wait_until_ready();
  5890. // Send an invalid request line to trigger Bad Request
  5891. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5892. std::string out;
  5893. ASSERT_TRUE(send_request(5, bad_req, &out));
  5894. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5895. }
  5896. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5897. std::string out;
  5898. std::string request(
  5899. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5900. test_raw_request(request, &out);
  5901. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5902. }
  5903. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5904. std::string out;
  5905. std::string request(
  5906. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5907. test_raw_request(request, &out);
  5908. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5909. }
  5910. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5911. std::string out;
  5912. std::string request(
  5913. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5914. test_raw_request(request, &out);
  5915. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5916. }
  5917. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5918. std::string out;
  5919. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5920. "Test: \r\n\r\n",
  5921. &out);
  5922. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5923. }
  5924. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5925. Server svr;
  5926. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5927. res.set_header("Cache-Control", "no-cache");
  5928. res.set_chunked_content_provider(
  5929. "text/event-stream", [](size_t offset, DataSink &sink) {
  5930. std::string s = "data:";
  5931. s += std::to_string(offset);
  5932. s += "\n\n";
  5933. auto ret = sink.write(s.data(), s.size());
  5934. EXPECT_TRUE(ret);
  5935. std::this_thread::sleep_for(std::chrono::seconds(1));
  5936. return true;
  5937. });
  5938. });
  5939. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5940. svr.wait_until_ready();
  5941. Client client(HOST, PORT);
  5942. const Headers headers = {{"Accept", "text/event-stream"}};
  5943. auto get_thread = std::thread([&client, &headers]() {
  5944. auto res = client.Get(
  5945. "/events", headers,
  5946. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5947. });
  5948. auto se = detail::scope_exit([&] {
  5949. svr.stop();
  5950. get_thread.join();
  5951. listen_thread.join();
  5952. ASSERT_FALSE(svr.is_running());
  5953. });
  5954. // Give GET time to get a few messages.
  5955. std::this_thread::sleep_for(std::chrono::seconds(2));
  5956. }
  5957. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5958. httplib::Server svr;
  5959. svr.Post("/hi",
  5960. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5961. res.status = StatusCode::OK_200;
  5962. });
  5963. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5964. svr.wait_until_ready();
  5965. Client cli(HOST, PORT);
  5966. auto res = cli.Post("/hi", "data", "text/plain");
  5967. ASSERT_TRUE(res);
  5968. EXPECT_EQ(StatusCode::OK_200, res->status);
  5969. svr.stop();
  5970. thread.join();
  5971. ASSERT_FALSE(svr.is_running());
  5972. res = cli.Post("/hi", "data", "text/plain");
  5973. ASSERT_FALSE(res);
  5974. }
  5975. TEST(ServerStopTest, ListenFailure) {
  5976. Server svr;
  5977. auto t = thread([&]() {
  5978. auto ret = svr.listen("????", PORT);
  5979. EXPECT_FALSE(ret);
  5980. });
  5981. svr.wait_until_ready();
  5982. svr.stop();
  5983. t.join();
  5984. }
  5985. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5986. TEST(ServerStopTest, Decommision) {
  5987. Server svr;
  5988. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5989. for (int i = 0; i < 4; i++) {
  5990. auto is_even = !(i % 2);
  5991. std::thread t{[&] {
  5992. try {
  5993. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5994. if (is_even) {
  5995. throw std::runtime_error("Some thing that happens to go wrong.");
  5996. }
  5997. svr.listen(HOST, PORT);
  5998. } catch (...) { svr.decommission(); }
  5999. }};
  6000. svr.wait_until_ready();
  6001. // Server is up
  6002. {
  6003. Client cli(HOST, PORT);
  6004. auto res = cli.Get("/hi");
  6005. if (is_even) {
  6006. EXPECT_FALSE(res);
  6007. } else {
  6008. EXPECT_TRUE(res);
  6009. EXPECT_EQ("hi...", res->body);
  6010. }
  6011. }
  6012. svr.stop();
  6013. t.join();
  6014. // Server is down...
  6015. {
  6016. Client cli(HOST, PORT);
  6017. auto res = cli.Get("/hi");
  6018. EXPECT_FALSE(res);
  6019. }
  6020. }
  6021. }
  6022. #endif
  6023. // Helper function for string body upload progress tests
  6024. template <typename SetupHandler, typename ClientCall>
  6025. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6026. ClientCall &&client_call,
  6027. const string &body) {
  6028. Server svr;
  6029. setup_handler(svr);
  6030. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6031. auto se = detail::scope_exit([&] {
  6032. svr.stop();
  6033. t.join();
  6034. });
  6035. svr.wait_until_ready();
  6036. Client cli(HOST, PORT);
  6037. vector<uint64_t> progress_values;
  6038. bool progress_called = false;
  6039. auto res =
  6040. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6041. progress_values.push_back(current);
  6042. progress_called = true;
  6043. return true;
  6044. });
  6045. ASSERT_TRUE(res);
  6046. EXPECT_EQ(200, res->status);
  6047. EXPECT_TRUE(progress_called);
  6048. }
  6049. TEST(UploadProgressTest, PostStringBodyBasic) {
  6050. TestStringBodyUploadProgress(
  6051. [](Server &svr) {
  6052. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6053. res.set_content("received", "text/plain");
  6054. });
  6055. },
  6056. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6057. return cli.Post("/test", body, "text/plain", progress_callback);
  6058. },
  6059. "test data for upload progress");
  6060. }
  6061. TEST(UploadProgressTest, PutStringBodyBasic) {
  6062. TestStringBodyUploadProgress(
  6063. [](Server &svr) {
  6064. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6065. res.set_content("put received", "text/plain");
  6066. });
  6067. },
  6068. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6069. return cli.Put("/test", body, "text/plain", progress_callback);
  6070. },
  6071. "put test data for upload progress");
  6072. }
  6073. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6074. TestStringBodyUploadProgress(
  6075. [](Server &svr) {
  6076. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6077. res.set_content("patch received", "text/plain");
  6078. });
  6079. },
  6080. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6081. return cli.Patch("/test", body, "text/plain", progress_callback);
  6082. },
  6083. "patch test data for upload progress");
  6084. }
  6085. // Helper function for content provider upload progress tests
  6086. template <typename SetupHandler, typename ClientCall>
  6087. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6088. ClientCall &&client_call) {
  6089. Server svr;
  6090. setup_handler(svr);
  6091. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6092. auto se = detail::scope_exit([&] {
  6093. svr.stop();
  6094. t.join();
  6095. });
  6096. svr.wait_until_ready();
  6097. Client cli(HOST, PORT);
  6098. vector<uint64_t> progress_values;
  6099. auto res =
  6100. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6101. progress_values.push_back(current);
  6102. return true;
  6103. });
  6104. ASSERT_TRUE(res);
  6105. EXPECT_EQ(200, res->status);
  6106. EXPECT_FALSE(progress_values.empty());
  6107. }
  6108. TEST(UploadProgressTest, PostContentProviderProgress) {
  6109. TestContentProviderUploadProgress(
  6110. [](Server &svr) {
  6111. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6112. res.set_content("provider received", "text/plain");
  6113. });
  6114. },
  6115. [](Client &cli, UploadProgress progress_callback) {
  6116. return cli.Post(
  6117. "/test", 10,
  6118. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6119. sink.os << "test data";
  6120. return true;
  6121. },
  6122. "text/plain", progress_callback);
  6123. });
  6124. }
  6125. // Helper function for multipart upload progress tests
  6126. template <typename SetupHandler, typename ClientCall>
  6127. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6128. ClientCall &&client_call,
  6129. const string &endpoint) {
  6130. Server svr;
  6131. setup_handler(svr);
  6132. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6133. auto se = detail::scope_exit([&] {
  6134. svr.stop();
  6135. t.join();
  6136. });
  6137. svr.wait_until_ready();
  6138. Client cli(HOST, PORT);
  6139. vector<uint64_t> progress_values;
  6140. UploadFormDataItems items = {
  6141. {"field1", "value1", "", ""},
  6142. {"field2", "longer value for progress tracking test", "", ""},
  6143. {"file1", "file content data for upload progress", "test.txt",
  6144. "text/plain"}};
  6145. auto res = client_call(cli, endpoint, items,
  6146. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6147. progress_values.push_back(current);
  6148. return true;
  6149. });
  6150. ASSERT_TRUE(res);
  6151. EXPECT_EQ(200, res->status);
  6152. EXPECT_FALSE(progress_values.empty());
  6153. }
  6154. TEST(UploadProgressTest, PostMultipartProgress) {
  6155. TestMultipartUploadProgress(
  6156. [](Server &svr) {
  6157. svr.Post("/multipart", [](const Request &req, Response &res) {
  6158. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6159. res.set_content("multipart received", "text/plain");
  6160. });
  6161. },
  6162. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6163. UploadProgress progress_callback) {
  6164. return cli.Post(endpoint, items, progress_callback);
  6165. },
  6166. "/multipart");
  6167. }
  6168. // Helper function for basic download progress tests
  6169. template <typename SetupHandler, typename ClientCall>
  6170. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6171. ClientCall &&client_call, const string &endpoint,
  6172. size_t expected_content_size) {
  6173. Server svr;
  6174. setup_handler(svr);
  6175. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6176. auto se = detail::scope_exit([&] {
  6177. svr.stop();
  6178. t.join();
  6179. });
  6180. svr.wait_until_ready();
  6181. Client cli(HOST, PORT);
  6182. vector<uint64_t> progress_values;
  6183. auto res = client_call(cli, endpoint,
  6184. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6185. progress_values.push_back(current);
  6186. return true;
  6187. });
  6188. ASSERT_TRUE(res);
  6189. EXPECT_EQ(200, res->status);
  6190. EXPECT_FALSE(progress_values.empty());
  6191. EXPECT_EQ(expected_content_size, res->body.size());
  6192. }
  6193. TEST(DownloadProgressTest, GetBasic) {
  6194. TestBasicDownloadProgress(
  6195. [](Server &svr) {
  6196. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6197. string content(1000, 'D');
  6198. res.set_content(content, "text/plain");
  6199. });
  6200. },
  6201. [](Client &cli, const string &endpoint,
  6202. DownloadProgress progress_callback) {
  6203. return cli.Get(endpoint, progress_callback);
  6204. },
  6205. "/download", 1000u);
  6206. }
  6207. // Helper function for content receiver download progress tests
  6208. template <typename SetupHandler, typename ClientCall>
  6209. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6210. ClientCall &&client_call,
  6211. const string &endpoint,
  6212. size_t expected_content_size) {
  6213. Server svr;
  6214. setup_handler(svr);
  6215. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6216. auto se = detail::scope_exit([&] {
  6217. svr.stop();
  6218. t.join();
  6219. });
  6220. svr.wait_until_ready();
  6221. Client cli(HOST, PORT);
  6222. vector<uint64_t> progress_values;
  6223. string received_body;
  6224. auto res = client_call(
  6225. cli, endpoint,
  6226. [&](const char *data, size_t data_length) -> bool {
  6227. received_body.append(data, data_length);
  6228. return true;
  6229. },
  6230. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6231. progress_values.push_back(current);
  6232. return true;
  6233. });
  6234. ASSERT_TRUE(res);
  6235. EXPECT_EQ(200, res->status);
  6236. EXPECT_FALSE(progress_values.empty());
  6237. EXPECT_EQ(expected_content_size, received_body.size());
  6238. EXPECT_TRUE(res->body.empty());
  6239. }
  6240. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6241. TestContentReceiverDownloadProgress(
  6242. [](Server &svr) {
  6243. svr.Get("/download-receiver",
  6244. [](const Request & /*req*/, Response &res) {
  6245. string content(2000, 'R');
  6246. res.set_content(content, "text/plain");
  6247. });
  6248. },
  6249. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6250. DownloadProgress progress_callback) {
  6251. return cli.Get(endpoint, content_receiver, progress_callback);
  6252. },
  6253. "/download-receiver", 2000u);
  6254. }
  6255. TEST(StreamingTest, NoContentLengthStreaming) {
  6256. Server svr;
  6257. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6258. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6259. if (offset < 6) {
  6260. sink.os << (offset < 3 ? "a" : "b");
  6261. } else {
  6262. sink.done();
  6263. }
  6264. return true;
  6265. });
  6266. });
  6267. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6268. auto listen_se = detail::scope_exit([&] {
  6269. svr.stop();
  6270. listen_thread.join();
  6271. ASSERT_FALSE(svr.is_running());
  6272. });
  6273. svr.wait_until_ready();
  6274. Client client(HOST, PORT);
  6275. auto get_thread = std::thread([&client]() {
  6276. std::string s;
  6277. auto res =
  6278. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6279. s += std::string(data, len);
  6280. return true;
  6281. });
  6282. ASSERT_TRUE(res);
  6283. EXPECT_EQ(StatusCode::OK_200, res->status);
  6284. EXPECT_EQ("aaabbb", s);
  6285. });
  6286. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6287. // Give GET time to get a few messages.
  6288. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6289. }
  6290. TEST(MountTest, Unmount) {
  6291. Server svr;
  6292. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6293. auto se = detail::scope_exit([&] {
  6294. svr.stop();
  6295. listen_thread.join();
  6296. ASSERT_FALSE(svr.is_running());
  6297. });
  6298. svr.wait_until_ready();
  6299. Client cli("localhost", PORT);
  6300. svr.set_mount_point("/mount2", "./www2");
  6301. auto res = cli.Get("/");
  6302. ASSERT_TRUE(res);
  6303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6304. res = cli.Get("/mount2/dir/test.html");
  6305. ASSERT_TRUE(res);
  6306. EXPECT_EQ(StatusCode::OK_200, res->status);
  6307. svr.set_mount_point("/", "./www");
  6308. res = cli.Get("/dir/");
  6309. ASSERT_TRUE(res);
  6310. EXPECT_EQ(StatusCode::OK_200, res->status);
  6311. svr.remove_mount_point("/");
  6312. res = cli.Get("/dir/");
  6313. ASSERT_TRUE(res);
  6314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6315. svr.remove_mount_point("/mount2");
  6316. res = cli.Get("/mount2/dir/test.html");
  6317. ASSERT_TRUE(res);
  6318. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6319. }
  6320. TEST(MountTest, Redicect) {
  6321. Server svr;
  6322. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6323. auto se = detail::scope_exit([&] {
  6324. svr.stop();
  6325. listen_thread.join();
  6326. ASSERT_FALSE(svr.is_running());
  6327. });
  6328. svr.set_mount_point("/", "./www");
  6329. svr.wait_until_ready();
  6330. Client cli("localhost", PORT);
  6331. auto res = cli.Get("/dir/");
  6332. ASSERT_TRUE(res);
  6333. EXPECT_EQ(StatusCode::OK_200, res->status);
  6334. res = cli.Get("/dir");
  6335. ASSERT_TRUE(res);
  6336. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6337. res = cli.Get("/file");
  6338. ASSERT_TRUE(res);
  6339. EXPECT_EQ(StatusCode::OK_200, res->status);
  6340. res = cli.Get("/file/");
  6341. ASSERT_TRUE(res);
  6342. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6343. cli.set_follow_location(true);
  6344. res = cli.Get("/dir");
  6345. ASSERT_TRUE(res);
  6346. EXPECT_EQ(StatusCode::OK_200, res->status);
  6347. }
  6348. TEST(MountTest, MultibytesPathName) {
  6349. Server svr;
  6350. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6351. auto se = detail::scope_exit([&] {
  6352. svr.stop();
  6353. listen_thread.join();
  6354. ASSERT_FALSE(svr.is_running());
  6355. });
  6356. svr.set_mount_point("/", "./www");
  6357. svr.wait_until_ready();
  6358. Client cli("localhost", PORT);
  6359. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6360. ASSERT_TRUE(res);
  6361. EXPECT_EQ(StatusCode::OK_200, res->status);
  6362. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6363. }
  6364. TEST(KeepAliveTest, ReadTimeout) {
  6365. Server svr;
  6366. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6367. std::this_thread::sleep_for(std::chrono::seconds(2));
  6368. res.set_content("a", "text/plain");
  6369. });
  6370. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6371. res.set_content("b", "text/plain");
  6372. });
  6373. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6374. auto se = detail::scope_exit([&] {
  6375. svr.stop();
  6376. listen_thread.join();
  6377. ASSERT_FALSE(svr.is_running());
  6378. });
  6379. svr.wait_until_ready();
  6380. Client cli("localhost", PORT);
  6381. cli.set_keep_alive(true);
  6382. cli.set_read_timeout(std::chrono::seconds(1));
  6383. auto resa = cli.Get("/a");
  6384. ASSERT_FALSE(resa);
  6385. EXPECT_EQ(Error::Read, resa.error());
  6386. auto resb = cli.Get("/b");
  6387. ASSERT_TRUE(resb);
  6388. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6389. EXPECT_EQ("b", resb->body);
  6390. }
  6391. TEST(KeepAliveTest, MaxCount) {
  6392. size_t keep_alive_max_count = 3;
  6393. Server svr;
  6394. svr.set_keep_alive_max_count(keep_alive_max_count);
  6395. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6396. res.set_content("Hello World!", "text/plain");
  6397. });
  6398. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6399. auto se = detail::scope_exit([&] {
  6400. svr.stop();
  6401. listen_thread.join();
  6402. ASSERT_FALSE(svr.is_running());
  6403. });
  6404. svr.wait_until_ready();
  6405. Client cli(HOST, PORT);
  6406. cli.set_keep_alive(true);
  6407. for (size_t i = 0; i < 5; i++) {
  6408. auto result = cli.Get("/hi");
  6409. ASSERT_TRUE(result);
  6410. EXPECT_EQ(StatusCode::OK_200, result->status);
  6411. if (i == keep_alive_max_count - 1) {
  6412. EXPECT_EQ("close", result->get_header_value("Connection"));
  6413. } else {
  6414. EXPECT_FALSE(result->has_header("Connection"));
  6415. }
  6416. }
  6417. }
  6418. TEST(KeepAliveTest, Issue1041) {
  6419. Server svr;
  6420. svr.set_keep_alive_timeout(3);
  6421. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6422. res.set_content("Hello World!", "text/plain");
  6423. });
  6424. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6425. auto se = detail::scope_exit([&] {
  6426. svr.stop();
  6427. listen_thread.join();
  6428. ASSERT_FALSE(svr.is_running());
  6429. });
  6430. svr.wait_until_ready();
  6431. Client cli(HOST, PORT);
  6432. cli.set_keep_alive(true);
  6433. auto result = cli.Get("/hi");
  6434. ASSERT_TRUE(result);
  6435. EXPECT_EQ(StatusCode::OK_200, result->status);
  6436. std::this_thread::sleep_for(std::chrono::seconds(5));
  6437. result = cli.Get("/hi");
  6438. ASSERT_TRUE(result);
  6439. EXPECT_EQ(StatusCode::OK_200, result->status);
  6440. }
  6441. TEST(KeepAliveTest, Issue1959) {
  6442. Server svr;
  6443. svr.set_keep_alive_timeout(5);
  6444. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6445. res.set_content("a", "text/plain");
  6446. });
  6447. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6448. auto se = detail::scope_exit([&] {
  6449. if (!svr.is_running()) return;
  6450. svr.stop();
  6451. listen_thread.join();
  6452. ASSERT_FALSE(svr.is_running());
  6453. });
  6454. svr.wait_until_ready();
  6455. Client cli("localhost", PORT);
  6456. cli.set_keep_alive(true);
  6457. using namespace std::chrono;
  6458. auto start = steady_clock::now();
  6459. cli.Get("/a");
  6460. svr.stop();
  6461. listen_thread.join();
  6462. auto end = steady_clock::now();
  6463. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6464. EXPECT_LT(elapsed, 5000);
  6465. }
  6466. #ifdef CPPHTTPLIB_SSL_ENABLED
  6467. TEST(KeepAliveTest, SSLClientReconnection) {
  6468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6469. ASSERT_TRUE(svr.is_valid());
  6470. svr.set_keep_alive_timeout(1);
  6471. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6472. res.set_content("Hello World!", "text/plain");
  6473. });
  6474. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6475. auto se = detail::scope_exit([&] {
  6476. svr.stop();
  6477. listen_thread.join();
  6478. ASSERT_FALSE(svr.is_running());
  6479. });
  6480. svr.wait_until_ready();
  6481. SSLClient cli(HOST, PORT);
  6482. cli.enable_server_certificate_verification(false);
  6483. cli.set_keep_alive(true);
  6484. auto result = cli.Get("/hi");
  6485. ASSERT_TRUE(result);
  6486. EXPECT_EQ(StatusCode::OK_200, result->status);
  6487. result = cli.Get("/hi");
  6488. ASSERT_TRUE(result);
  6489. EXPECT_EQ(StatusCode::OK_200, result->status);
  6490. std::this_thread::sleep_for(std::chrono::seconds(2));
  6491. // Recoonect
  6492. result = cli.Get("/hi");
  6493. ASSERT_TRUE(result);
  6494. EXPECT_EQ(StatusCode::OK_200, result->status);
  6495. result = cli.Get("/hi");
  6496. ASSERT_TRUE(result);
  6497. EXPECT_EQ(StatusCode::OK_200, result->status);
  6498. }
  6499. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6500. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6501. ASSERT_TRUE(svr.is_valid());
  6502. svr.set_keep_alive_timeout(1);
  6503. std::string content = "reconnect";
  6504. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6505. res.set_content("Hello World!", "text/plain");
  6506. });
  6507. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6508. auto se = detail::scope_exit([&] {
  6509. svr.stop();
  6510. listen_thread.join();
  6511. ASSERT_FALSE(svr.is_running());
  6512. });
  6513. svr.wait_until_ready();
  6514. SSLClient cli(HOST, PORT);
  6515. cli.enable_server_certificate_verification(false);
  6516. cli.set_keep_alive(true);
  6517. auto result = cli.Post(
  6518. "/hi", content.size(),
  6519. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6520. sink.write(content.c_str(), content.size());
  6521. return true;
  6522. },
  6523. "text/plain");
  6524. ASSERT_TRUE(result);
  6525. EXPECT_EQ(200, result->status);
  6526. std::this_thread::sleep_for(std::chrono::seconds(2));
  6527. // Recoonect
  6528. result = cli.Post(
  6529. "/hi", content.size(),
  6530. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6531. sink.write(content.c_str(), content.size());
  6532. return true;
  6533. },
  6534. "text/plain");
  6535. ASSERT_TRUE(result);
  6536. EXPECT_EQ(200, result->status);
  6537. result = cli.Post(
  6538. "/hi", content.size(),
  6539. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6540. sink.write(content.c_str(), content.size());
  6541. return true;
  6542. },
  6543. "text/plain");
  6544. ASSERT_TRUE(result);
  6545. EXPECT_EQ(200, result->status);
  6546. }
  6547. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6548. using namespace httplib::tls;
  6549. {
  6550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6551. ASSERT_TRUE(svr.is_valid());
  6552. svr.Get("/sni", [&](const Request &req, Response &res) {
  6553. std::string expected = req.sni();
  6554. EXPECT_EQ(expected, req.get_param_value("expected"));
  6555. res.set_content("ok", "text/plain");
  6556. });
  6557. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6558. auto se = detail::scope_exit([&] {
  6559. svr.stop();
  6560. listen_thread.join();
  6561. ASSERT_FALSE(svr.is_running());
  6562. });
  6563. svr.wait_until_ready();
  6564. {
  6565. SSLClient cli("localhost", PORT);
  6566. cli.enable_server_certificate_verification(false);
  6567. auto res = cli.Get("/sni?expected=localhost");
  6568. ASSERT_TRUE(res);
  6569. }
  6570. {
  6571. SSLClient cli("::1", PORT);
  6572. cli.enable_server_certificate_verification(false);
  6573. auto res = cli.Get("/sni?expected=");
  6574. // NOTE: This may fail if the server is listening on IPv4 only
  6575. // (e.g., when localhost resolves to 127.0.0.1 only)
  6576. if (res) {
  6577. EXPECT_EQ(StatusCode::OK_200, res->status);
  6578. } else {
  6579. EXPECT_EQ(Error::Connection, res.error());
  6580. }
  6581. }
  6582. }
  6583. }
  6584. #endif
  6585. TEST(ClientProblemDetectionTest, ContentProvider) {
  6586. Server svr;
  6587. size_t content_length = 1024 * 1024;
  6588. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6589. res.set_content_provider(
  6590. content_length, "text/plain",
  6591. [&](size_t offset, size_t length, DataSink &sink) {
  6592. auto out_len = std::min(length, static_cast<size_t>(1024));
  6593. std::string out(out_len, '@');
  6594. sink.write(out.data(), out_len);
  6595. return offset < 4096;
  6596. },
  6597. [](bool success) { ASSERT_FALSE(success); });
  6598. });
  6599. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6600. res.set_content_provider(
  6601. 0, "text/plain",
  6602. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6603. EXPECT_TRUE(false);
  6604. return true;
  6605. },
  6606. [](bool success) { ASSERT_FALSE(success); });
  6607. });
  6608. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6609. auto se = detail::scope_exit([&] {
  6610. svr.stop();
  6611. listen_thread.join();
  6612. ASSERT_FALSE(svr.is_running());
  6613. });
  6614. svr.wait_until_ready();
  6615. Client cli("localhost", PORT);
  6616. {
  6617. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6618. size_t /*data_length*/) { return false; });
  6619. ASSERT_FALSE(res);
  6620. }
  6621. {
  6622. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6623. size_t /*data_length*/) { return false; });
  6624. ASSERT_TRUE(res);
  6625. }
  6626. }
  6627. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6628. Server svr;
  6629. svr.set_error_handler([](Request const &, Response &res) -> void {
  6630. res.set_chunked_content_provider(
  6631. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6632. sink.os << "hello";
  6633. sink.os << "world";
  6634. sink.done();
  6635. return true;
  6636. });
  6637. });
  6638. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6639. auto se = detail::scope_exit([&] {
  6640. svr.stop();
  6641. listen_thread.join();
  6642. ASSERT_FALSE(svr.is_running());
  6643. });
  6644. svr.wait_until_ready();
  6645. Client cli("localhost", PORT);
  6646. auto res = cli.Get("/");
  6647. ASSERT_TRUE(res);
  6648. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6649. EXPECT_EQ("helloworld", res->body);
  6650. }
  6651. TEST(LongPollingTest, ClientCloseDetection) {
  6652. Server svr;
  6653. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6654. res.set_chunked_content_provider(
  6655. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6656. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6657. sink.os << "hello";
  6658. auto count = 10;
  6659. while (count > 0 && sink.is_writable()) {
  6660. this_thread::sleep_for(chrono::milliseconds(10));
  6661. count--;
  6662. }
  6663. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6664. return true;
  6665. });
  6666. });
  6667. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6668. auto se = detail::scope_exit([&] {
  6669. svr.stop();
  6670. listen_thread.join();
  6671. ASSERT_FALSE(svr.is_running());
  6672. });
  6673. svr.wait_until_ready();
  6674. Client cli("localhost", PORT);
  6675. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6676. EXPECT_EQ("hello", string(data, data_length));
  6677. return false; // close the socket immediately.
  6678. });
  6679. ASSERT_FALSE(res);
  6680. }
  6681. TEST(GetWithParametersTest, GetWithParameters) {
  6682. Server svr;
  6683. svr.Get("/", [&](const Request &req, Response &) {
  6684. EXPECT_EQ("world", req.get_param_value("hello"));
  6685. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6686. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6687. });
  6688. svr.Get("/params", [&](const Request &req, Response &) {
  6689. EXPECT_EQ("world", req.get_param_value("hello"));
  6690. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6691. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6692. });
  6693. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6694. EXPECT_EQ("resource-id", req.matches[1]);
  6695. EXPECT_EQ("foo", req.get_param_value("param1"));
  6696. EXPECT_EQ("bar", req.get_param_value("param2"));
  6697. });
  6698. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6699. EXPECT_EQ("user-id", req.path_params.at("id"));
  6700. EXPECT_EQ("foo", req.get_param_value("param1"));
  6701. EXPECT_EQ("bar", req.get_param_value("param2"));
  6702. });
  6703. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6704. auto se = detail::scope_exit([&] {
  6705. svr.stop();
  6706. listen_thread.join();
  6707. ASSERT_FALSE(svr.is_running());
  6708. });
  6709. svr.wait_until_ready();
  6710. {
  6711. Client cli(HOST, PORT);
  6712. Params params;
  6713. params.emplace("hello", "world");
  6714. params.emplace("hello2", "world2");
  6715. params.emplace("hello3", "world3");
  6716. auto res = cli.Get("/", params, Headers{});
  6717. ASSERT_TRUE(res);
  6718. EXPECT_EQ(StatusCode::OK_200, res->status);
  6719. }
  6720. {
  6721. Client cli(HOST, PORT);
  6722. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6723. ASSERT_TRUE(res);
  6724. EXPECT_EQ(StatusCode::OK_200, res->status);
  6725. }
  6726. {
  6727. Client cli(HOST, PORT);
  6728. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6729. ASSERT_TRUE(res);
  6730. EXPECT_EQ(StatusCode::OK_200, res->status);
  6731. }
  6732. {
  6733. Client cli(HOST, PORT);
  6734. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6735. ASSERT_TRUE(res);
  6736. EXPECT_EQ(StatusCode::OK_200, res->status);
  6737. }
  6738. }
  6739. TEST(GetWithParametersTest, GetWithParameters2) {
  6740. Server svr;
  6741. svr.Get("/", [&](const Request &req, Response &res) {
  6742. auto text = req.get_param_value("hello");
  6743. res.set_content(text, "text/plain");
  6744. });
  6745. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6746. auto se = detail::scope_exit([&] {
  6747. svr.stop();
  6748. listen_thread.join();
  6749. ASSERT_FALSE(svr.is_running());
  6750. });
  6751. svr.wait_until_ready();
  6752. Client cli("localhost", PORT);
  6753. Params params;
  6754. params.emplace("hello", "world");
  6755. std::string body;
  6756. auto res = cli.Get("/", params, Headers{},
  6757. [&](const char *data, size_t data_length) {
  6758. body.append(data, data_length);
  6759. return true;
  6760. });
  6761. ASSERT_TRUE(res);
  6762. EXPECT_EQ(StatusCode::OK_200, res->status);
  6763. EXPECT_EQ("world", body);
  6764. }
  6765. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6766. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6767. auto host = "httpcan.org";
  6768. auto path = std::string{"/range/32"};
  6769. #else
  6770. auto host = "nghttp2.org";
  6771. auto path = std::string{"/httpbin/range/32"};
  6772. #endif
  6773. #ifdef CPPHTTPLIB_SSL_ENABLED
  6774. SSLClient cli(host);
  6775. #else
  6776. Client cli(host);
  6777. #endif
  6778. cli.set_default_headers({make_range_header({{1, 10}})});
  6779. cli.set_connection_timeout(5);
  6780. {
  6781. auto res = cli.Get(path);
  6782. ASSERT_TRUE(res);
  6783. EXPECT_EQ("bcdefghijk", res->body);
  6784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6785. }
  6786. {
  6787. auto res = cli.Get(path);
  6788. ASSERT_TRUE(res);
  6789. EXPECT_EQ("bcdefghijk", res->body);
  6790. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6791. }
  6792. }
  6793. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6794. Server svr;
  6795. svr.set_default_headers({{"Hello", "World"}});
  6796. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6797. res.set_content("ok", "text/plain");
  6798. });
  6799. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6800. auto se = detail::scope_exit([&] {
  6801. svr.stop();
  6802. listen_thread.join();
  6803. ASSERT_FALSE(svr.is_running());
  6804. });
  6805. svr.wait_until_ready();
  6806. Client cli("localhost", PORT);
  6807. auto res = cli.Get("/");
  6808. ASSERT_TRUE(res);
  6809. EXPECT_EQ(StatusCode::OK_200, res->status);
  6810. EXPECT_EQ("ok", res->body);
  6811. EXPECT_EQ("World", res->get_header_value("Hello"));
  6812. }
  6813. #ifdef CPPHTTPLIB_SSL_ENABLED
  6814. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6816. ASSERT_TRUE(svr.is_valid());
  6817. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6818. std::this_thread::sleep_for(std::chrono::seconds(2));
  6819. res.set_content("a", "text/plain");
  6820. });
  6821. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6822. res.set_content("b", "text/plain");
  6823. });
  6824. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6825. auto se = detail::scope_exit([&] {
  6826. svr.stop();
  6827. listen_thread.join();
  6828. ASSERT_FALSE(svr.is_running());
  6829. });
  6830. svr.wait_until_ready();
  6831. SSLClient cli("localhost", PORT);
  6832. cli.enable_server_certificate_verification(false);
  6833. cli.set_keep_alive(true);
  6834. cli.set_read_timeout(std::chrono::seconds(1));
  6835. auto resa = cli.Get("/a");
  6836. ASSERT_TRUE(!resa);
  6837. EXPECT_EQ(Error::Read, resa.error());
  6838. auto resb = cli.Get("/b");
  6839. ASSERT_TRUE(resb);
  6840. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6841. EXPECT_EQ("b", resb->body);
  6842. }
  6843. #endif
  6844. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6845. protected:
  6846. ServerTestWithAI_PASSIVE()
  6847. : cli_(HOST, PORT)
  6848. #ifdef CPPHTTPLIB_SSL_ENABLED
  6849. ,
  6850. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6851. #endif
  6852. {
  6853. #ifdef CPPHTTPLIB_SSL_ENABLED
  6854. cli_.enable_server_certificate_verification(false);
  6855. #endif
  6856. }
  6857. virtual void SetUp() {
  6858. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6859. res.set_content("Hello World!", "text/plain");
  6860. });
  6861. t_ = thread(
  6862. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6863. svr_.wait_until_ready();
  6864. }
  6865. virtual void TearDown() {
  6866. svr_.stop();
  6867. t_.join();
  6868. }
  6869. #ifdef CPPHTTPLIB_SSL_ENABLED
  6870. SSLClient cli_;
  6871. SSLServer svr_;
  6872. #else
  6873. Client cli_;
  6874. Server svr_;
  6875. #endif
  6876. thread t_;
  6877. };
  6878. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6879. auto res = cli_.Get("/hi");
  6880. ASSERT_TRUE(res);
  6881. EXPECT_EQ(StatusCode::OK_200, res->status);
  6882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6883. EXPECT_EQ("Hello World!", res->body);
  6884. }
  6885. class ServerUpDownTest : public ::testing::Test {
  6886. protected:
  6887. ServerUpDownTest() : cli_(HOST, PORT) {}
  6888. virtual void SetUp() {
  6889. t_ = thread([&]() {
  6890. svr_.bind_to_any_port(HOST);
  6891. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6892. ASSERT_TRUE(svr_.listen_after_bind());
  6893. });
  6894. svr_.wait_until_ready();
  6895. }
  6896. virtual void TearDown() {
  6897. svr_.stop();
  6898. t_.join();
  6899. }
  6900. Client cli_;
  6901. Server svr_;
  6902. thread t_;
  6903. };
  6904. TEST_F(ServerUpDownTest, QuickStartStop) {
  6905. // Should not crash, especially when run with
  6906. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6907. }
  6908. class PayloadMaxLengthTest : public ::testing::Test {
  6909. protected:
  6910. PayloadMaxLengthTest()
  6911. : cli_(HOST, PORT)
  6912. #ifdef CPPHTTPLIB_SSL_ENABLED
  6913. ,
  6914. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6915. #endif
  6916. {
  6917. #ifdef CPPHTTPLIB_SSL_ENABLED
  6918. cli_.enable_server_certificate_verification(false);
  6919. #endif
  6920. }
  6921. virtual void SetUp() {
  6922. svr_.set_payload_max_length(8);
  6923. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6924. res.set_content("test", "text/plain");
  6925. });
  6926. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6927. svr_.wait_until_ready();
  6928. }
  6929. virtual void TearDown() {
  6930. svr_.stop();
  6931. t_.join();
  6932. }
  6933. #ifdef CPPHTTPLIB_SSL_ENABLED
  6934. SSLClient cli_;
  6935. SSLServer svr_;
  6936. #else
  6937. Client cli_;
  6938. Server svr_;
  6939. #endif
  6940. thread t_;
  6941. };
  6942. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6943. auto res = cli_.Post("/test", "123456789", "text/plain");
  6944. ASSERT_TRUE(res);
  6945. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6946. res = cli_.Post("/test", "12345678", "text/plain");
  6947. ASSERT_TRUE(res);
  6948. EXPECT_EQ(StatusCode::OK_200, res->status);
  6949. }
  6950. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6951. // Test chunked encoding with payload exceeding the 8-byte limit
  6952. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6953. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6954. ASSERT_TRUE(res);
  6955. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6956. }
  6957. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6958. // Test chunked encoding with payload within the 8-byte limit
  6959. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6960. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6961. ASSERT_TRUE(res);
  6962. EXPECT_EQ(StatusCode::OK_200, res->status);
  6963. }
  6964. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6965. // Test using send_request to send chunked data exceeding payload limit
  6966. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6967. "Host: " +
  6968. std::string(HOST) + ":" + std::to_string(PORT) +
  6969. "\r\n"
  6970. "Transfer-Encoding: chunked\r\n"
  6971. "Connection: close\r\n"
  6972. "\r\n"
  6973. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6974. "0123456789\r\n"
  6975. "0\r\n" // End chunk
  6976. "\r\n";
  6977. std::string response;
  6978. bool result = send_request(1, chunked_request, &response);
  6979. if (!result) {
  6980. // If send_request fails, it might be because the server closed the
  6981. // connection due to payload limit enforcement, which is acceptable
  6982. SUCCEED()
  6983. << "Server rejected oversized chunked request (connection closed)";
  6984. } else {
  6985. // If we got a response, check if it's an error response or connection was
  6986. // closed early Short response length indicates connection was closed due to
  6987. // payload limit
  6988. if (response.length() <= 10) {
  6989. SUCCEED() << "Server closed connection for oversized chunked request";
  6990. } else {
  6991. // Check for error status codes
  6992. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6993. response.find("Payload Too Large") != std::string::npos ||
  6994. response.find("400") != std::string::npos);
  6995. }
  6996. }
  6997. }
  6998. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6999. // Test request without Content-Length header exceeding payload limit
  7000. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7001. "Host: " +
  7002. std::string(HOST) + ":" +
  7003. std::to_string(PORT) +
  7004. "\r\n"
  7005. "Connection: close\r\n"
  7006. "\r\n";
  7007. // Add payload exceeding the 8-byte limit
  7008. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7009. request_without_content_length += large_payload;
  7010. std::string response;
  7011. bool result = send_request(1, request_without_content_length, &response);
  7012. if (!result) {
  7013. // If send_request fails, server likely closed connection due to payload
  7014. // limit
  7015. SUCCEED() << "Server rejected oversized request without Content-Length "
  7016. "(connection closed)";
  7017. } else {
  7018. // Check if server responded with error or closed connection early
  7019. if (response.length() <= 10) {
  7020. SUCCEED() << "Server closed connection for oversized request without "
  7021. "Content-Length";
  7022. } else {
  7023. // Check for error status codes
  7024. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7025. response.find("Payload Too Large") != std::string::npos ||
  7026. response.find("400") != std::string::npos);
  7027. }
  7028. }
  7029. }
  7030. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7031. // Test request without Content-Length header within payload limit
  7032. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7033. "Host: " +
  7034. std::string(HOST) + ":" +
  7035. std::to_string(PORT) +
  7036. "\r\n"
  7037. "Connection: close\r\n"
  7038. "\r\n";
  7039. // Add payload within the 8-byte limit
  7040. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7041. request_without_content_length += small_payload;
  7042. std::string response;
  7043. bool result = send_request(1, request_without_content_length, &response);
  7044. // For requests without Content-Length, the server may have different behavior
  7045. // The key is that it should not reject due to payload limit for small
  7046. // payloads
  7047. if (result) {
  7048. // Check for any HTTP response (success or error, but not connection closed)
  7049. if (response.length() > 10) {
  7050. SUCCEED()
  7051. << "Server processed request without Content-Length within limit";
  7052. } else {
  7053. // Short response might indicate connection closed, which is acceptable
  7054. SUCCEED() << "Server closed connection for request without "
  7055. "Content-Length (acceptable behavior)";
  7056. }
  7057. } else {
  7058. // Connection failure might be due to protocol requirements
  7059. SUCCEED() << "Connection issue with request without Content-Length "
  7060. "(environment-specific)";
  7061. }
  7062. }
  7063. class LargePayloadMaxLengthTest : public ::testing::Test {
  7064. protected:
  7065. LargePayloadMaxLengthTest()
  7066. : cli_(HOST, PORT)
  7067. #ifdef CPPHTTPLIB_SSL_ENABLED
  7068. ,
  7069. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7070. #endif
  7071. {
  7072. #ifdef CPPHTTPLIB_SSL_ENABLED
  7073. cli_.enable_server_certificate_verification(false);
  7074. #endif
  7075. }
  7076. virtual void SetUp() {
  7077. // Set 10MB payload limit
  7078. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7079. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7080. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7081. res.set_content("Large payload test", "text/plain");
  7082. });
  7083. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7084. svr_.wait_until_ready();
  7085. }
  7086. virtual void TearDown() {
  7087. svr_.stop();
  7088. t_.join();
  7089. }
  7090. #ifdef CPPHTTPLIB_SSL_ENABLED
  7091. SSLClient cli_;
  7092. SSLServer svr_;
  7093. #else
  7094. Client cli_;
  7095. Server svr_;
  7096. #endif
  7097. thread t_;
  7098. };
  7099. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7100. // Test chunked encoding with payload within 10MB limit
  7101. std::string medium_payload(5 * 1024 * 1024,
  7102. 'A'); // 5MB payload, within 10MB limit
  7103. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7104. ASSERT_TRUE(res);
  7105. EXPECT_EQ(StatusCode::OK_200, res->status);
  7106. }
  7107. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7108. // Test chunked encoding with payload exceeding 10MB limit
  7109. std::string large_payload(12 * 1024 * 1024,
  7110. 'B'); // 12MB payload, exceeds 10MB limit
  7111. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7112. ASSERT_TRUE(res);
  7113. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7114. }
  7115. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7116. // Test request without Content-Length header within 10MB limit
  7117. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7118. "Host: " +
  7119. std::string(HOST) + ":" +
  7120. std::to_string(PORT) +
  7121. "\r\n"
  7122. "Connection: close\r\n"
  7123. "\r\n";
  7124. // Add 1MB payload (within 10MB limit)
  7125. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7126. request_without_content_length += medium_payload;
  7127. std::string response;
  7128. bool result = send_request(5, request_without_content_length, &response);
  7129. if (result) {
  7130. // Should get a proper HTTP response for payloads within limit
  7131. if (response.length() > 10) {
  7132. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7133. "10MB limit";
  7134. } else {
  7135. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7136. "Content-Length)";
  7137. }
  7138. } else {
  7139. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7140. }
  7141. }
  7142. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7143. // Test request without Content-Length header exceeding 10MB limit
  7144. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7145. "Host: " +
  7146. std::string(HOST) + ":" +
  7147. std::to_string(PORT) +
  7148. "\r\n"
  7149. "Connection: close\r\n"
  7150. "\r\n";
  7151. // Add 12MB payload (exceeds 10MB limit)
  7152. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7153. request_without_content_length += large_payload;
  7154. std::string response;
  7155. bool result = send_request(10, request_without_content_length, &response);
  7156. if (!result) {
  7157. // Server should close connection due to payload limit
  7158. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7159. "(connection closed)";
  7160. } else {
  7161. // Check for error response
  7162. if (response.length() <= 10) {
  7163. SUCCEED()
  7164. << "Server closed connection for 12MB request exceeding 10MB limit";
  7165. } else {
  7166. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7167. response.find("Payload Too Large") != std::string::npos ||
  7168. response.find("400") != std::string::npos);
  7169. }
  7170. }
  7171. }
  7172. TEST(HostAndPortPropertiesTest, NoSSL) {
  7173. httplib::Client cli("www.google.com", 1234);
  7174. ASSERT_EQ("www.google.com", cli.host());
  7175. ASSERT_EQ(1234, cli.port());
  7176. }
  7177. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7178. httplib::Client cli("www.google.com:1234");
  7179. ASSERT_EQ("www.google.com", cli.host());
  7180. ASSERT_EQ(1234, cli.port());
  7181. }
  7182. #ifdef CPPHTTPLIB_SSL_ENABLED
  7183. TEST(HostAndPortPropertiesTest, SSL) {
  7184. httplib::SSLClient cli("www.google.com");
  7185. ASSERT_EQ("www.google.com", cli.host());
  7186. ASSERT_EQ(443, cli.port());
  7187. }
  7188. TEST(SSLClientTest, UpdateCAStoreWithPem) {
  7189. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7190. std::string cert;
  7191. read_file(CA_CERT_FILE, cert);
  7192. httplib::SSLClient httplib_client("www.google.com");
  7193. // Load CA store first time
  7194. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7195. // Load CA store second time (update)
  7196. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7197. // Verify client is still valid and can make connections
  7198. httplib_client.enable_server_certificate_verification(true);
  7199. auto res = httplib_client.Get("/");
  7200. ASSERT_TRUE(res);
  7201. // Google may return 200 or 301 depending on various factors
  7202. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7203. res->status == StatusCode::MovedPermanently_301);
  7204. }
  7205. TEST(SSLClientTest, ServerNameIndication_Online) {
  7206. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7207. auto host = "httpcan.org";
  7208. auto path = std::string{"/get"};
  7209. #else
  7210. auto host = "nghttp2.org";
  7211. auto path = std::string{"/httpbin/get"};
  7212. #endif
  7213. SSLClient cli(host, 443);
  7214. auto res = cli.Get(path);
  7215. ASSERT_TRUE(res);
  7216. ASSERT_EQ(StatusCode::OK_200, res->status);
  7217. }
  7218. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7219. // Use a site that will cause SSL verification failure due to self-signed cert
  7220. SSLClient cli("self-signed.badssl.com", 443);
  7221. cli.enable_server_certificate_verification(true);
  7222. auto res = cli.Get("/");
  7223. ASSERT_TRUE(!res);
  7224. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7225. // Verify backend error is captured for SSLServerVerification
  7226. // This occurs when certificate verification fails
  7227. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7228. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7229. EXPECT_NE(0UL, res.ssl_backend_error());
  7230. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7231. // For OpenSSL, ssl_error is 0 for verification errors
  7232. EXPECT_EQ(0, res.ssl_error());
  7233. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7234. res.ssl_backend_error());
  7235. #endif
  7236. }
  7237. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7238. // Use a site where hostname doesn't match the certificate
  7239. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7240. SSLClient cli("wrong.host.badssl.com", 443);
  7241. cli.enable_server_certificate_verification(true);
  7242. cli.enable_server_hostname_verification(true);
  7243. auto res = cli.Get("/");
  7244. ASSERT_TRUE(!res);
  7245. // The error type depends on when hostname verification occurs:
  7246. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  7247. // - Mbed TLS: SSLServerVerification (during handshake)
  7248. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  7249. res.error() == Error::SSLServerVerification);
  7250. // Verify backend error is captured for hostname verification failure
  7251. EXPECT_NE(0UL, res.ssl_backend_error());
  7252. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7253. // For OpenSSL, ssl_error is 0 for verification errors
  7254. EXPECT_EQ(0, res.ssl_error());
  7255. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7256. res.ssl_backend_error());
  7257. #endif
  7258. }
  7259. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7260. Client cli("https://google.com");
  7261. auto res = cli.Get("/");
  7262. ASSERT_TRUE(res);
  7263. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7264. }
  7265. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7266. SSLClient cli("google.com");
  7267. cli.set_ca_cert_path(CA_CERT_FILE);
  7268. auto res = cli.Get("/");
  7269. ASSERT_TRUE(res);
  7270. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7271. }
  7272. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7273. SSLClient cli("google.com");
  7274. cli.enable_server_certificate_verification(true);
  7275. cli.set_ca_cert_path("hello");
  7276. auto res = cli.Get("/");
  7277. ASSERT_TRUE(!res);
  7278. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7279. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  7280. // should be set
  7281. EXPECT_EQ(0, res.ssl_error());
  7282. // Verify backend error is captured for SSLLoadingCerts
  7283. // This error occurs when loading CA certificates fails
  7284. EXPECT_NE(0UL, res.ssl_backend_error());
  7285. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7286. // OpenSSL specific error codes:
  7287. // > openssl errstr 0x80000002
  7288. // error:80000002:system library::No such file or directory
  7289. // > openssl errstr 0xA000126
  7290. // error:0A000126:SSL routines::unexpected eof while reading
  7291. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  7292. res.ssl_backend_error() == 0xA000126);
  7293. #endif
  7294. }
  7295. TEST(SSLClientTest, ServerCertificateVerification4) {
  7296. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7297. ASSERT_TRUE(svr.is_valid());
  7298. svr.Get("/test", [&](const Request &, Response &res) {
  7299. res.set_content("test", "text/plain");
  7300. svr.stop();
  7301. ASSERT_TRUE(true);
  7302. });
  7303. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7304. auto se = detail::scope_exit([&] {
  7305. t.join();
  7306. ASSERT_FALSE(svr.is_running());
  7307. });
  7308. svr.wait_until_ready();
  7309. SSLClient cli("127.0.0.1", PORT);
  7310. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7311. cli.enable_server_certificate_verification(true);
  7312. cli.set_connection_timeout(30);
  7313. auto res = cli.Get("/test");
  7314. ASSERT_TRUE(res);
  7315. ASSERT_EQ(StatusCode::OK_200, res->status);
  7316. }
  7317. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7318. std::string cert;
  7319. read_file(CA_CERT_FILE, cert);
  7320. SSLClient cli("google.com");
  7321. cli.load_ca_cert_store(cert.data(), cert.size());
  7322. const auto res = cli.Get("/");
  7323. ASSERT_TRUE(res);
  7324. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7325. }
  7326. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7327. // clang-format off
  7328. static constexpr char cert[] =
  7329. "GlobalSign Root CA\n"
  7330. "==================\n"
  7331. "-----BEGIN CERTIFICATE-----\n"
  7332. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7333. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7334. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7335. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7336. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7337. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7338. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7339. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7340. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7341. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7342. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7343. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7344. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7345. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7346. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7347. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7348. "-----END CERTIFICATE-----\n";
  7349. // clang-format on
  7350. SSLClient cli("google.com");
  7351. cli.load_ca_cert_store(cert, sizeof(cert));
  7352. const auto res = cli.Get("/");
  7353. ASSERT_TRUE(res);
  7354. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7355. }
  7356. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7357. SSLClient cli("www.youtube.com");
  7358. cli.set_ca_cert_path(CA_CERT_FILE);
  7359. cli.enable_server_certificate_verification(true);
  7360. cli.set_follow_location(true);
  7361. auto res = cli.Get("/");
  7362. ASSERT_TRUE(res);
  7363. ASSERT_EQ(StatusCode::OK_200, res->status);
  7364. }
  7365. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  7366. SSLClient cli("wWw.YouTube.Com");
  7367. cli.set_ca_cert_path(CA_CERT_FILE);
  7368. cli.enable_server_certificate_verification(true);
  7369. cli.enable_server_hostname_verification(true);
  7370. cli.set_follow_location(true);
  7371. auto res = cli.Get("/");
  7372. ASSERT_TRUE(res);
  7373. ASSERT_EQ(StatusCode::OK_200, res->status);
  7374. }
  7375. TEST(SSLClientTest, HostNameMatchCase_Online) {
  7376. SSLClient cli("gOoGlE.COm");
  7377. cli.enable_server_certificate_verification(true);
  7378. cli.enable_server_hostname_verification(true);
  7379. cli.set_follow_location(true);
  7380. auto res = cli.Get("/");
  7381. ASSERT_TRUE(res);
  7382. ASSERT_EQ(StatusCode::OK_200, res->status);
  7383. }
  7384. TEST(SSLClientTest, Issue2004_Online) {
  7385. Client client("https://google.com");
  7386. client.set_follow_location(true);
  7387. auto res = client.Get("/");
  7388. ASSERT_TRUE(res);
  7389. ASSERT_EQ(StatusCode::OK_200, res->status);
  7390. auto body = res->body;
  7391. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7392. }
  7393. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7394. // Create SSLClient with invalid cert/key to make is_valid() return false
  7395. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7396. "nonexistent_key.pem");
  7397. // is_valid() should be false due to cert loading failure
  7398. ASSERT_FALSE(cli.is_valid());
  7399. auto res = cli.Get("/");
  7400. ASSERT_FALSE(res);
  7401. EXPECT_EQ(Error::SSLConnection, res.error());
  7402. }
  7403. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7404. // Test for Issue #2251: SSL error not properly reported when client cert
  7405. // and key paths are swapped or mismatched
  7406. // This simulates the scenario where user accidentally swaps the cert and key
  7407. // files
  7408. // Using client cert file as private key and vice versa (completely wrong)
  7409. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7410. // Should fail validation due to cert/key mismatch
  7411. ASSERT_FALSE(cli.is_valid());
  7412. // Attempt to make a request should fail with proper error
  7413. auto res = cli.Get("/");
  7414. ASSERT_FALSE(res);
  7415. EXPECT_EQ(Error::SSLConnection, res.error());
  7416. // SSL error should be recorded in the Result object (this is the key fix for
  7417. // Issue #2251)
  7418. auto backend_error = res.ssl_backend_error();
  7419. EXPECT_NE(0u, backend_error);
  7420. }
  7421. // Tests cert/key mismatch detection at the TLS context level
  7422. TEST(TlsApiTest, ClientCertKeyMismatch) {
  7423. // Test that using mismatched cert/key causes connection failure.
  7424. // We verify this at the SSLClient level rather than through internal
  7425. // TLS API functions.
  7426. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  7427. cli.enable_server_certificate_verification(false);
  7428. cli.set_connection_timeout(2);
  7429. // The mismatch should cause a connection or handshake error
  7430. auto res = cli.Get("/test");
  7431. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  7432. // Either way, the request should fail
  7433. EXPECT_FALSE(res);
  7434. }
  7435. #endif
  7436. #if 0
  7437. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7438. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7439. ASSERT_TRUE(cli != nullptr);
  7440. cli->set_address_family(AF_INET6);
  7441. cli->set_interface("en0");
  7442. auto res = cli->Get("/get");
  7443. ASSERT_TRUE(res);
  7444. ASSERT_EQ(StatusCode::OK_200, res->status);
  7445. }
  7446. #endif
  7447. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  7448. #ifdef CPPHTTPLIB_SSL_ENABLED
  7449. void ClientCertPresent(
  7450. const std::string &client_cert_file,
  7451. const std::string &client_private_key_file,
  7452. const std::string &client_encrypted_private_key_pass = std::string()) {
  7453. using namespace httplib::tls;
  7454. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7455. CLIENT_CA_CERT_DIR);
  7456. ASSERT_TRUE(svr.is_valid());
  7457. svr.Get("/test", [&](const Request &req, Response &res) {
  7458. res.set_content("test", "text/plain");
  7459. auto cert = req.peer_cert();
  7460. ASSERT_TRUE(static_cast<bool>(cert));
  7461. std::string common_name = cert.subject_cn();
  7462. EXPECT_EQ("Common Name", common_name);
  7463. });
  7464. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7465. auto se = detail::scope_exit([&] {
  7466. svr.stop();
  7467. t.join();
  7468. ASSERT_FALSE(svr.is_running());
  7469. });
  7470. svr.wait_until_ready();
  7471. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7472. client_encrypted_private_key_pass);
  7473. cli.enable_server_certificate_verification(false);
  7474. cli.set_connection_timeout(30);
  7475. auto res = cli.Get("/test");
  7476. ASSERT_TRUE(res);
  7477. ASSERT_EQ(StatusCode::OK_200, res->status);
  7478. }
  7479. TEST(SSLClientServerTest, ClientCertPresent) {
  7480. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7481. }
  7482. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7483. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7484. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7485. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7486. }
  7487. // PEM memory-based constructor tests (works with all TLS backends)
  7488. void PemMemoryClientCertPresent(
  7489. const std::string &client_cert_file,
  7490. const std::string &client_private_key_file,
  7491. const std::string &client_encrypted_private_key_pass = std::string()) {
  7492. // Read PEM files into memory
  7493. std::string server_cert_pem, server_key_pem;
  7494. std::string client_ca_pem;
  7495. std::string client_cert_pem, client_key_pem;
  7496. read_file(SERVER_CERT_FILE, server_cert_pem);
  7497. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  7498. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  7499. read_file(client_cert_file, client_cert_pem);
  7500. read_file(client_private_key_file, client_key_pem);
  7501. // Create server with PEM memory
  7502. SSLServer::PemMemory server_pem = {
  7503. server_cert_pem.c_str(),
  7504. server_cert_pem.size(),
  7505. server_key_pem.c_str(),
  7506. server_key_pem.size(),
  7507. client_ca_pem.c_str(),
  7508. client_ca_pem.size(),
  7509. nullptr // no password for server key
  7510. };
  7511. SSLServer svr(server_pem);
  7512. ASSERT_TRUE(svr.is_valid());
  7513. svr.Get("/test", [&](const Request &, Response &res) {
  7514. res.set_content("test", "text/plain");
  7515. });
  7516. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7517. auto se = detail::scope_exit([&] {
  7518. svr.stop();
  7519. t.join();
  7520. ASSERT_FALSE(svr.is_running());
  7521. });
  7522. svr.wait_until_ready();
  7523. // Create client with PEM memory
  7524. const char *password = client_encrypted_private_key_pass.empty()
  7525. ? nullptr
  7526. : client_encrypted_private_key_pass.c_str();
  7527. SSLClient::PemMemory client_pem = {
  7528. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  7529. client_key_pem.size(), password};
  7530. SSLClient cli(HOST, PORT, client_pem);
  7531. cli.enable_server_certificate_verification(false);
  7532. cli.set_connection_timeout(30);
  7533. auto res = cli.Get("/test");
  7534. ASSERT_TRUE(res);
  7535. ASSERT_EQ(StatusCode::OK_200, res->status);
  7536. }
  7537. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  7538. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7539. }
  7540. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  7541. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7542. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7543. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7544. }
  7545. TEST(SSLClientServerTest, ClientCertMissing) {
  7546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7547. CLIENT_CA_CERT_DIR);
  7548. ASSERT_TRUE(svr.is_valid());
  7549. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7550. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7551. auto se = detail::scope_exit([&] {
  7552. svr.stop();
  7553. t.join();
  7554. ASSERT_FALSE(svr.is_running());
  7555. });
  7556. svr.wait_until_ready();
  7557. SSLClient cli(HOST, PORT);
  7558. cli.set_connection_timeout(30);
  7559. auto res = cli.Get("/test");
  7560. ASSERT_TRUE(!res);
  7561. // When client cert is missing and server requires it, connection fails
  7562. // Error type depends on backend implementation
  7563. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  7564. res.error() == Error::SSLConnection);
  7565. // Verify backend error is captured
  7566. // Note: This test may have different error codes depending on the exact
  7567. // verification failure
  7568. EXPECT_NE(0UL, res.ssl_backend_error());
  7569. }
  7570. TEST(SSLClientServerTest, TrustDirOptional) {
  7571. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7572. ASSERT_TRUE(svr.is_valid());
  7573. svr.Get("/test", [&](const Request &, Response &res) {
  7574. res.set_content("test", "text/plain");
  7575. });
  7576. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7577. auto se = detail::scope_exit([&] {
  7578. svr.stop();
  7579. t.join();
  7580. ASSERT_FALSE(svr.is_running());
  7581. });
  7582. svr.wait_until_ready();
  7583. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7584. cli.enable_server_certificate_verification(false);
  7585. cli.set_connection_timeout(30);
  7586. auto res = cli.Get("/test");
  7587. ASSERT_TRUE(res);
  7588. ASSERT_EQ(StatusCode::OK_200, res->status);
  7589. }
  7590. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7591. class NoListenSSLServer : public SSLServer {
  7592. public:
  7593. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7594. const char *client_ca_cert_file_path,
  7595. const char *client_ca_cert_dir_path = nullptr)
  7596. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7597. client_ca_cert_dir_path),
  7598. stop_(false) {}
  7599. std::atomic_bool stop_;
  7600. private:
  7601. bool process_and_close_socket(socket_t /*sock*/) override {
  7602. // Don't create SSL context
  7603. while (!stop_.load()) {
  7604. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7605. }
  7606. return true;
  7607. }
  7608. };
  7609. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7610. CLIENT_CA_CERT_FILE);
  7611. ASSERT_TRUE(svr.is_valid());
  7612. svr.Get("/test", [&](const Request &, Response &res) {
  7613. res.set_content("test", "text/plain");
  7614. });
  7615. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7616. auto se = detail::scope_exit([&] {
  7617. svr.stop_ = true;
  7618. svr.stop();
  7619. t.join();
  7620. ASSERT_FALSE(svr.is_running());
  7621. });
  7622. svr.wait_until_ready();
  7623. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7624. cli.enable_server_certificate_verification(false);
  7625. cli.set_connection_timeout(1);
  7626. auto res = cli.Get("/test");
  7627. ASSERT_TRUE(!res);
  7628. EXPECT_EQ(Error::SSLConnection, res.error());
  7629. // Timeout results in WantRead error code (maps to backend-specific value)
  7630. EXPECT_NE(0, res.ssl_error());
  7631. }
  7632. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  7633. // Test SSLServer with client certificate verification using the standard
  7634. // constructor (ContextSetupCallback is tested by backend-specific tests)
  7635. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7636. CLIENT_CA_CERT_DIR);
  7637. ASSERT_TRUE(svr.is_valid());
  7638. svr.Get("/test", [&](const Request &req, Response &res) {
  7639. res.set_content("test", "text/plain");
  7640. auto cert = req.peer_cert();
  7641. ASSERT_TRUE(static_cast<bool>(cert));
  7642. auto common_name = cert.subject_cn();
  7643. EXPECT_EQ("Common Name", common_name);
  7644. });
  7645. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7646. auto se = detail::scope_exit([&] {
  7647. svr.stop();
  7648. t.join();
  7649. ASSERT_FALSE(svr.is_running());
  7650. });
  7651. svr.wait_until_ready();
  7652. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7653. cli.enable_server_certificate_verification(false);
  7654. cli.set_connection_timeout(30);
  7655. auto res = cli.Get("/test");
  7656. ASSERT_TRUE(res);
  7657. ASSERT_EQ(StatusCode::OK_200, res->status);
  7658. }
  7659. // Test verify_hostname for both OpenSSL and MbedTLS backends
  7660. // Verifies that wildcard matching and exact matching work consistently
  7661. TEST(SSLClientServerTest, TlsVerifyHostname) {
  7662. using namespace httplib::tls;
  7663. // We need a running server to test against
  7664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7665. ASSERT_TRUE(svr.is_valid());
  7666. svr.Get("/test", [](const Request &, Response &res) {
  7667. res.set_content("ok", "text/plain");
  7668. });
  7669. thread t([&]() { svr.listen(HOST, PORT); });
  7670. auto se = detail::scope_exit([&] {
  7671. svr.stop();
  7672. t.join();
  7673. });
  7674. svr.wait_until_ready();
  7675. bool verify_callback_called = false;
  7676. bool verify_result_wrong = false;
  7677. SSLClient cli(HOST, PORT);
  7678. cli.enable_server_certificate_verification(true);
  7679. cli.set_ca_cert_path(CA_CERT_FILE);
  7680. cli.set_connection_timeout(5);
  7681. // Note: Test certificate has CN="Common Name", not "localhost"
  7682. bool verify_result_cn = false;
  7683. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7684. verify_callback_called = true;
  7685. if (!ctx.cert) return false;
  7686. // Test 1: "Common Name" should match (our test server cert CN)
  7687. verify_result_cn = ctx.check_hostname("Common Name");
  7688. // Test 2: wrong hostname should not match
  7689. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  7690. return true; // Accept for the purpose of this test
  7691. });
  7692. auto res = cli.Get("/test");
  7693. // The request may succeed or fail depending on cert configuration
  7694. // but the callback should have been called
  7695. ASSERT_TRUE(verify_callback_called)
  7696. << "Verify callback should have been called";
  7697. // CN="Common Name" should match our test certificate
  7698. EXPECT_TRUE(verify_result_cn)
  7699. << "verify_hostname should match 'Common Name' (certificate CN)";
  7700. // Wrong hostname should not match
  7701. EXPECT_FALSE(verify_result_wrong)
  7702. << "verify_hostname should not match 'wronghost.example.com'";
  7703. }
  7704. #endif
  7705. // mbedTLS-specific callback constructor test
  7706. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  7707. #ifdef CPPHTTPLIB_SSL_ENABLED
  7708. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7710. ASSERT_TRUE(svr.is_valid());
  7711. // Set up a handler to verify client certificate is present
  7712. bool client_cert_verified = false;
  7713. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7714. // Verify that client certificate was provided
  7715. client_cert_verified = true;
  7716. res.set_content("success", "text/plain");
  7717. });
  7718. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7719. auto se = detail::scope_exit([&] {
  7720. svr.stop();
  7721. t.join();
  7722. ASSERT_FALSE(svr.is_running());
  7723. });
  7724. svr.wait_until_ready();
  7725. // Client with certificate
  7726. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7727. cli.enable_server_certificate_verification(false);
  7728. cli.set_connection_timeout(30);
  7729. auto res = cli.Get("/test");
  7730. ASSERT_TRUE(res);
  7731. ASSERT_EQ(StatusCode::OK_200, res->status);
  7732. ASSERT_TRUE(client_cert_verified);
  7733. EXPECT_EQ("success", res->body);
  7734. }
  7735. #endif
  7736. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  7737. // backends
  7738. #ifdef CPPHTTPLIB_SSL_ENABLED
  7739. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7740. using namespace httplib::tls;
  7741. // Test that when client CA cert file is provided,
  7742. // the server properly requests and validates client certificates
  7743. // Create a server with client authentication
  7744. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7745. ASSERT_TRUE(svr.is_valid());
  7746. bool handler_called = false;
  7747. svr.Get("/test", [&](const Request &req, Response &res) {
  7748. handler_called = true;
  7749. // Verify that a client certificate was provided
  7750. auto cert = req.peer_cert();
  7751. ASSERT_TRUE(static_cast<bool>(cert));
  7752. // Get the issuer name
  7753. std::string issuer_str = cert.issuer_name();
  7754. ASSERT_FALSE(issuer_str.empty());
  7755. // The client certificate should be issued by our test CA
  7756. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7757. res.set_content("authenticated", "text/plain");
  7758. });
  7759. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7760. auto se = detail::scope_exit([&] {
  7761. svr.stop();
  7762. t.join();
  7763. ASSERT_FALSE(svr.is_running());
  7764. });
  7765. svr.wait_until_ready();
  7766. // Connect with a client certificate issued by the CA
  7767. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7768. cli.enable_server_certificate_verification(false);
  7769. cli.set_connection_timeout(30);
  7770. auto res = cli.Get("/test");
  7771. ASSERT_TRUE(res);
  7772. ASSERT_EQ(StatusCode::OK_200, res->status);
  7773. ASSERT_TRUE(handler_called);
  7774. EXPECT_EQ("authenticated", res->body);
  7775. }
  7776. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  7777. using namespace httplib::tls;
  7778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7779. ASSERT_TRUE(svr.is_valid());
  7780. svr.Get("/test", [](const Request &, Response &res) {
  7781. res.set_content("ok", "text/plain");
  7782. });
  7783. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7784. auto se = detail::scope_exit([&] {
  7785. svr.stop();
  7786. t.join();
  7787. });
  7788. svr.wait_until_ready();
  7789. SSLClient cli(HOST, PORT);
  7790. cli.enable_server_certificate_verification(false);
  7791. cli.set_connection_timeout(30);
  7792. bool cert_checked = false;
  7793. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7794. if (ctx.cert) {
  7795. auto sans = ctx.sans();
  7796. // Test certificate may or may not have SANs - just verify the API
  7797. // works If SANs exist, verify the types are valid
  7798. for (const auto &san : sans) {
  7799. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  7800. san.type == SanType::EMAIL || san.type == SanType::URI ||
  7801. san.type == SanType::OTHER);
  7802. EXPECT_FALSE(san.value.empty());
  7803. }
  7804. cert_checked = true;
  7805. }
  7806. return true;
  7807. });
  7808. auto res = cli.Get("/test");
  7809. ASSERT_TRUE(res);
  7810. EXPECT_TRUE(cert_checked);
  7811. }
  7812. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  7813. using namespace httplib::tls;
  7814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7815. ASSERT_TRUE(svr.is_valid());
  7816. svr.Get("/test", [](const Request &, Response &res) {
  7817. res.set_content("ok", "text/plain");
  7818. });
  7819. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7820. auto se = detail::scope_exit([&] {
  7821. svr.stop();
  7822. t.join();
  7823. });
  7824. svr.wait_until_ready();
  7825. SSLClient cli(HOST, PORT);
  7826. cli.enable_server_certificate_verification(false);
  7827. cli.set_connection_timeout(30);
  7828. bool validity_checked = false;
  7829. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7830. if (ctx.cert) {
  7831. time_t not_before = 0, not_after = 0;
  7832. bool result = ctx.validity(not_before, not_after);
  7833. EXPECT_TRUE(result);
  7834. // Verify that not_before < now < not_after for a valid cert
  7835. time_t now = time(nullptr);
  7836. EXPECT_LT(not_before, now);
  7837. EXPECT_GT(not_after, now);
  7838. validity_checked = true;
  7839. }
  7840. return true;
  7841. });
  7842. auto res = cli.Get("/test");
  7843. ASSERT_TRUE(res);
  7844. EXPECT_TRUE(validity_checked);
  7845. }
  7846. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  7847. using namespace httplib::tls;
  7848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7849. ASSERT_TRUE(svr.is_valid());
  7850. svr.Get("/test", [](const Request &, Response &res) {
  7851. res.set_content("ok", "text/plain");
  7852. });
  7853. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7854. auto se = detail::scope_exit([&] {
  7855. svr.stop();
  7856. t.join();
  7857. });
  7858. svr.wait_until_ready();
  7859. SSLClient cli(HOST, PORT);
  7860. cli.enable_server_certificate_verification(false);
  7861. cli.set_connection_timeout(30);
  7862. bool serial_checked = false;
  7863. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7864. if (ctx.cert) {
  7865. std::string serial = ctx.serial();
  7866. EXPECT_FALSE(serial.empty());
  7867. // Serial should be a hex string
  7868. for (char c : serial) {
  7869. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  7870. (c >= 'a' && c <= 'f'));
  7871. }
  7872. serial_checked = true;
  7873. }
  7874. return true;
  7875. });
  7876. auto res = cli.Get("/test");
  7877. ASSERT_TRUE(res);
  7878. EXPECT_TRUE(serial_checked);
  7879. }
  7880. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7881. // Test 1: Valid CA file - no error should be recorded
  7882. {
  7883. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7884. CLIENT_CA_CERT_FILE);
  7885. ASSERT_TRUE(svr.is_valid());
  7886. // With valid setup, last_ssl_error should be 0
  7887. EXPECT_EQ(0, svr.ssl_last_error());
  7888. }
  7889. // Test 2: Invalid CA file content
  7890. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7891. {
  7892. // Create a temporary file with completely invalid content
  7893. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7894. {
  7895. std::ofstream ofs(temp_invalid_ca);
  7896. ofs << "This is not a certificate file at all\n";
  7897. ofs << "Just plain text content\n";
  7898. }
  7899. // Create server with invalid CA file
  7900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7901. // Clean up temporary file
  7902. std::remove(temp_invalid_ca);
  7903. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7904. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7905. // Note: SSL_CTX_load_verify_locations typically fails first,
  7906. // but our error handling code path is still exercised
  7907. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7908. }
  7909. }
  7910. TEST(VerifyCallbackTest, VerifyContextFields) {
  7911. using namespace httplib::tls;
  7912. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7913. ASSERT_TRUE(svr.is_valid());
  7914. svr.Get("/test", [](const Request &, Response &res) {
  7915. res.set_content("ok", "text/plain");
  7916. });
  7917. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7918. auto se = detail::scope_exit([&] {
  7919. svr.stop();
  7920. t.join();
  7921. });
  7922. svr.wait_until_ready();
  7923. SSLClient cli(HOST, PORT);
  7924. cli.enable_server_certificate_verification(false);
  7925. cli.set_connection_timeout(30);
  7926. int callback_count = 0;
  7927. bool saw_leaf_cert = false;
  7928. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7929. if (ctx.cert) {
  7930. callback_count++;
  7931. // We should see at least one certificate (the leaf)
  7932. std::string cn = ctx.subject_cn();
  7933. if (!cn.empty()) { saw_leaf_cert = true; }
  7934. // Verify context fields are populated
  7935. EXPECT_NE(ctx.session, nullptr);
  7936. EXPECT_GE(ctx.depth, 0);
  7937. }
  7938. return true;
  7939. });
  7940. auto res = cli.Get("/test");
  7941. ASSERT_TRUE(res);
  7942. EXPECT_GT(callback_count, 0);
  7943. EXPECT_TRUE(saw_leaf_cert);
  7944. }
  7945. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  7946. using httplib::tls::TlsError;
  7947. // Test that verify_error_to_string returns empty for success
  7948. std::string success_str = TlsError::verify_error_to_string(0);
  7949. EXPECT_TRUE(success_str.empty());
  7950. // Test that verify_error_to_string returns non-empty for error codes
  7951. // Using a common error code (certificate expired)
  7952. std::string error_str =
  7953. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  7954. EXPECT_FALSE(error_str.empty());
  7955. }
  7956. TEST(SessionVerifierTest, CertificateAccepted) {
  7957. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7958. ASSERT_TRUE(svr.is_valid());
  7959. svr.Get("/test", [](const Request &, Response &res) {
  7960. res.set_content("ok", "text/plain");
  7961. });
  7962. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7963. auto se = detail::scope_exit([&] {
  7964. svr.stop();
  7965. t.join();
  7966. });
  7967. svr.wait_until_ready();
  7968. SSLClient cli(HOST, PORT);
  7969. cli.enable_server_certificate_verification(false);
  7970. cli.set_connection_timeout(30);
  7971. bool callback_called = false;
  7972. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  7973. EXPECT_NE(session, nullptr);
  7974. callback_called = true;
  7975. return SSLVerifierResponse::CertificateAccepted;
  7976. });
  7977. auto res = cli.Get("/test");
  7978. ASSERT_TRUE(res);
  7979. EXPECT_EQ(200, res->status);
  7980. EXPECT_TRUE(callback_called);
  7981. }
  7982. TEST(SessionVerifierTest, CertificateRejected) {
  7983. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7984. ASSERT_TRUE(svr.is_valid());
  7985. svr.Get("/test", [](const Request &, Response &res) {
  7986. res.set_content("ok", "text/plain");
  7987. });
  7988. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7989. auto se = detail::scope_exit([&] {
  7990. svr.stop();
  7991. t.join();
  7992. });
  7993. svr.wait_until_ready();
  7994. SSLClient cli(HOST, PORT);
  7995. cli.enable_server_certificate_verification(false);
  7996. cli.set_connection_timeout(30);
  7997. bool callback_called = false;
  7998. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  7999. EXPECT_NE(session, nullptr);
  8000. callback_called = true;
  8001. return SSLVerifierResponse::CertificateRejected;
  8002. });
  8003. auto res = cli.Get("/test");
  8004. EXPECT_FALSE(res);
  8005. EXPECT_TRUE(callback_called);
  8006. }
  8007. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8009. ASSERT_TRUE(svr.is_valid());
  8010. svr.Get("/test", [](const Request &, Response &res) {
  8011. res.set_content("ok", "text/plain");
  8012. });
  8013. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8014. auto se = detail::scope_exit([&] {
  8015. svr.stop();
  8016. t.join();
  8017. });
  8018. svr.wait_until_ready();
  8019. // NoDecisionMade with verification disabled should succeed (no default check)
  8020. SSLClient cli(HOST, PORT);
  8021. cli.enable_server_certificate_verification(false);
  8022. cli.set_connection_timeout(30);
  8023. bool callback_called = false;
  8024. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8025. EXPECT_NE(session, nullptr);
  8026. callback_called = true;
  8027. return SSLVerifierResponse::NoDecisionMade;
  8028. });
  8029. auto res = cli.Get("/test");
  8030. ASSERT_TRUE(res);
  8031. EXPECT_EQ(200, res->status);
  8032. EXPECT_TRUE(callback_called);
  8033. }
  8034. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8035. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8036. ASSERT_TRUE(svr.is_valid());
  8037. svr.Get("/test", [](const Request &, Response &res) {
  8038. res.set_content("ok", "text/plain");
  8039. });
  8040. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8041. auto se = detail::scope_exit([&] {
  8042. svr.stop();
  8043. t.join();
  8044. });
  8045. svr.wait_until_ready();
  8046. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8047. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8048. // so we only check that the request fails, not whether the callback was
  8049. // called.
  8050. SSLClient cli(HOST, PORT);
  8051. cli.enable_server_certificate_verification(true);
  8052. cli.set_connection_timeout(30);
  8053. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8054. EXPECT_NE(session, nullptr);
  8055. return SSLVerifierResponse::NoDecisionMade;
  8056. });
  8057. auto res = cli.Get("/test");
  8058. EXPECT_FALSE(res);
  8059. }
  8060. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8061. // Test SSL server using PemMemory constructor with client CA certificates
  8062. // Read PEM files
  8063. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8064. read_file(SERVER_CERT_FILE, server_cert_pem);
  8065. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8066. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8067. // Create SSLServer with PemMemory constructor including client CA
  8068. SSLServer::PemMemory server_pem = {
  8069. server_cert_pem.c_str(),
  8070. server_cert_pem.size(),
  8071. server_key_pem.c_str(),
  8072. server_key_pem.size(),
  8073. client_ca_pem.c_str(),
  8074. client_ca_pem.size(),
  8075. nullptr // no password for server key
  8076. };
  8077. SSLServer svr(server_pem);
  8078. ASSERT_TRUE(svr.is_valid());
  8079. // No SSL error should be recorded for valid setup
  8080. EXPECT_EQ(0, svr.ssl_last_error());
  8081. // Set up server endpoints
  8082. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8083. res.set_content("ok", "text/plain");
  8084. });
  8085. // Start server in a thread
  8086. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8087. svr.wait_until_ready();
  8088. // Connect with client certificate (using constructor with paths)
  8089. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8090. cli.enable_server_certificate_verification(false);
  8091. auto res = cli.Get("/test-pem-ca");
  8092. ASSERT_TRUE(res);
  8093. EXPECT_EQ(200, res->status);
  8094. EXPECT_EQ("ok", res->body);
  8095. svr.stop();
  8096. server_thread.join();
  8097. }
  8098. #endif
  8099. #ifdef _WIN32
  8100. TEST(CleanupTest, WSACleanup) {
  8101. int ret = WSACleanup();
  8102. ASSERT_EQ(0, ret);
  8103. }
  8104. #endif
  8105. #ifndef CPPHTTPLIB_SSL_ENABLED
  8106. TEST(NoSSLSupport, SimpleInterface) {
  8107. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8108. }
  8109. #endif
  8110. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8111. TEST(InvalidScheme, SimpleInterface) {
  8112. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8113. }
  8114. #endif
  8115. TEST(NoScheme, SimpleInterface) {
  8116. Client cli("yahoo.com:80");
  8117. ASSERT_TRUE(cli.is_valid());
  8118. }
  8119. TEST(SendAPI, SimpleInterface_Online) {
  8120. Client cli("http://yahoo.com");
  8121. Request req;
  8122. req.method = "GET";
  8123. req.path = "/";
  8124. auto res = cli.send(req);
  8125. ASSERT_TRUE(res);
  8126. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8127. }
  8128. TEST(SendAPI, WithParamsInRequest) {
  8129. Server svr;
  8130. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8131. EXPECT_TRUE(req.has_param("test"));
  8132. EXPECT_EQ("test_value", req.get_param_value("test"));
  8133. });
  8134. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8135. auto se = detail::scope_exit([&] {
  8136. svr.stop();
  8137. t.join();
  8138. ASSERT_FALSE(svr.is_running());
  8139. });
  8140. svr.wait_until_ready();
  8141. Client cli(HOST, PORT);
  8142. {
  8143. Request req;
  8144. req.method = "GET";
  8145. req.path = "/";
  8146. req.params.emplace("test", "test_value");
  8147. auto res = cli.send(req);
  8148. ASSERT_TRUE(res);
  8149. }
  8150. {
  8151. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8152. ASSERT_TRUE(res);
  8153. }
  8154. }
  8155. TEST(ClientImplMethods, GetSocketTest) {
  8156. httplib::Server svr;
  8157. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8158. res.status = StatusCode::OK_200;
  8159. });
  8160. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  8161. auto se = detail::scope_exit([&] {
  8162. svr.stop();
  8163. thread.join();
  8164. ASSERT_FALSE(svr.is_running());
  8165. });
  8166. svr.wait_until_ready();
  8167. {
  8168. httplib::Client cli("http://127.0.0.1:3333");
  8169. cli.set_keep_alive(true);
  8170. // Use the behavior of cpp-httplib of opening the connection
  8171. // only when the first request happens. If that changes,
  8172. // this test would be obsolete.
  8173. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8174. // This also implicitly tests the server. But other tests would fail much
  8175. // earlier than this one to be considered.
  8176. auto res = cli.Get("/");
  8177. ASSERT_TRUE(res);
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8180. }
  8181. }
  8182. // Disabled due to out-of-memory problem on GitHub Actions
  8183. #ifdef _WIN64
  8184. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8185. // allocate content size larger than 2GB in memory
  8186. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8187. char *content = (char *)malloc(content_size);
  8188. ASSERT_TRUE(content);
  8189. Server svr;
  8190. svr.Get("/foo",
  8191. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8192. res.set_content(content, content_size, "application/octet-stream");
  8193. });
  8194. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8195. auto se = detail::scope_exit([&] {
  8196. svr.stop();
  8197. listen_thread.join();
  8198. if (content) free(content);
  8199. ASSERT_FALSE(svr.is_running());
  8200. });
  8201. svr.wait_until_ready();
  8202. Client cli(HOST, PORT);
  8203. auto res = cli.Get("/foo");
  8204. ASSERT_TRUE(res);
  8205. EXPECT_EQ(StatusCode::OK_200, res->status);
  8206. EXPECT_EQ(content_size, res->body.length());
  8207. }
  8208. #endif
  8209. #ifdef CPPHTTPLIB_SSL_ENABLED
  8210. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8211. Client cli("http://yahoo.com");
  8212. auto res = cli.Get("/");
  8213. ASSERT_TRUE(res);
  8214. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8215. cli.set_follow_location(true);
  8216. res = cli.Get("/");
  8217. ASSERT_TRUE(res);
  8218. EXPECT_EQ(StatusCode::OK_200, res->status);
  8219. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8220. }
  8221. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8222. Client cli("https://yahoo.com");
  8223. auto res = cli.Get("/");
  8224. ASSERT_TRUE(res);
  8225. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8226. cli.set_follow_location(true);
  8227. res = cli.Get("/");
  8228. ASSERT_TRUE(res);
  8229. EXPECT_EQ(StatusCode::OK_200, res->status);
  8230. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8231. }
  8232. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8233. Client cli("https://yahoo.com");
  8234. auto res = cli.Get("/");
  8235. ASSERT_TRUE(res);
  8236. ASSERT_FALSE(!res);
  8237. ASSERT_TRUE(res);
  8238. ASSERT_FALSE(res == nullptr);
  8239. ASSERT_TRUE(res != nullptr);
  8240. EXPECT_EQ(Error::Success, res.error());
  8241. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8242. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8243. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8244. cli.set_follow_location(true);
  8245. res = cli.Get("/");
  8246. ASSERT_TRUE(res);
  8247. EXPECT_EQ(Error::Success, res.error());
  8248. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8249. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8250. EXPECT_EQ(StatusCode::OK_200, res->status);
  8251. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8252. }
  8253. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8254. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8255. Client cli("https://cdnjs.cloudflare.com");
  8256. auto res =
  8257. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8258. ASSERT_TRUE(res);
  8259. EXPECT_EQ(StatusCode::OK_200, res->status);
  8260. EXPECT_EQ(287630U, res->body.size());
  8261. EXPECT_EQ("application/javascript; charset=utf-8",
  8262. res->get_header_value("Content-Type"));
  8263. }
  8264. #endif
  8265. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8266. #undef REDIR_HOST // Silence compiler warning
  8267. #define REDIR_HOST "https://httpbingo.org"
  8268. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8269. Client cli(REDIR_HOST);
  8270. cli.set_follow_location(true);
  8271. auto res =
  8272. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8273. ASSERT_TRUE(res);
  8274. EXPECT_EQ(StatusCode::OK_200, res->status);
  8275. }
  8276. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8277. Client cli(REDIR_HOST);
  8278. cli.set_follow_location(true);
  8279. Params params;
  8280. params.emplace("url", "http://example.com");
  8281. params.emplace("status_code", "302");
  8282. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8283. ASSERT_TRUE(res);
  8284. EXPECT_EQ(StatusCode::OK_200, res->status);
  8285. }
  8286. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8287. Client cli(REDIR_HOST);
  8288. cli.set_follow_location(true);
  8289. Params params;
  8290. params.emplace("url", "http://example.com");
  8291. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8292. ASSERT_TRUE(res);
  8293. EXPECT_EQ(StatusCode::OK_200, res->status);
  8294. }
  8295. TEST(HttpToHttpsRedirectTest, CertFile) {
  8296. Server svr;
  8297. ASSERT_TRUE(svr.is_valid());
  8298. svr.Get("/index", [&](const Request &, Response &res) {
  8299. res.set_redirect("https://127.0.0.1:1235/index");
  8300. svr.stop();
  8301. });
  8302. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8303. ASSERT_TRUE(ssl_svr.is_valid());
  8304. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8305. res.set_content("test", "text/plain");
  8306. ssl_svr.stop();
  8307. });
  8308. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8309. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8310. auto se = detail::scope_exit([&] {
  8311. t2.join();
  8312. t.join();
  8313. ASSERT_FALSE(svr.is_running());
  8314. });
  8315. svr.wait_until_ready();
  8316. ssl_svr.wait_until_ready();
  8317. Client cli("127.0.0.1", PORT);
  8318. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8319. cli.enable_server_certificate_verification(true);
  8320. cli.set_follow_location(true);
  8321. cli.set_connection_timeout(30);
  8322. auto res = cli.Get("/index");
  8323. ASSERT_TRUE(res);
  8324. ASSERT_EQ(StatusCode::OK_200, res->status);
  8325. }
  8326. TEST(SSLClientRedirectTest, CertFile) {
  8327. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8328. ASSERT_TRUE(ssl_svr1.is_valid());
  8329. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8330. res.set_redirect("https://127.0.0.1:1235/index");
  8331. ssl_svr1.stop();
  8332. });
  8333. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8334. ASSERT_TRUE(ssl_svr2.is_valid());
  8335. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8336. res.set_content("test", "text/plain");
  8337. ssl_svr2.stop();
  8338. });
  8339. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8340. thread t2 =
  8341. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8342. auto se = detail::scope_exit([&] {
  8343. t2.join();
  8344. t.join();
  8345. ASSERT_FALSE(ssl_svr1.is_running());
  8346. });
  8347. ssl_svr1.wait_until_ready();
  8348. ssl_svr2.wait_until_ready();
  8349. SSLClient cli("127.0.0.1", PORT);
  8350. std::string cert;
  8351. read_file(SERVER_CERT2_FILE, cert);
  8352. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8353. cli.enable_server_certificate_verification(true);
  8354. cli.set_follow_location(true);
  8355. cli.set_connection_timeout(30);
  8356. auto res = cli.Get("/index");
  8357. ASSERT_TRUE(res);
  8358. ASSERT_EQ(StatusCode::OK_200, res->status);
  8359. }
  8360. #endif
  8361. #ifdef CPPHTTPLIB_SSL_ENABLED
  8362. // Test that set_ca_cert_store() skips system certs (consistent with
  8363. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  8364. // should be trusted - system certs should NOT be loaded.
  8365. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  8366. // Load a specific cert that is NOT a system CA cert
  8367. std::string cert;
  8368. read_file(SERVER_CERT2_FILE, cert);
  8369. SSLClient cli("google.com");
  8370. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8371. cli.enable_server_certificate_verification(true);
  8372. // This should FAIL because:
  8373. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  8374. // 2. System certs should NOT be loaded when custom store is set
  8375. // If system certs WERE loaded, this would succeed
  8376. auto res = cli.Get("/");
  8377. ASSERT_FALSE(res);
  8378. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8379. }
  8380. TEST(MultipartFormDataTest, LargeData) {
  8381. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8382. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8383. const ContentReader &content_reader) {
  8384. if (req.is_multipart_form_data()) {
  8385. std::vector<FormData> items;
  8386. content_reader(
  8387. [&](const FormData &file) {
  8388. items.push_back(file);
  8389. return true;
  8390. },
  8391. [&](const char *data, size_t data_length) {
  8392. items.back().content.append(data, data_length);
  8393. return true;
  8394. });
  8395. EXPECT_TRUE(std::string(items[0].name) == "document");
  8396. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8397. EXPECT_TRUE(items[0].filename == "2MB_data");
  8398. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8399. EXPECT_TRUE(items[1].name == "hello");
  8400. EXPECT_TRUE(items[1].content == "world");
  8401. EXPECT_TRUE(items[1].filename == "");
  8402. EXPECT_TRUE(items[1].content_type == "");
  8403. } else {
  8404. std::string body;
  8405. content_reader([&](const char *data, size_t data_length) {
  8406. body.append(data, data_length);
  8407. return true;
  8408. });
  8409. }
  8410. });
  8411. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8412. auto se = detail::scope_exit([&] {
  8413. svr.stop();
  8414. t.join();
  8415. ASSERT_FALSE(svr.is_running());
  8416. });
  8417. svr.wait_until_ready();
  8418. {
  8419. std::string data(1024 * 1024 * 2, '.');
  8420. std::stringstream buffer;
  8421. buffer << data;
  8422. Client cli("https://localhost:8080");
  8423. cli.enable_server_certificate_verification(false);
  8424. UploadFormDataItems items{
  8425. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8426. {"hello", "world", "", ""},
  8427. };
  8428. auto res = cli.Post("/post", items);
  8429. ASSERT_TRUE(res);
  8430. ASSERT_EQ(StatusCode::OK_200, res->status);
  8431. }
  8432. }
  8433. TEST(MultipartFormDataTest, DataProviderItems) {
  8434. std::random_device seed_gen;
  8435. std::mt19937 random(seed_gen());
  8436. std::string rand1;
  8437. rand1.resize(1000);
  8438. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8439. std::string rand2;
  8440. rand2.resize(3000);
  8441. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8443. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8444. const ContentReader &content_reader) {
  8445. ASSERT_FALSE(req.is_multipart_form_data());
  8446. std::string body;
  8447. content_reader([&](const char *data, size_t data_length) {
  8448. body.append(data, data_length);
  8449. return true;
  8450. });
  8451. EXPECT_EQ(body, "");
  8452. });
  8453. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8454. const ContentReader &content_reader) {
  8455. ASSERT_TRUE(req.is_multipart_form_data());
  8456. std::vector<FormData> items;
  8457. content_reader(
  8458. [&](const FormData &file) {
  8459. items.push_back(file);
  8460. return true;
  8461. },
  8462. [&](const char *data, size_t data_length) {
  8463. items.back().content.append(data, data_length);
  8464. return true;
  8465. });
  8466. ASSERT_TRUE(items.size() == 2);
  8467. EXPECT_EQ(std::string(items[0].name), "name1");
  8468. EXPECT_EQ(items[0].content, "Testing123");
  8469. EXPECT_EQ(items[0].filename, "filename1");
  8470. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8471. EXPECT_EQ(items[1].name, "name2");
  8472. EXPECT_EQ(items[1].content, "Testing456");
  8473. EXPECT_EQ(items[1].filename, "");
  8474. EXPECT_EQ(items[1].content_type, "");
  8475. });
  8476. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8477. const ContentReader &content_reader) {
  8478. ASSERT_TRUE(req.is_multipart_form_data());
  8479. std::vector<FormData> items;
  8480. content_reader(
  8481. [&](const FormData &file) {
  8482. items.push_back(file);
  8483. return true;
  8484. },
  8485. [&](const char *data, size_t data_length) {
  8486. items.back().content.append(data, data_length);
  8487. return true;
  8488. });
  8489. ASSERT_TRUE(items.size() == 2);
  8490. EXPECT_EQ(items[0].name, "name3");
  8491. EXPECT_EQ(items[0].content, rand1);
  8492. EXPECT_EQ(items[0].filename, "filename3");
  8493. EXPECT_EQ(items[0].content_type, "");
  8494. EXPECT_EQ(items[1].name, "name4");
  8495. EXPECT_EQ(items[1].content, rand2);
  8496. EXPECT_EQ(items[1].filename, "filename4");
  8497. EXPECT_EQ(items[1].content_type, "");
  8498. });
  8499. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8500. const ContentReader &content_reader) {
  8501. ASSERT_TRUE(req.is_multipart_form_data());
  8502. std::vector<FormData> items;
  8503. content_reader(
  8504. [&](const FormData &file) {
  8505. items.push_back(file);
  8506. return true;
  8507. },
  8508. [&](const char *data, size_t data_length) {
  8509. items.back().content.append(data, data_length);
  8510. return true;
  8511. });
  8512. ASSERT_TRUE(items.size() == 4);
  8513. EXPECT_EQ(std::string(items[0].name), "name1");
  8514. EXPECT_EQ(items[0].content, "Testing123");
  8515. EXPECT_EQ(items[0].filename, "filename1");
  8516. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8517. EXPECT_EQ(items[1].name, "name2");
  8518. EXPECT_EQ(items[1].content, "Testing456");
  8519. EXPECT_EQ(items[1].filename, "");
  8520. EXPECT_EQ(items[1].content_type, "");
  8521. EXPECT_EQ(items[2].name, "name3");
  8522. EXPECT_EQ(items[2].content, rand1);
  8523. EXPECT_EQ(items[2].filename, "filename3");
  8524. EXPECT_EQ(items[2].content_type, "");
  8525. EXPECT_EQ(items[3].name, "name4");
  8526. EXPECT_EQ(items[3].content, rand2);
  8527. EXPECT_EQ(items[3].filename, "filename4");
  8528. EXPECT_EQ(items[3].content_type, "");
  8529. });
  8530. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8531. auto se = detail::scope_exit([&] {
  8532. svr.stop();
  8533. t.join();
  8534. ASSERT_FALSE(svr.is_running());
  8535. });
  8536. svr.wait_until_ready();
  8537. {
  8538. Client cli("https://localhost:8080");
  8539. cli.enable_server_certificate_verification(false);
  8540. UploadFormDataItems items{
  8541. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8542. {"name2", "Testing456", "", ""}, // not a file
  8543. };
  8544. {
  8545. auto res = cli.Post("/post-none", {}, {}, {});
  8546. ASSERT_TRUE(res);
  8547. ASSERT_EQ(StatusCode::OK_200, res->status);
  8548. }
  8549. FormDataProviderItems providers;
  8550. {
  8551. auto res =
  8552. cli.Post("/post-items", {}, items, providers); // empty providers
  8553. ASSERT_TRUE(res);
  8554. ASSERT_EQ(StatusCode::OK_200, res->status);
  8555. }
  8556. providers.push_back({"name3",
  8557. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8558. // test the offset is given correctly at each step
  8559. if (!offset)
  8560. sink.os.write(rand1.data(), 30);
  8561. else if (offset == 30)
  8562. sink.os.write(rand1.data() + 30, 300);
  8563. else if (offset == 330)
  8564. sink.os.write(rand1.data() + 330, 670);
  8565. else if (offset == rand1.size())
  8566. sink.done();
  8567. return true;
  8568. },
  8569. "filename3",
  8570. {}});
  8571. providers.push_back({"name4",
  8572. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8573. // test the offset is given correctly at each step
  8574. if (!offset)
  8575. sink.os.write(rand2.data(), 2000);
  8576. else if (offset == 2000)
  8577. sink.os.write(rand2.data() + 2000, 1);
  8578. else if (offset == 2001)
  8579. sink.os.write(rand2.data() + 2001, 999);
  8580. else if (offset == rand2.size())
  8581. sink.done();
  8582. return true;
  8583. },
  8584. "filename4",
  8585. {}});
  8586. {
  8587. auto res = cli.Post("/post-providers", {}, {}, providers);
  8588. ASSERT_TRUE(res);
  8589. ASSERT_EQ(StatusCode::OK_200, res->status);
  8590. }
  8591. {
  8592. auto res = cli.Post("/post-both", {}, items, providers);
  8593. ASSERT_TRUE(res);
  8594. ASSERT_EQ(StatusCode::OK_200, res->status);
  8595. }
  8596. }
  8597. }
  8598. TEST(MultipartFormDataTest, BadHeader) {
  8599. Server svr;
  8600. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8601. res.set_content("ok", "text/plain");
  8602. });
  8603. thread t = thread([&] { svr.listen(HOST, PORT); });
  8604. auto se = detail::scope_exit([&] {
  8605. svr.stop();
  8606. t.join();
  8607. ASSERT_FALSE(svr.is_running());
  8608. });
  8609. svr.wait_until_ready();
  8610. const std::string body =
  8611. "This is the preamble. It is to be ignored, though it\r\n"
  8612. "is a handy place for composition agents to include an\r\n"
  8613. "explanatory note to non-MIME conformant readers.\r\n"
  8614. "\r\n"
  8615. "\r\n"
  8616. "--simple boundary\r\n"
  8617. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8618. ": BAD...\r\n"
  8619. "\r\n"
  8620. "value1\r\n"
  8621. "--simple boundary\r\n"
  8622. "Content-Disposition: form-data; name=\"field2\"; "
  8623. "filename=\"example.txt\"\r\n"
  8624. "\r\n"
  8625. "value2\r\n"
  8626. "--simple boundary--\r\n"
  8627. "This is the epilogue. It is also to be ignored.\r\n";
  8628. std::string content_type =
  8629. R"(multipart/form-data; boundary="simple boundary")";
  8630. Client cli(HOST, PORT);
  8631. auto res = cli.Post("/post", body, content_type.c_str());
  8632. ASSERT_TRUE(res);
  8633. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8634. }
  8635. TEST(MultipartFormDataTest, WithPreamble) {
  8636. Server svr;
  8637. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8638. res.set_content("ok", "text/plain");
  8639. });
  8640. thread t = thread([&] { svr.listen(HOST, PORT); });
  8641. auto se = detail::scope_exit([&] {
  8642. svr.stop();
  8643. t.join();
  8644. ASSERT_FALSE(svr.is_running());
  8645. });
  8646. svr.wait_until_ready();
  8647. const std::string body =
  8648. "This is the preamble. It is to be ignored, though it\r\n"
  8649. "is a handy place for composition agents to include an\r\n"
  8650. "explanatory note to non-MIME conformant readers.\r\n"
  8651. "\r\n"
  8652. "\r\n"
  8653. "--simple boundary\r\n"
  8654. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8655. "\r\n"
  8656. "value1\r\n"
  8657. "--simple boundary\r\n"
  8658. "Content-Disposition: form-data; name=\"field2\"; "
  8659. "filename=\"example.txt\"\r\n"
  8660. "\r\n"
  8661. "value2\r\n"
  8662. "--simple boundary--\r\n"
  8663. "This is the epilogue. It is also to be ignored.\r\n";
  8664. std::string content_type =
  8665. R"(multipart/form-data; boundary="simple boundary")";
  8666. Client cli(HOST, PORT);
  8667. auto res = cli.Post("/post", body, content_type.c_str());
  8668. ASSERT_TRUE(res);
  8669. EXPECT_EQ(StatusCode::OK_200, res->status);
  8670. }
  8671. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8672. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8673. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8674. const ContentReader &content_reader) {
  8675. if (req.is_multipart_form_data()) {
  8676. std::vector<FormData> items;
  8677. content_reader(
  8678. [&](const FormData &file) {
  8679. items.push_back(file);
  8680. return true;
  8681. },
  8682. [&](const char *data, size_t data_length) {
  8683. items.back().content.append(data, data_length);
  8684. return true;
  8685. });
  8686. EXPECT_TRUE(std::string(items[0].name) == "document");
  8687. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8688. EXPECT_TRUE(items[0].filename == "2MB_data");
  8689. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8690. EXPECT_TRUE(items[1].name == "hello");
  8691. EXPECT_TRUE(items[1].content == "world");
  8692. EXPECT_TRUE(items[1].filename == "");
  8693. EXPECT_TRUE(items[1].content_type == "");
  8694. } else {
  8695. std::string body;
  8696. content_reader([&](const char *data, size_t data_length) {
  8697. body.append(data, data_length);
  8698. return true;
  8699. });
  8700. }
  8701. });
  8702. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8703. auto se = detail::scope_exit([&] {
  8704. svr.stop();
  8705. t.join();
  8706. ASSERT_FALSE(svr.is_running());
  8707. });
  8708. svr.wait_until_ready();
  8709. {
  8710. std::string data(1024 * 1024 * 2, '.');
  8711. std::stringstream buffer;
  8712. buffer << data;
  8713. Client cli("https://localhost:8080");
  8714. cli.enable_server_certificate_verification(false);
  8715. UploadFormDataItems items{
  8716. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8717. {"hello", "world", "", ""},
  8718. };
  8719. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8720. ASSERT_TRUE(res);
  8721. ASSERT_EQ(StatusCode::OK_200, res->status);
  8722. }
  8723. }
  8724. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8725. std::string data(1024 * 1024 * 2, '&');
  8726. std::stringstream buffer;
  8727. buffer << data;
  8728. Client cli("https://localhost:8080");
  8729. UploadFormDataItems items{
  8730. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8731. {"hello", "world", "", ""},
  8732. };
  8733. for (const char &c : " \t\r\n") {
  8734. auto res =
  8735. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8736. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8737. ASSERT_FALSE(res);
  8738. }
  8739. }
  8740. TEST(MultipartFormDataTest, PutFormData) {
  8741. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8742. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8743. const ContentReader &content_reader) {
  8744. if (req.is_multipart_form_data()) {
  8745. std::vector<FormData> items;
  8746. content_reader(
  8747. [&](const FormData &file) {
  8748. items.push_back(file);
  8749. return true;
  8750. },
  8751. [&](const char *data, size_t data_length) {
  8752. items.back().content.append(data, data_length);
  8753. return true;
  8754. });
  8755. EXPECT_TRUE(std::string(items[0].name) == "document");
  8756. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8757. EXPECT_TRUE(items[0].filename == "2MB_data");
  8758. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8759. EXPECT_TRUE(items[1].name == "hello");
  8760. EXPECT_TRUE(items[1].content == "world");
  8761. EXPECT_TRUE(items[1].filename == "");
  8762. EXPECT_TRUE(items[1].content_type == "");
  8763. } else {
  8764. std::string body;
  8765. content_reader([&](const char *data, size_t data_length) {
  8766. body.append(data, data_length);
  8767. return true;
  8768. });
  8769. }
  8770. });
  8771. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8772. auto se = detail::scope_exit([&] {
  8773. svr.stop();
  8774. t.join();
  8775. ASSERT_FALSE(svr.is_running());
  8776. });
  8777. svr.wait_until_ready();
  8778. {
  8779. std::string data(1024 * 1024 * 2, '&');
  8780. std::stringstream buffer;
  8781. buffer << data;
  8782. Client cli("https://localhost:8080");
  8783. cli.enable_server_certificate_verification(false);
  8784. UploadFormDataItems items{
  8785. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8786. {"hello", "world", "", ""},
  8787. };
  8788. auto res = cli.Put("/put", items);
  8789. ASSERT_TRUE(res);
  8790. ASSERT_EQ(StatusCode::OK_200, res->status);
  8791. }
  8792. }
  8793. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8794. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8795. svr.Put("/put_customboundary",
  8796. [&](const Request &req, const Response & /*res*/,
  8797. const ContentReader &content_reader) {
  8798. if (req.is_multipart_form_data()) {
  8799. std::vector<FormData> items;
  8800. content_reader(
  8801. [&](const FormData &file) {
  8802. items.push_back(file);
  8803. return true;
  8804. },
  8805. [&](const char *data, size_t data_length) {
  8806. items.back().content.append(data, data_length);
  8807. return true;
  8808. });
  8809. EXPECT_TRUE(std::string(items[0].name) == "document");
  8810. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8811. EXPECT_TRUE(items[0].filename == "2MB_data");
  8812. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8813. EXPECT_TRUE(items[1].name == "hello");
  8814. EXPECT_TRUE(items[1].content == "world");
  8815. EXPECT_TRUE(items[1].filename == "");
  8816. EXPECT_TRUE(items[1].content_type == "");
  8817. } else {
  8818. std::string body;
  8819. content_reader([&](const char *data, size_t data_length) {
  8820. body.append(data, data_length);
  8821. return true;
  8822. });
  8823. }
  8824. });
  8825. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8826. auto se = detail::scope_exit([&] {
  8827. svr.stop();
  8828. t.join();
  8829. ASSERT_FALSE(svr.is_running());
  8830. });
  8831. svr.wait_until_ready();
  8832. {
  8833. std::string data(1024 * 1024 * 2, '&');
  8834. std::stringstream buffer;
  8835. buffer << data;
  8836. Client cli("https://localhost:8080");
  8837. cli.enable_server_certificate_verification(false);
  8838. UploadFormDataItems items{
  8839. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8840. {"hello", "world", "", ""},
  8841. };
  8842. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8843. ASSERT_TRUE(res);
  8844. ASSERT_EQ(StatusCode::OK_200, res->status);
  8845. }
  8846. }
  8847. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8848. std::string data(1024 * 1024 * 2, '&');
  8849. std::stringstream buffer;
  8850. buffer << data;
  8851. Client cli("https://localhost:8080");
  8852. cli.enable_server_certificate_verification(false);
  8853. UploadFormDataItems items{
  8854. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8855. {"hello", "world", "", ""},
  8856. };
  8857. for (const char &c : " \t\r\n") {
  8858. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8859. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8860. ASSERT_FALSE(res);
  8861. }
  8862. }
  8863. TEST(MultipartFormDataTest, AlternateFilename) {
  8864. auto handled = false;
  8865. Server svr;
  8866. svr.Post("/test", [&](const Request &req, Response &res) {
  8867. ASSERT_EQ(2u, req.form.files.size());
  8868. ASSERT_EQ(1u, req.form.fields.size());
  8869. // Test files
  8870. const auto &file1 = req.form.get_file("file1");
  8871. ASSERT_EQ("file1", file1.name);
  8872. ASSERT_EQ("A.txt", file1.filename);
  8873. ASSERT_EQ("text/plain", file1.content_type);
  8874. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8875. const auto &file2 = req.form.get_file("file2");
  8876. ASSERT_EQ("file2", file2.name);
  8877. ASSERT_EQ("a.html", file2.filename);
  8878. ASSERT_EQ("text/html", file2.content_type);
  8879. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8880. file2.content);
  8881. // Test text field
  8882. const auto &text = req.form.get_field("text");
  8883. ASSERT_EQ("text default", text);
  8884. res.set_content("ok", "text/plain");
  8885. handled = true;
  8886. });
  8887. thread t = thread([&] { svr.listen(HOST, PORT); });
  8888. auto se = detail::scope_exit([&] {
  8889. svr.stop();
  8890. t.join();
  8891. ASSERT_FALSE(svr.is_running());
  8892. ASSERT_TRUE(handled);
  8893. });
  8894. svr.wait_until_ready();
  8895. auto req = "POST /test HTTP/1.1\r\n"
  8896. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8897. "Content-Length: 399\r\n"
  8898. "\r\n"
  8899. "----------\r\n"
  8900. "Content-Disposition: form-data; name=\"text\"\r\n"
  8901. "\r\n"
  8902. "text default\r\n"
  8903. "----------\r\n"
  8904. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8905. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8906. "Content-Type: text/plain\r\n"
  8907. "\r\n"
  8908. "Content of a.txt.\r\n"
  8909. "\r\n"
  8910. "----------\r\n"
  8911. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8912. "\"a.html\"\r\n"
  8913. "Content-Type: text/html\r\n"
  8914. "\r\n"
  8915. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8916. "\r\n"
  8917. "------------\r\n";
  8918. ASSERT_TRUE(send_request(1, req));
  8919. }
  8920. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8921. auto handled = false;
  8922. Server svr;
  8923. svr.Post("/test", [&](const Request &req, Response &) {
  8924. ASSERT_EQ(2u, req.form.fields.size());
  8925. const auto &text1 = req.form.get_field("text1");
  8926. ASSERT_EQ("text1", text1);
  8927. const auto &text2 = req.form.get_field("text2");
  8928. ASSERT_EQ("text2", text2);
  8929. handled = true;
  8930. });
  8931. thread t = thread([&] { svr.listen(HOST, PORT); });
  8932. auto se = detail::scope_exit([&] {
  8933. svr.stop();
  8934. t.join();
  8935. ASSERT_FALSE(svr.is_running());
  8936. ASSERT_TRUE(handled);
  8937. });
  8938. svr.wait_until_ready();
  8939. auto req = "POST /test HTTP/1.1\r\n"
  8940. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8941. "Content-Length: 146\r\n"
  8942. "\r\n----------\r\n"
  8943. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8944. "\r\n"
  8945. "text1"
  8946. "\r\n----------\r\n"
  8947. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8948. "\r\n"
  8949. "text2"
  8950. "\r\n------------";
  8951. std::string response;
  8952. ASSERT_TRUE(send_request(1, req, &response));
  8953. ASSERT_EQ("200", response.substr(9, 3));
  8954. }
  8955. TEST(MultipartFormDataTest, ContentLength) {
  8956. auto handled = false;
  8957. Server svr;
  8958. svr.Post("/test", [&](const Request &req, Response &) {
  8959. ASSERT_EQ(2u, req.form.fields.size());
  8960. const auto &text1 = req.form.get_field("text1");
  8961. ASSERT_EQ("text1", text1);
  8962. const auto &text2 = req.form.get_field("text2");
  8963. ASSERT_EQ("text2", text2);
  8964. handled = true;
  8965. });
  8966. thread t = thread([&] { svr.listen(HOST, PORT); });
  8967. auto se = detail::scope_exit([&] {
  8968. svr.stop();
  8969. t.join();
  8970. ASSERT_FALSE(svr.is_running());
  8971. ASSERT_TRUE(handled);
  8972. });
  8973. svr.wait_until_ready();
  8974. auto req = "POST /test HTTP/1.1\r\n"
  8975. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8976. "Content-Length: 167\r\n"
  8977. "\r\n----------\r\n"
  8978. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8979. "Content-Length: 5\r\n"
  8980. "\r\n"
  8981. "text1"
  8982. "\r\n----------\r\n"
  8983. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8984. "\r\n"
  8985. "text2"
  8986. "\r\n------------\r\n";
  8987. std::string response;
  8988. ASSERT_TRUE(send_request(1, req, &response));
  8989. ASSERT_EQ("200", response.substr(9, 3));
  8990. }
  8991. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8992. auto handled = false;
  8993. Server svr;
  8994. svr.Post("/test", [&](const Request &req, Response &) {
  8995. ASSERT_EQ(2u, req.form.fields.size());
  8996. const auto &text1 = req.form.get_field("text1");
  8997. ASSERT_EQ("text1", text1);
  8998. // TODO: Add header access for text fields if needed
  8999. const auto &text2 = req.form.get_field("text2");
  9000. ASSERT_EQ("text2", text2);
  9001. // TODO: Header access for text fields needs to be implemented
  9002. // auto &headers = it->second.headers;
  9003. // ASSERT_EQ(3U, headers.size());
  9004. // auto custom_header = headers.find("x-whatever");
  9005. // ASSERT_TRUE(custom_header != headers.end());
  9006. // ASSERT_NE("customvalue", custom_header->second);
  9007. // ASSERT_EQ("CustomValue", custom_header->second);
  9008. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9009. handled = true;
  9010. });
  9011. thread t = thread([&] { svr.listen(HOST, PORT); });
  9012. auto se = detail::scope_exit([&] {
  9013. svr.stop();
  9014. t.join();
  9015. ASSERT_FALSE(svr.is_running());
  9016. ASSERT_TRUE(handled);
  9017. });
  9018. svr.wait_until_ready();
  9019. auto req = "POST /test HTTP/1.1\r\n"
  9020. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9021. "Content-Length: 232\r\n"
  9022. "\r\n----------\r\n"
  9023. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9024. "Content-Length: 5\r\n"
  9025. "X-Test: 1\r\n"
  9026. "\r\n"
  9027. "text1"
  9028. "\r\n----------\r\n"
  9029. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9030. "Content-Type: text/plain\r\n"
  9031. "X-Whatever: CustomValue\r\n"
  9032. "\r\n"
  9033. "text2"
  9034. "\r\n------------\r\n"
  9035. "That should be disregarded. Not even read";
  9036. std::string response;
  9037. ASSERT_TRUE(send_request(1, req, &response));
  9038. ASSERT_EQ("200", response.substr(9, 3));
  9039. }
  9040. TEST(MultipartFormDataTest, LargeHeader) {
  9041. auto handled = false;
  9042. Server svr;
  9043. svr.Post("/test", [&](const Request &req, Response &) {
  9044. ASSERT_EQ(1u, req.form.fields.size());
  9045. const auto &text = req.form.get_field("name1");
  9046. ASSERT_EQ("text1", text);
  9047. handled = true;
  9048. });
  9049. thread t = thread([&] { svr.listen(HOST, PORT); });
  9050. auto se = detail::scope_exit([&] {
  9051. svr.stop();
  9052. t.join();
  9053. ASSERT_FALSE(svr.is_running());
  9054. ASSERT_TRUE(handled);
  9055. });
  9056. svr.wait_until_ready();
  9057. auto boundary = std::string("cpp-httplib-multipart-data");
  9058. std::string content = "--" + boundary +
  9059. "\r\n"
  9060. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9061. "\r\n"
  9062. "text1\r\n"
  9063. "--" +
  9064. boundary + "--\r\n";
  9065. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9066. "Content-Type: multipart/form-data;boundary=" +
  9067. boundary +
  9068. "\r\n"
  9069. "Content-Length: " +
  9070. std::to_string(content.size()) +
  9071. "\r\n"
  9072. "Dummy-Header: ";
  9073. std::string header_suffix = "\r\n"
  9074. "\r\n";
  9075. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9076. size_t header_dummy_size =
  9077. read_buff_size -
  9078. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9079. auto header_dummy = std::string(header_dummy_size, '@');
  9080. auto req = header_prefix + header_dummy + header_suffix + content;
  9081. std::string response;
  9082. ASSERT_TRUE(send_request(1, req, &response));
  9083. ASSERT_EQ("200", response.substr(9, 3));
  9084. }
  9085. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  9086. static constexpr unsigned int number_of_tasks{1000000};
  9087. std::atomic_uint count{0};
  9088. std::unique_ptr<TaskQueue> task_queue{
  9089. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  9090. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9091. auto queued = task_queue->enqueue(
  9092. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  9093. EXPECT_TRUE(queued);
  9094. }
  9095. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9096. task_queue->shutdown();
  9097. #else
  9098. EXPECT_NO_THROW(task_queue->shutdown());
  9099. #endif
  9100. EXPECT_EQ(number_of_tasks, count.load());
  9101. }
  9102. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  9103. static constexpr unsigned int number_of_tasks{1000000};
  9104. static constexpr unsigned int qlimit{2};
  9105. unsigned int queued_count{0};
  9106. std::atomic_uint count{0};
  9107. std::unique_ptr<TaskQueue> task_queue{
  9108. new ThreadPool{/*num_threads=*/1, qlimit}};
  9109. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9110. if (task_queue->enqueue(
  9111. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  9112. queued_count++;
  9113. }
  9114. }
  9115. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9116. task_queue->shutdown();
  9117. #else
  9118. EXPECT_NO_THROW(task_queue->shutdown());
  9119. #endif
  9120. EXPECT_EQ(queued_count, count.load());
  9121. EXPECT_TRUE(queued_count <= number_of_tasks);
  9122. EXPECT_TRUE(queued_count >= qlimit);
  9123. }
  9124. TEST(TaskQueueTest, MaxQueuedRequests) {
  9125. static constexpr unsigned int qlimit{3};
  9126. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  9127. std::condition_variable sem_cv;
  9128. std::mutex sem_mtx;
  9129. int credits = 0;
  9130. bool queued;
  9131. /* Fill up the queue with tasks that will block until we give them credits to
  9132. * complete. */
  9133. for (unsigned int n = 0; n <= qlimit;) {
  9134. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  9135. std::unique_lock<std::mutex> lock(sem_mtx);
  9136. while (credits <= 0) {
  9137. sem_cv.wait(lock);
  9138. }
  9139. /* Consume the credit and signal the test code if they are all gone. */
  9140. if (--credits == 0) { sem_cv.notify_one(); }
  9141. });
  9142. if (n < qlimit) {
  9143. /* The first qlimit enqueues must succeed. */
  9144. EXPECT_TRUE(queued);
  9145. } else {
  9146. /* The last one will succeed only when the worker thread
  9147. * starts and dequeues the first blocking task. Although
  9148. * not necessary for the correctness of this test, we sleep for
  9149. * a short while to avoid busy waiting. */
  9150. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  9151. }
  9152. if (queued) { n++; }
  9153. }
  9154. /* Further enqueues must fail since the queue is full. */
  9155. for (auto i = 0; i < 4; i++) {
  9156. queued = task_queue->enqueue([] {});
  9157. EXPECT_FALSE(queued);
  9158. }
  9159. /* Give the credits to allow the previous tasks to complete. */
  9160. {
  9161. std::unique_lock<std::mutex> lock(sem_mtx);
  9162. credits += qlimit + 1;
  9163. }
  9164. sem_cv.notify_all();
  9165. /* Wait for all the credits to be consumed. */
  9166. {
  9167. std::unique_lock<std::mutex> lock(sem_mtx);
  9168. while (credits > 0) {
  9169. sem_cv.wait(lock);
  9170. }
  9171. }
  9172. /* Check that we are able again to enqueue at least qlimit tasks. */
  9173. for (unsigned int i = 0; i < qlimit; i++) {
  9174. queued = task_queue->enqueue([] {});
  9175. EXPECT_TRUE(queued);
  9176. }
  9177. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9178. task_queue->shutdown();
  9179. #else
  9180. EXPECT_NO_THROW(task_queue->shutdown());
  9181. #endif
  9182. }
  9183. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  9184. Server svr;
  9185. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9186. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  9187. });
  9188. svr.Get("/hello", [](const Request &req, Response &res) {
  9189. res.set_content(req.get_param_value("key"), "text/plain");
  9190. });
  9191. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9192. auto se = detail::scope_exit([&] {
  9193. svr.stop();
  9194. thread.join();
  9195. ASSERT_FALSE(svr.is_running());
  9196. });
  9197. svr.wait_until_ready();
  9198. {
  9199. Client cli(HOST, PORT);
  9200. cli.set_follow_location(true);
  9201. auto res = cli.Get("/");
  9202. ASSERT_TRUE(res);
  9203. EXPECT_EQ(StatusCode::OK_200, res->status);
  9204. EXPECT_EQ("val&key2=val2", res->body);
  9205. }
  9206. }
  9207. #endif
  9208. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  9209. Server svr;
  9210. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9211. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  9212. });
  9213. svr.Get("/hello", [](const Request &req, Response &res) {
  9214. res.set_content(req.get_param_value("key"), "text/plain");
  9215. });
  9216. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9217. auto se = detail::scope_exit([&] {
  9218. svr.stop();
  9219. thread.join();
  9220. ASSERT_FALSE(svr.is_running());
  9221. });
  9222. svr.wait_until_ready();
  9223. {
  9224. Client cli(HOST, PORT);
  9225. cli.set_follow_location(true);
  9226. auto res = cli.Get("/");
  9227. ASSERT_TRUE(res);
  9228. EXPECT_EQ(StatusCode::OK_200, res->status);
  9229. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  9230. }
  9231. }
  9232. #ifdef CPPHTTPLIB_SSL_ENABLED
  9233. TEST(RedirectTest, Issue2185_Online) {
  9234. SSLClient client("github.com");
  9235. client.set_follow_location(true);
  9236. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  9237. "Coollab-Windows.zip");
  9238. ASSERT_TRUE(res);
  9239. EXPECT_EQ(StatusCode::OK_200, res->status);
  9240. EXPECT_EQ(9920427U, res->body.size());
  9241. }
  9242. #endif
  9243. TEST(VulnerabilityTest, CRLFInjection) {
  9244. Server svr;
  9245. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  9246. res.set_content("Hello 1", "text/plain");
  9247. });
  9248. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  9249. res.set_content("Hello 2", "text/plain");
  9250. });
  9251. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  9252. res.set_content("Hello 3", "text/plain");
  9253. });
  9254. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  9255. res.set_content("Hello 4", "text/plain");
  9256. });
  9257. svr.set_logger([](const Request &req, const Response & /*res*/) {
  9258. for (const auto &x : req.headers) {
  9259. auto key = x.first;
  9260. EXPECT_STRNE("evil", key.c_str());
  9261. }
  9262. });
  9263. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9264. auto se = detail::scope_exit([&] {
  9265. svr.stop();
  9266. thread.join();
  9267. ASSERT_FALSE(svr.is_running());
  9268. });
  9269. svr.wait_until_ready();
  9270. {
  9271. Client cli(HOST, PORT);
  9272. cli.Post("/test1", "A=B",
  9273. "application/x-www-form-urlencoded\r\nevil: hello1");
  9274. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9275. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9276. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9277. }
  9278. }
  9279. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9280. auto server_thread = std::thread([] {
  9281. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9282. default_socket_options(srv);
  9283. sockaddr_in addr{};
  9284. addr.sin_family = AF_INET;
  9285. addr.sin_port = htons(PORT + 1);
  9286. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9287. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9288. ::listen(srv, 1);
  9289. sockaddr_in cli_addr{};
  9290. socklen_t cli_len = sizeof(cli_addr);
  9291. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9292. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9293. std::string buf_all;
  9294. char buf[2048];
  9295. ssize_t n;
  9296. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9297. buf_all.append(buf, static_cast<size_t>(n));
  9298. size_t pos;
  9299. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9300. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9301. auto e = request_block.find("\r\n");
  9302. if (e != std::string::npos) {
  9303. auto request_line = request_block.substr(0, e);
  9304. std::string msg =
  9305. "CRLF injection detected in request line: '" + request_line + "'";
  9306. EXPECT_FALSE(true) << msg;
  9307. }
  9308. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9309. ::send(cli,
  9310. #ifdef _WIN32
  9311. static_cast<const char *>(resp.c_str()),
  9312. static_cast<int>(resp.size()),
  9313. #else
  9314. resp.c_str(), resp.size(),
  9315. #endif
  9316. 0);
  9317. buf_all.erase(0, pos + 4);
  9318. }
  9319. }
  9320. detail::close_socket(cli);
  9321. detail::close_socket(srv);
  9322. });
  9323. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9324. auto cli = Client("127.0.0.1", PORT + 1);
  9325. auto headers = Headers{
  9326. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9327. {"Connection", "keep-alive"}};
  9328. auto res = cli.Get("/hi", headers);
  9329. EXPECT_FALSE(res);
  9330. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9331. server_thread.join();
  9332. }
  9333. TEST(PathParamsTest, StaticMatch) {
  9334. const auto pattern = "/users/all";
  9335. detail::PathParamsMatcher matcher(pattern);
  9336. Request request;
  9337. request.path = "/users/all";
  9338. ASSERT_TRUE(matcher.match(request));
  9339. std::unordered_map<std::string, std::string> expected_params = {};
  9340. EXPECT_EQ(request.path_params, expected_params);
  9341. }
  9342. TEST(PathParamsTest, StaticMismatch) {
  9343. const auto pattern = "/users/all";
  9344. detail::PathParamsMatcher matcher(pattern);
  9345. Request request;
  9346. request.path = "/users/1";
  9347. ASSERT_FALSE(matcher.match(request));
  9348. }
  9349. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9350. const auto pattern = "/users/:id/subscriptions";
  9351. detail::PathParamsMatcher matcher(pattern);
  9352. Request request;
  9353. request.path = "/users/42/subscriptions";
  9354. ASSERT_TRUE(matcher.match(request));
  9355. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9356. EXPECT_EQ(request.path_params, expected_params);
  9357. }
  9358. TEST(PathParamsTest, SingleParamInTheEnd) {
  9359. const auto pattern = "/users/:id";
  9360. detail::PathParamsMatcher matcher(pattern);
  9361. Request request;
  9362. request.path = "/users/24";
  9363. ASSERT_TRUE(matcher.match(request));
  9364. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9365. EXPECT_EQ(request.path_params, expected_params);
  9366. }
  9367. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9368. const auto pattern = "/users/:id/";
  9369. detail::PathParamsMatcher matcher(pattern);
  9370. Request request;
  9371. request.path = "/users/42/";
  9372. ASSERT_TRUE(matcher.match(request));
  9373. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9374. EXPECT_EQ(request.path_params, expected_params);
  9375. }
  9376. TEST(PathParamsTest, EmptyParam) {
  9377. const auto pattern = "/users/:id/";
  9378. detail::PathParamsMatcher matcher(pattern);
  9379. Request request;
  9380. request.path = "/users//";
  9381. ASSERT_TRUE(matcher.match(request));
  9382. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9383. EXPECT_EQ(request.path_params, expected_params);
  9384. }
  9385. TEST(PathParamsTest, FragmentMismatch) {
  9386. const auto pattern = "/users/:id/";
  9387. detail::PathParamsMatcher matcher(pattern);
  9388. Request request;
  9389. request.path = "/admins/24/";
  9390. ASSERT_FALSE(matcher.match(request));
  9391. }
  9392. TEST(PathParamsTest, ExtraFragments) {
  9393. const auto pattern = "/users/:id";
  9394. detail::PathParamsMatcher matcher(pattern);
  9395. Request request;
  9396. request.path = "/users/42/subscriptions";
  9397. ASSERT_FALSE(matcher.match(request));
  9398. }
  9399. TEST(PathParamsTest, MissingTrailingParam) {
  9400. const auto pattern = "/users/:id";
  9401. detail::PathParamsMatcher matcher(pattern);
  9402. Request request;
  9403. request.path = "/users";
  9404. ASSERT_FALSE(matcher.match(request));
  9405. }
  9406. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9407. const auto pattern = "/users/:id/subscriptions";
  9408. detail::PathParamsMatcher matcher(pattern);
  9409. Request request;
  9410. request.path = "/users/subscriptions";
  9411. ASSERT_FALSE(matcher.match(request));
  9412. }
  9413. TEST(PathParamsTest, MultipleParams) {
  9414. const auto pattern = "/users/:userid/subscriptions/:subid";
  9415. detail::PathParamsMatcher matcher(pattern);
  9416. Request request;
  9417. request.path = "/users/42/subscriptions/2";
  9418. ASSERT_TRUE(matcher.match(request));
  9419. std::unordered_map<std::string, std::string> expected_params = {
  9420. {"userid", "42"}, {"subid", "2"}};
  9421. EXPECT_EQ(request.path_params, expected_params);
  9422. }
  9423. TEST(PathParamsTest, SequenceOfParams) {
  9424. const auto pattern = "/values/:x/:y/:z";
  9425. detail::PathParamsMatcher matcher(pattern);
  9426. Request request;
  9427. request.path = "/values/1/2/3";
  9428. ASSERT_TRUE(matcher.match(request));
  9429. std::unordered_map<std::string, std::string> expected_params = {
  9430. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9431. EXPECT_EQ(request.path_params, expected_params);
  9432. }
  9433. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9434. const auto pattern = "/prefix:suffix";
  9435. detail::PathParamsMatcher matcher(pattern);
  9436. Request request;
  9437. request.path = "/prefix:suffix";
  9438. ASSERT_TRUE(matcher.match(request));
  9439. const std::unordered_map<std::string, std::string> expected_params = {};
  9440. EXPECT_EQ(request.path_params, expected_params);
  9441. }
  9442. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9443. // If ipv6 regex working, regex match codepath is taken.
  9444. // else port will default to 80 in Client impl
  9445. int clientImplMagicPort = 80;
  9446. int port = 4321;
  9447. // above ports must be different to avoid false negative
  9448. EXPECT_NE(clientImplMagicPort, port);
  9449. std::string ipV6TestURL = "http://[ff06::c3]";
  9450. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9451. CLIENT_PRIVATE_KEY_FILE);
  9452. EXPECT_EQ(cli.port(), port);
  9453. }
  9454. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9455. auto file_path = "./www/dir/index.html";
  9456. auto dir_path = "./www/dir";
  9457. detail::FileStat stat_file(file_path);
  9458. EXPECT_TRUE(stat_file.is_file());
  9459. EXPECT_FALSE(stat_file.is_dir());
  9460. detail::FileStat stat_dir(dir_path);
  9461. EXPECT_FALSE(stat_dir.is_file());
  9462. EXPECT_TRUE(stat_dir.is_dir());
  9463. }
  9464. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9465. // IPv4 with default HTTP port (80)
  9466. EXPECT_EQ("example.com",
  9467. detail::make_host_and_port_string("example.com", 80, false));
  9468. // IPv4 with default HTTPS port (443)
  9469. EXPECT_EQ("example.com",
  9470. detail::make_host_and_port_string("example.com", 443, true));
  9471. // IPv4 with non-default HTTP port
  9472. EXPECT_EQ("example.com:8080",
  9473. detail::make_host_and_port_string("example.com", 8080, false));
  9474. // IPv4 with non-default HTTPS port
  9475. EXPECT_EQ("example.com:8443",
  9476. detail::make_host_and_port_string("example.com", 8443, true));
  9477. // IPv6 with default HTTP port (80)
  9478. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9479. // IPv6 with default HTTPS port (443)
  9480. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9481. // IPv6 with non-default HTTP port
  9482. EXPECT_EQ("[::1]:8080",
  9483. detail::make_host_and_port_string("::1", 8080, false));
  9484. // IPv6 with non-default HTTPS port
  9485. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9486. // IPv6 full address with default port
  9487. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9488. detail::make_host_and_port_string(
  9489. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9490. // IPv6 full address with non-default port
  9491. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9492. detail::make_host_and_port_string(
  9493. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9494. // IPv6 localhost with non-default port
  9495. EXPECT_EQ("[::1]:3000",
  9496. detail::make_host_and_port_string("::1", 3000, false));
  9497. // IPv6 with zone ID (link-local address) with default port
  9498. EXPECT_EQ("[fe80::1%eth0]",
  9499. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9500. // IPv6 with zone ID (link-local address) with non-default port
  9501. EXPECT_EQ("[fe80::1%eth0]:8080",
  9502. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9503. // Edge case: Port 443 with is_ssl=false (should add port)
  9504. EXPECT_EQ("example.com:443",
  9505. detail::make_host_and_port_string("example.com", 443, false));
  9506. // Edge case: Port 80 with is_ssl=true (should add port)
  9507. EXPECT_EQ("example.com:80",
  9508. detail::make_host_and_port_string("example.com", 80, true));
  9509. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9510. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9511. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9512. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9513. // Security fix: Already bracketed IPv6 should not get double brackets
  9514. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9515. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9516. EXPECT_EQ("[::1]:8080",
  9517. detail::make_host_and_port_string("[::1]", 8080, false));
  9518. EXPECT_EQ("[2001:db8::1]:8080",
  9519. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9520. EXPECT_EQ("[fe80::1%eth0]",
  9521. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9522. EXPECT_EQ("[fe80::1%eth0]:8080",
  9523. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9524. // Edge case: Empty host (should return as-is)
  9525. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9526. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9527. // This is a known limitation but shouldn't crash
  9528. EXPECT_EQ("[host:name]",
  9529. detail::make_host_and_port_string("host:name", 80, false));
  9530. // Port number edge cases (no validation, but should not crash)
  9531. EXPECT_EQ("example.com:0",
  9532. detail::make_host_and_port_string("example.com", 0, false));
  9533. EXPECT_EQ("example.com:-1",
  9534. detail::make_host_and_port_string("example.com", -1, false));
  9535. EXPECT_EQ("example.com:65535",
  9536. detail::make_host_and_port_string("example.com", 65535, false));
  9537. EXPECT_EQ("example.com:65536",
  9538. detail::make_host_and_port_string("example.com", 65536, false));
  9539. }
  9540. #ifdef CPPHTTPLIB_SSL_ENABLED
  9541. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  9542. httplib::SSLClient cli("roblox.com", 443);
  9543. cli.set_follow_location(true);
  9544. auto res = cli.Get("/");
  9545. ASSERT_TRUE(res);
  9546. EXPECT_EQ(StatusCode::OK_200, res->status);
  9547. }
  9548. #endif
  9549. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9550. Server svr;
  9551. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9552. EXPECT_EQ(res.status, 400);
  9553. });
  9554. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9555. auto se = detail::scope_exit([&] {
  9556. svr.stop();
  9557. thread.join();
  9558. ASSERT_FALSE(svr.is_running());
  9559. });
  9560. svr.wait_until_ready();
  9561. Client cli(HOST, PORT);
  9562. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9563. }
  9564. TEST(InvalidHeaderCharsTest, is_field_name) {
  9565. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9566. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9567. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9568. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9569. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9570. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9571. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9572. EXPECT_FALSE(detail::fields::is_field_name(""));
  9573. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9574. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9575. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9576. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9577. }
  9578. TEST(InvalidHeaderCharsTest, is_field_value) {
  9579. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9580. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9581. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9582. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9583. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9584. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9585. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9586. EXPECT_TRUE(detail::fields::is_field_value(""));
  9587. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9588. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9589. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9590. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9591. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9592. }
  9593. TEST(InvalidHeaderCharsTest, OnServer) {
  9594. Server svr;
  9595. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9596. std::string header = "Not Set";
  9597. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9598. res.set_header(header, "value");
  9599. res.set_content("Page Content Page Content", "text/plain");
  9600. });
  9601. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9602. std::string header = "Not Set";
  9603. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9604. res.set_header("X-Test", header);
  9605. res.set_content("Page Content Page Content", "text/plain");
  9606. });
  9607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9608. auto se = detail::scope_exit([&] {
  9609. svr.stop();
  9610. thread.join();
  9611. ASSERT_FALSE(svr.is_running());
  9612. });
  9613. svr.wait_until_ready();
  9614. Client cli(HOST, PORT);
  9615. {
  9616. auto res = cli.Get(
  9617. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9618. ASSERT_TRUE(res);
  9619. EXPECT_EQ("Page Content Page Content", res->body);
  9620. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9621. }
  9622. {
  9623. auto res = cli.Get(
  9624. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9625. ASSERT_TRUE(res);
  9626. EXPECT_EQ("Page Content Page Content", res->body);
  9627. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9628. }
  9629. }
  9630. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9631. auto handled = false;
  9632. Server svr;
  9633. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9634. thread t = thread([&] { svr.listen(HOST, PORT); });
  9635. auto se = detail::scope_exit([&] {
  9636. svr.stop();
  9637. t.join();
  9638. ASSERT_FALSE(svr.is_running());
  9639. ASSERT_FALSE(handled);
  9640. });
  9641. svr.wait_until_ready();
  9642. auto req = "POST /test HTTP/1.1\r\n"
  9643. "Content-Length: x\r\n"
  9644. "\r\n";
  9645. std::string response;
  9646. ASSERT_TRUE(send_request(1, req, &response));
  9647. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9648. response.substr(0, response.find("\r\n")));
  9649. }
  9650. #ifndef _WIN32
  9651. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9652. static constexpr char reject[] = "Unauthorized";
  9653. static constexpr char accept[] = "Upload accepted";
  9654. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9655. Server svr;
  9656. svr.set_expect_100_continue_handler(
  9657. [](const Request & /*req*/, Response &res) {
  9658. res.status = StatusCode::Unauthorized_401;
  9659. res.set_content(reject, "text/plain");
  9660. return res.status;
  9661. });
  9662. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9663. res.set_content(accept, "text/plain");
  9664. });
  9665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9666. auto se = detail::scope_exit([&] {
  9667. svr.stop();
  9668. thread.join();
  9669. ASSERT_FALSE(svr.is_running());
  9670. });
  9671. svr.wait_until_ready();
  9672. {
  9673. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9674. curl_easy_init(), &curl_easy_cleanup};
  9675. ASSERT_NE(curl, nullptr);
  9676. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9677. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9678. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9679. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9680. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9681. &curl_slist_free_all};
  9682. ASSERT_NE(list, nullptr);
  9683. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9684. struct read_data {
  9685. size_t read_size;
  9686. size_t total_size;
  9687. } data = {0, total_size};
  9688. using read_callback_t =
  9689. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9690. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9691. void *userdata) -> size_t {
  9692. read_data *data = (read_data *)userdata;
  9693. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9694. std::fill_n(ptr, size * nmemb, 'A');
  9695. data->read_size += size * nmemb;
  9696. return size * nmemb;
  9697. };
  9698. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9699. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9700. std::vector<char> buffer;
  9701. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9702. using write_callback_t =
  9703. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9704. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9705. void *userdata) -> size_t {
  9706. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9707. buffer->reserve(buffer->size() + size * nmemb + 1);
  9708. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9709. return size * nmemb;
  9710. };
  9711. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9712. {
  9713. const auto res = curl_easy_perform(curl.get());
  9714. ASSERT_EQ(res, CURLE_OK);
  9715. }
  9716. {
  9717. auto response_code = long{};
  9718. const auto res =
  9719. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9720. ASSERT_EQ(res, CURLE_OK);
  9721. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9722. }
  9723. {
  9724. auto dl = curl_off_t{};
  9725. const auto res =
  9726. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9727. ASSERT_EQ(res, CURLE_OK);
  9728. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9729. }
  9730. {
  9731. buffer.push_back('\0');
  9732. ASSERT_STRCASEEQ(buffer.data(), reject);
  9733. }
  9734. }
  9735. }
  9736. #endif
  9737. template <typename S, typename C>
  9738. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9739. svr.Get("/stream", [&](const Request &, Response &res) {
  9740. auto data = new std::string("01234567890123456789");
  9741. res.set_content_provider(
  9742. data->size(), "text/plain",
  9743. [&, data](size_t offset, size_t length, DataSink &sink) {
  9744. const size_t DATA_CHUNK_SIZE = 4;
  9745. const auto &d = *data;
  9746. std::this_thread::sleep_for(std::chrono::seconds(1));
  9747. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9748. return true;
  9749. },
  9750. [data](bool success) {
  9751. EXPECT_FALSE(success);
  9752. delete data;
  9753. });
  9754. });
  9755. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9756. auto i = new size_t(0);
  9757. res.set_content_provider(
  9758. "text/plain",
  9759. [i](size_t, DataSink &sink) {
  9760. if (*i < 5) {
  9761. std::this_thread::sleep_for(std::chrono::seconds(1));
  9762. sink.write("abcd", 4);
  9763. (*i)++;
  9764. } else {
  9765. sink.done();
  9766. }
  9767. return true;
  9768. },
  9769. [i](bool success) {
  9770. EXPECT_FALSE(success);
  9771. delete i;
  9772. });
  9773. });
  9774. svr.Get("/chunked", [&](const Request &, Response &res) {
  9775. auto i = new size_t(0);
  9776. res.set_chunked_content_provider(
  9777. "text/plain",
  9778. [i](size_t, DataSink &sink) {
  9779. if (*i < 5) {
  9780. std::this_thread::sleep_for(std::chrono::seconds(1));
  9781. sink.os << "abcd";
  9782. (*i)++;
  9783. } else {
  9784. sink.done();
  9785. }
  9786. return true;
  9787. },
  9788. [i](bool success) {
  9789. EXPECT_FALSE(success);
  9790. delete i;
  9791. });
  9792. });
  9793. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9794. auto se = detail::scope_exit([&] {
  9795. svr.stop();
  9796. listen_thread.join();
  9797. ASSERT_FALSE(svr.is_running());
  9798. });
  9799. svr.wait_until_ready();
  9800. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9801. {
  9802. auto start = std::chrono::steady_clock::now();
  9803. auto res = cli.Get("/stream");
  9804. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9805. std::chrono::steady_clock::now() - start)
  9806. .count();
  9807. ASSERT_FALSE(res);
  9808. EXPECT_EQ(Error::Read, res.error());
  9809. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9810. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9811. }
  9812. {
  9813. auto start = std::chrono::steady_clock::now();
  9814. auto res = cli.Get("/stream_without_length");
  9815. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9816. std::chrono::steady_clock::now() - start)
  9817. .count();
  9818. ASSERT_FALSE(res);
  9819. EXPECT_EQ(Error::Read, res.error());
  9820. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9821. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9822. }
  9823. {
  9824. auto start = std::chrono::steady_clock::now();
  9825. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9826. EXPECT_EQ("abcd", string(data, data_length));
  9827. return true;
  9828. });
  9829. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9830. std::chrono::steady_clock::now() - start)
  9831. .count();
  9832. ASSERT_FALSE(res);
  9833. EXPECT_EQ(Error::Read, res.error());
  9834. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9835. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9836. }
  9837. }
  9838. TEST(MaxTimeoutTest, ContentStream) {
  9839. time_t timeout = 2000;
  9840. time_t threshold = 200;
  9841. Server svr;
  9842. Client cli("localhost", PORT);
  9843. max_timeout_test(svr, cli, timeout, threshold);
  9844. }
  9845. #ifdef CPPHTTPLIB_SSL_ENABLED
  9846. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9847. time_t timeout = 2000;
  9848. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9849. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9850. SSLClient cli("localhost", PORT);
  9851. cli.enable_server_certificate_verification(false);
  9852. max_timeout_test(svr, cli, timeout, threshold);
  9853. }
  9854. #endif
  9855. class EventDispatcher {
  9856. public:
  9857. EventDispatcher() {}
  9858. bool wait_event(DataSink *sink) {
  9859. unique_lock<mutex> lk(m_);
  9860. int id = id_;
  9861. // Wait with timeout to prevent hanging if client disconnects
  9862. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9863. [&] { return cid_ == id; })) {
  9864. return false; // Timeout occurred
  9865. }
  9866. sink->write(message_.data(), message_.size());
  9867. return true;
  9868. }
  9869. void send_event(const string &message) {
  9870. lock_guard<mutex> lk(m_);
  9871. cid_ = id_++;
  9872. message_ = message;
  9873. cv_.notify_all();
  9874. }
  9875. private:
  9876. mutex m_;
  9877. condition_variable cv_;
  9878. atomic_int id_{0};
  9879. atomic_int cid_{-1};
  9880. string message_;
  9881. };
  9882. TEST(ClientInThreadTest, Issue2068) {
  9883. EventDispatcher ed;
  9884. Server svr;
  9885. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9886. res.set_chunked_content_provider("text/event-stream",
  9887. [&](size_t /*offset*/, DataSink &sink) {
  9888. return ed.wait_event(&sink);
  9889. });
  9890. });
  9891. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9892. svr.wait_until_ready();
  9893. thread event_thread([&] {
  9894. int id = 0;
  9895. while (svr.is_running()) {
  9896. this_thread::sleep_for(chrono::milliseconds(500));
  9897. std::stringstream ss;
  9898. ss << "data: " << id << "\n\n";
  9899. ed.send_event(ss.str());
  9900. id++;
  9901. }
  9902. });
  9903. auto se = detail::scope_exit([&] {
  9904. svr.stop();
  9905. listen_thread.join();
  9906. event_thread.join();
  9907. ASSERT_FALSE(svr.is_running());
  9908. });
  9909. {
  9910. auto client = detail::make_unique<Client>(HOST, PORT);
  9911. client->set_read_timeout(std::chrono::minutes(10));
  9912. std::atomic<bool> stop{false};
  9913. std::thread t([&] {
  9914. client->Get("/event1",
  9915. [&](const char *, size_t) -> bool { return !stop; });
  9916. });
  9917. std::this_thread::sleep_for(std::chrono::seconds(2));
  9918. stop = true;
  9919. client->stop();
  9920. t.join();
  9921. // Reset client after thread has finished
  9922. client.reset();
  9923. }
  9924. }
  9925. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9926. Server svr;
  9927. svr.Get("/", [](const Request &req, Response &res) {
  9928. EXPECT_EQ(2U, req.trailers.size());
  9929. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9930. // Denied
  9931. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9932. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9933. // Accepted
  9934. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9935. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9936. EXPECT_TRUE(req.has_trailer("X-World"));
  9937. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9938. res.set_content("ok", "text/plain");
  9939. });
  9940. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9941. auto se = detail::scope_exit([&] {
  9942. svr.stop();
  9943. t.join();
  9944. ASSERT_FALSE(svr.is_running());
  9945. });
  9946. svr.wait_until_ready();
  9947. const std::string req = "GET / HTTP/1.1\r\n"
  9948. "Transfer-Encoding: chunked\r\n"
  9949. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9950. "\r\n"
  9951. "0\r\n"
  9952. "Content-Length: 10\r\n"
  9953. "Host: internal.local\r\n"
  9954. "Content-Type: malicious/content\r\n"
  9955. "Cookie: any\r\n"
  9956. "Set-Cookie: any\r\n"
  9957. "X-Forwarded-For: attacker.com\r\n"
  9958. "X-Real-Ip: 1.1.1.1\r\n"
  9959. "X-Hello: hello\r\n"
  9960. "X-World: world\r\n"
  9961. "\r\n";
  9962. std::string res;
  9963. ASSERT_TRUE(send_request(1, req, &res));
  9964. }
  9965. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9966. Server svr;
  9967. std::string observed_remote_addr;
  9968. std::string observed_xff;
  9969. svr.Get("/ip", [&](const Request &req, Response &res) {
  9970. observed_remote_addr = req.remote_addr;
  9971. observed_xff = req.get_header_value("X-Forwarded-For");
  9972. res.set_content("ok", "text/plain");
  9973. });
  9974. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9975. auto se = detail::scope_exit([&] {
  9976. svr.stop();
  9977. t.join();
  9978. ASSERT_FALSE(svr.is_running());
  9979. });
  9980. svr.wait_until_ready();
  9981. Client cli(HOST, PORT);
  9982. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9983. ASSERT_TRUE(res);
  9984. EXPECT_EQ(StatusCode::OK_200, res->status);
  9985. EXPECT_EQ(observed_xff, "203.0.113.66");
  9986. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9987. observed_remote_addr == "127.0.0.1");
  9988. }
  9989. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9990. Server svr;
  9991. svr.set_trusted_proxies({"203.0.113.66"});
  9992. std::string observed_remote_addr;
  9993. std::string observed_xff;
  9994. svr.Get("/ip", [&](const Request &req, Response &res) {
  9995. observed_remote_addr = req.remote_addr;
  9996. observed_xff = req.get_header_value("X-Forwarded-For");
  9997. res.set_content("ok", "text/plain");
  9998. });
  9999. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10000. auto se = detail::scope_exit([&] {
  10001. svr.stop();
  10002. t.join();
  10003. ASSERT_FALSE(svr.is_running());
  10004. });
  10005. svr.wait_until_ready();
  10006. Client cli(HOST, PORT);
  10007. auto res = cli.Get("/ip");
  10008. ASSERT_TRUE(res);
  10009. EXPECT_EQ(StatusCode::OK_200, res->status);
  10010. EXPECT_EQ(observed_xff, "");
  10011. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10012. observed_remote_addr == "127.0.0.1");
  10013. }
  10014. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10015. Server svr;
  10016. svr.set_trusted_proxies({"203.0.113.66"});
  10017. std::string observed_remote_addr;
  10018. std::string observed_xff;
  10019. svr.Get("/ip", [&](const Request &req, Response &res) {
  10020. observed_remote_addr = req.remote_addr;
  10021. observed_xff = req.get_header_value("X-Forwarded-For");
  10022. res.set_content("ok", "text/plain");
  10023. });
  10024. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10025. auto se = detail::scope_exit([&] {
  10026. svr.stop();
  10027. t.join();
  10028. ASSERT_FALSE(svr.is_running());
  10029. });
  10030. svr.wait_until_ready();
  10031. Client cli(HOST, PORT);
  10032. auto res =
  10033. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10034. ASSERT_TRUE(res);
  10035. EXPECT_EQ(StatusCode::OK_200, res->status);
  10036. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10037. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10038. }
  10039. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10040. Server svr;
  10041. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10042. std::string observed_remote_addr;
  10043. std::string observed_xff;
  10044. svr.Get("/ip", [&](const Request &req, Response &res) {
  10045. observed_remote_addr = req.remote_addr;
  10046. observed_xff = req.get_header_value("X-Forwarded-For");
  10047. res.set_content("ok", "text/plain");
  10048. });
  10049. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10050. auto se = detail::scope_exit([&] {
  10051. svr.stop();
  10052. t.join();
  10053. ASSERT_FALSE(svr.is_running());
  10054. });
  10055. svr.wait_until_ready();
  10056. Client cli(HOST, PORT);
  10057. auto res = cli.Get(
  10058. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10059. ASSERT_TRUE(res);
  10060. EXPECT_EQ(StatusCode::OK_200, res->status);
  10061. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10062. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10063. }
  10064. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  10065. Server svr;
  10066. svr.set_trusted_proxies({"192.0.2.45"});
  10067. std::string observed_remote_addr;
  10068. std::string observed_xff;
  10069. svr.Get("/ip", [&](const Request &req, Response &res) {
  10070. observed_remote_addr = req.remote_addr;
  10071. observed_xff = req.get_header_value("X-Forwarded-For");
  10072. res.set_content("ok", "text/plain");
  10073. });
  10074. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10075. auto se = detail::scope_exit([&] {
  10076. svr.stop();
  10077. t.join();
  10078. ASSERT_FALSE(svr.is_running());
  10079. });
  10080. svr.wait_until_ready();
  10081. Client cli(HOST, PORT);
  10082. auto res =
  10083. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  10084. ASSERT_TRUE(res);
  10085. EXPECT_EQ(StatusCode::OK_200, res->status);
  10086. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  10087. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10088. }
  10089. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  10090. Server svr;
  10091. svr.set_trusted_proxies({"192.0.2.45"});
  10092. std::string observed_remote_addr;
  10093. std::string observed_xff;
  10094. svr.Get("/ip", [&](const Request &req, Response &res) {
  10095. observed_remote_addr = req.remote_addr;
  10096. observed_xff = req.get_header_value("X-Forwarded-For");
  10097. res.set_content("ok", "text/plain");
  10098. });
  10099. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10100. auto se = detail::scope_exit([&] {
  10101. svr.stop();
  10102. t.join();
  10103. ASSERT_FALSE(svr.is_running());
  10104. });
  10105. svr.wait_until_ready();
  10106. Client cli(HOST, PORT);
  10107. auto res = cli.Get(
  10108. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10109. ASSERT_TRUE(res);
  10110. EXPECT_EQ(StatusCode::OK_200, res->status);
  10111. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10112. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10113. }
  10114. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  10115. Server svr;
  10116. svr.set_trusted_proxies({"192.0.2.45"});
  10117. std::string observed_remote_addr;
  10118. std::string observed_xff;
  10119. svr.Get("/ip", [&](const Request &req, Response &res) {
  10120. observed_remote_addr = req.remote_addr;
  10121. observed_xff = req.get_header_value("X-Forwarded-For");
  10122. res.set_content("ok", "text/plain");
  10123. });
  10124. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10125. auto se = detail::scope_exit([&] {
  10126. svr.stop();
  10127. t.join();
  10128. ASSERT_FALSE(svr.is_running());
  10129. });
  10130. svr.wait_until_ready();
  10131. std::string raw_req =
  10132. "GET /ip HTTP/1.1\r\n"
  10133. "Host: localhost\r\n"
  10134. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  10135. "Connection: close\r\n"
  10136. "\r\n";
  10137. std::string out;
  10138. ASSERT_TRUE(send_request(5, raw_req, &out));
  10139. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10140. // Header parser trims surrounding whitespace of the header value
  10141. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  10142. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10143. }
  10144. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  10145. Server svr;
  10146. svr.Post("/post", [&](const Request &req, Response &res) {
  10147. res.set_content(req.body, "text/plain");
  10148. });
  10149. svr.Put("/put", [&](const Request &req, Response &res) {
  10150. res.set_content(req.body, "text/plain");
  10151. });
  10152. svr.Patch("/patch", [&](const Request &req, Response &res) {
  10153. res.set_content(req.body, "text/plain");
  10154. });
  10155. svr.Delete("/delete", [&](const Request &req, Response &res) {
  10156. res.set_content(req.body, "text/plain");
  10157. });
  10158. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10159. auto se = detail::scope_exit([&] {
  10160. svr.stop();
  10161. t.join();
  10162. ASSERT_FALSE(svr.is_running());
  10163. });
  10164. svr.wait_until_ready();
  10165. std::string resp;
  10166. // POST without Content-Length
  10167. ASSERT_TRUE(send_request(5,
  10168. "POST /post HTTP/1.1\r\n"
  10169. "Host: localhost\r\n"
  10170. "Connection: close\r\n"
  10171. "\r\n",
  10172. &resp));
  10173. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10174. // PUT without Content-Length
  10175. resp.clear();
  10176. ASSERT_TRUE(send_request(5,
  10177. "PUT /put HTTP/1.1\r\n"
  10178. "Host: localhost\r\n"
  10179. "Connection: close\r\n"
  10180. "\r\n",
  10181. &resp));
  10182. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10183. // PATCH without Content-Length
  10184. resp.clear();
  10185. ASSERT_TRUE(send_request(5,
  10186. "PATCH /patch HTTP/1.1\r\n"
  10187. "Host: localhost\r\n"
  10188. "Connection: close\r\n"
  10189. "\r\n",
  10190. &resp));
  10191. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10192. // DELETE without Content-Length
  10193. resp.clear();
  10194. ASSERT_TRUE(send_request(5,
  10195. "DELETE /delete HTTP/1.1\r\n"
  10196. "Host: localhost\r\n"
  10197. "Connection: close\r\n"
  10198. "\r\n",
  10199. &resp));
  10200. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10201. }
  10202. //==============================================================================
  10203. // open_stream() Tests
  10204. //==============================================================================
  10205. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  10206. std::string result;
  10207. char buf[8192];
  10208. ssize_t n;
  10209. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10210. result.append(buf, static_cast<size_t>(n));
  10211. }
  10212. return result;
  10213. }
  10214. // Mock stream for unit tests
  10215. class MockStream : public Stream {
  10216. public:
  10217. std::string data;
  10218. size_t pos = 0;
  10219. ssize_t error_after = -1; // -1 = no error
  10220. explicit MockStream(const std::string &d, ssize_t err = -1)
  10221. : data(d), error_after(err) {}
  10222. bool is_readable() const override { return true; }
  10223. bool wait_readable() const override { return true; }
  10224. bool wait_writable() const override { return true; }
  10225. ssize_t read(char *ptr, size_t size) override {
  10226. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  10227. if (pos >= data.size()) return 0;
  10228. size_t limit =
  10229. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  10230. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  10231. std::memcpy(ptr, data.data() + pos, to_read);
  10232. pos += to_read;
  10233. return static_cast<ssize_t>(to_read);
  10234. }
  10235. ssize_t write(const char *, size_t) override { return -1; }
  10236. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  10237. ip = "127.0.0.1";
  10238. port = 0;
  10239. }
  10240. void get_local_ip_and_port(std::string &ip, int &port) const override {
  10241. ip = "127.0.0.1";
  10242. port = 0;
  10243. }
  10244. socket_t socket() const override { return INVALID_SOCKET; }
  10245. time_t duration() const override { return 0; }
  10246. };
  10247. TEST(StreamHandleTest, Basic) {
  10248. ClientImpl::StreamHandle handle;
  10249. EXPECT_FALSE(handle.is_valid());
  10250. handle.response = detail::make_unique<Response>();
  10251. handle.error = Error::Connection;
  10252. EXPECT_FALSE(handle.is_valid());
  10253. handle.error = Error::Success;
  10254. EXPECT_TRUE(handle.is_valid());
  10255. }
  10256. TEST(BodyReaderTest, Basic) {
  10257. MockStream stream("Hello, World!");
  10258. detail::BodyReader reader;
  10259. reader.stream = &stream;
  10260. reader.content_length = 13;
  10261. char buf[32];
  10262. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  10263. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  10264. EXPECT_TRUE(reader.eof);
  10265. }
  10266. TEST(BodyReaderTest, NoStream) {
  10267. detail::BodyReader reader;
  10268. char buf[32];
  10269. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10270. EXPECT_EQ(Error::Connection, reader.last_error);
  10271. }
  10272. TEST(BodyReaderTest, Error) {
  10273. MockStream stream("Hello, World!", 5);
  10274. detail::BodyReader reader;
  10275. reader.stream = &stream;
  10276. reader.content_length = 13;
  10277. char buf[32];
  10278. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10279. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10280. EXPECT_EQ(Error::Read, reader.last_error);
  10281. }
  10282. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10283. // Mock-based StreamHandle tests relying on private internals are removed.
  10284. class OpenStreamTest : public ::testing::Test {
  10285. protected:
  10286. void SetUp() override {
  10287. svr_.Get("/hello", [](const Request &, Response &res) {
  10288. res.set_content("Hello World!", "text/plain");
  10289. });
  10290. svr_.Get("/large", [](const Request &, Response &res) {
  10291. res.set_content(std::string(10000, 'X'), "text/plain");
  10292. });
  10293. svr_.Get("/chunked", [](const Request &, Response &res) {
  10294. res.set_chunked_content_provider("text/plain",
  10295. [](size_t offset, DataSink &sink) {
  10296. if (offset < 15) {
  10297. sink.write("chunk", 5);
  10298. return true;
  10299. }
  10300. sink.done();
  10301. return true;
  10302. });
  10303. });
  10304. svr_.Get("/compressible", [](const Request &, Response &res) {
  10305. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10306. DataSink &sink) {
  10307. if (offset < 100 * 1024) {
  10308. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10309. sink.write(chunk.data(), chunk.size());
  10310. return true;
  10311. }
  10312. sink.done();
  10313. return true;
  10314. });
  10315. });
  10316. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10317. [](const Request & /*req*/, Response &res) {
  10318. auto i = new int(0);
  10319. res.set_header("Trailer", "Content-Length, X-Allowed");
  10320. res.set_chunked_content_provider(
  10321. "text/plain",
  10322. [i](size_t /*offset*/, DataSink &sink) {
  10323. switch (*i) {
  10324. case 0: sink.os << "123"; break;
  10325. case 1: sink.os << "456"; break;
  10326. case 2: sink.os << "789"; break;
  10327. case 3: {
  10328. sink.done_with_trailer(
  10329. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10330. } break;
  10331. }
  10332. (*i)++;
  10333. return true;
  10334. },
  10335. [i](bool success) {
  10336. EXPECT_TRUE(success);
  10337. delete i;
  10338. });
  10339. });
  10340. // Echo headers endpoint for header-related tests
  10341. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10342. std::string body;
  10343. for (const auto &h : req.headers) {
  10344. body.append(h.first);
  10345. body.push_back(':');
  10346. body.append(h.second);
  10347. body.push_back('\n');
  10348. }
  10349. res.set_content(body, "text/plain");
  10350. });
  10351. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10352. std::string body;
  10353. for (const auto &h : req.headers) {
  10354. body.append(h.first);
  10355. body.push_back(':');
  10356. body.append(h.second);
  10357. body.push_back('\n');
  10358. }
  10359. res.set_content(body, "text/plain");
  10360. });
  10361. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10362. svr_.wait_until_ready();
  10363. }
  10364. void TearDown() override {
  10365. svr_.stop();
  10366. if (thread_.joinable()) thread_.join();
  10367. }
  10368. Server svr_;
  10369. std::thread thread_;
  10370. };
  10371. TEST_F(OpenStreamTest, Basic) {
  10372. Client cli("127.0.0.1", 8787);
  10373. auto handle = cli.open_stream("GET", "/hello");
  10374. EXPECT_TRUE(handle.is_valid());
  10375. EXPECT_EQ("Hello World!", read_all(handle));
  10376. }
  10377. TEST_F(OpenStreamTest, SmallBuffer) {
  10378. Client cli("127.0.0.1", 8787);
  10379. auto handle = cli.open_stream("GET", "/hello");
  10380. std::string result;
  10381. char buf[4];
  10382. ssize_t n;
  10383. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10384. result.append(buf, static_cast<size_t>(n));
  10385. EXPECT_EQ("Hello World!", result);
  10386. }
  10387. TEST_F(OpenStreamTest, DefaultHeaders) {
  10388. Client cli("127.0.0.1", 8787);
  10389. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10390. {
  10391. auto handle = cli.open_stream("GET", "/echo-headers");
  10392. ASSERT_TRUE(handle.is_valid());
  10393. auto body = read_all(handle);
  10394. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10395. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10396. std::string::npos);
  10397. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10398. }
  10399. // open_stream POST with body and no explicit content_type should NOT add
  10400. // text/plain Content-Type (behavior differs from non-streaming path), but
  10401. // should include Content-Length
  10402. {
  10403. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10404. ASSERT_TRUE(handle.is_valid());
  10405. auto body = read_all(handle);
  10406. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10407. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10408. }
  10409. // open_stream POST with explicit Content-Type should preserve it
  10410. {
  10411. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10412. {{"Content-Type", "application/custom"}},
  10413. "{}", "application/custom");
  10414. ASSERT_TRUE(handle.is_valid());
  10415. auto body = read_all(handle);
  10416. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10417. }
  10418. // User-specified User-Agent must not be overwritten for stream API
  10419. {
  10420. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10421. {{"User-Agent", "MyAgent/1.2"}});
  10422. ASSERT_TRUE(handle.is_valid());
  10423. auto body = read_all(handle);
  10424. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10425. }
  10426. }
  10427. TEST_F(OpenStreamTest, Large) {
  10428. Client cli("127.0.0.1", 8787);
  10429. auto handle = cli.open_stream("GET", "/large");
  10430. EXPECT_EQ(10000u, read_all(handle).size());
  10431. }
  10432. TEST_F(OpenStreamTest, ConnectionError) {
  10433. Client cli("127.0.0.1", 9999);
  10434. auto handle = cli.open_stream("GET", "/hello");
  10435. EXPECT_FALSE(handle.is_valid());
  10436. }
  10437. TEST_F(OpenStreamTest, Chunked) {
  10438. Client cli("127.0.0.1", 8787);
  10439. auto handle = cli.open_stream("GET", "/chunked");
  10440. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10441. "Transfer-Encoding") == "chunked");
  10442. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10443. }
  10444. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10445. Client cli("127.0.0.1", 8787);
  10446. auto handle =
  10447. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10448. ASSERT_TRUE(handle.is_valid());
  10449. // Consume body to allow trailers to be received/parsed
  10450. auto body = read_all(handle);
  10451. // Explicitly parse trailers (ensure trailers are available for assertion)
  10452. handle.parse_trailers_if_needed();
  10453. EXPECT_EQ(std::string("123456789"), body);
  10454. // The response should include a Trailer header declaring both names
  10455. ASSERT_TRUE(handle.response);
  10456. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10457. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10458. handle.response->get_header_value("Trailer"));
  10459. // Prohibited trailer must not be present
  10460. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10461. // Allowed trailer should be present
  10462. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10463. EXPECT_EQ(std::string("yes"),
  10464. handle.response->get_trailer_value("X-Allowed"));
  10465. // Verify trailers are NOT present as regular headers
  10466. EXPECT_EQ(std::string(""),
  10467. handle.response->get_header_value("Content-Length"));
  10468. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10469. }
  10470. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10471. TEST_F(OpenStreamTest, Gzip) {
  10472. Client cli("127.0.0.1", 8787);
  10473. auto handle = cli.open_stream("GET", "/compressible", {},
  10474. {{"Accept-Encoding", "gzip"}});
  10475. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10476. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10477. }
  10478. #endif
  10479. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10480. TEST_F(OpenStreamTest, Brotli) {
  10481. Client cli("127.0.0.1", 8787);
  10482. auto handle =
  10483. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10484. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10485. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10486. }
  10487. #endif
  10488. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10489. TEST_F(OpenStreamTest, Zstd) {
  10490. Client cli("127.0.0.1", 8787);
  10491. auto handle = cli.open_stream("GET", "/compressible", {},
  10492. {{"Accept-Encoding", "zstd"}});
  10493. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10494. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10495. }
  10496. #endif
  10497. #ifdef CPPHTTPLIB_SSL_ENABLED
  10498. class SSLOpenStreamTest : public ::testing::Test {
  10499. protected:
  10500. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10501. void SetUp() override {
  10502. svr_.Get("/hello", [](const Request &, Response &res) {
  10503. res.set_content("Hello SSL World!", "text/plain");
  10504. });
  10505. svr_.Get("/chunked", [](const Request &, Response &res) {
  10506. res.set_chunked_content_provider("text/plain",
  10507. [](size_t offset, DataSink &sink) {
  10508. if (offset < 15) {
  10509. sink.write("chunk", 5);
  10510. return true;
  10511. }
  10512. sink.done();
  10513. return true;
  10514. });
  10515. });
  10516. svr_.Post("/echo", [](const Request &req, Response &res) {
  10517. res.set_content(req.body, req.get_header_value("Content-Type"));
  10518. });
  10519. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10520. std::string body = req.body;
  10521. res.set_chunked_content_provider(
  10522. "text/plain", [body](size_t offset, DataSink &sink) {
  10523. if (offset < body.size()) {
  10524. sink.write(body.data() + offset, body.size() - offset);
  10525. }
  10526. sink.done();
  10527. return true;
  10528. });
  10529. });
  10530. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10531. svr_.wait_until_ready();
  10532. }
  10533. void TearDown() override {
  10534. svr_.stop();
  10535. if (thread_.joinable()) thread_.join();
  10536. }
  10537. SSLServer svr_;
  10538. std::thread thread_;
  10539. };
  10540. TEST_F(SSLOpenStreamTest, Basic) {
  10541. SSLClient cli("127.0.0.1", 8788);
  10542. cli.enable_server_certificate_verification(false);
  10543. auto handle = cli.open_stream("GET", "/hello");
  10544. ASSERT_TRUE(handle.is_valid());
  10545. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10546. }
  10547. TEST_F(SSLOpenStreamTest, Chunked) {
  10548. SSLClient cli("127.0.0.1", 8788);
  10549. cli.enable_server_certificate_verification(false);
  10550. auto handle = cli.open_stream("GET", "/chunked");
  10551. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10552. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10553. "Transfer-Encoding") == "chunked");
  10554. auto body = read_all(handle);
  10555. EXPECT_EQ("chunkchunkchunk", body);
  10556. }
  10557. TEST_F(SSLOpenStreamTest, Post) {
  10558. SSLClient cli("127.0.0.1", 8788);
  10559. cli.enable_server_certificate_verification(false);
  10560. auto handle =
  10561. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10562. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10563. EXPECT_EQ(200, handle.response->status);
  10564. auto body = read_all(handle);
  10565. EXPECT_EQ("Hello SSL POST", body);
  10566. }
  10567. TEST_F(SSLOpenStreamTest, PostChunked) {
  10568. SSLClient cli("127.0.0.1", 8788);
  10569. cli.enable_server_certificate_verification(false);
  10570. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10571. "Chunked SSL Data", "text/plain");
  10572. ASSERT_TRUE(handle.is_valid());
  10573. EXPECT_EQ(200, handle.response->status);
  10574. auto body = read_all(handle);
  10575. EXPECT_EQ("Chunked SSL Data", body);
  10576. }
  10577. #endif // CPPHTTPLIB_SSL_ENABLED
  10578. //==============================================================================
  10579. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10580. // results for various scenarios.
  10581. //==============================================================================
  10582. TEST(ParityTest, GetVsOpenStream) {
  10583. Server svr;
  10584. const std::string path = "/parity";
  10585. const std::string content = "Parity test content: hello world";
  10586. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10587. res.set_content(content, "text/plain");
  10588. });
  10589. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10590. auto se = detail::scope_exit([&] {
  10591. svr.stop();
  10592. t.join();
  10593. ASSERT_FALSE(svr.is_running());
  10594. });
  10595. svr.wait_until_ready();
  10596. Client cli(HOST, PORT);
  10597. // Non-stream path
  10598. auto r1 = cli.Get(path);
  10599. ASSERT_TRUE(r1);
  10600. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10601. // Stream path
  10602. auto h = cli.open_stream("GET", path);
  10603. ASSERT_TRUE(h.is_valid());
  10604. EXPECT_EQ(r1->body, read_all(h));
  10605. }
  10606. // Helper to compress data with provided compressor type T
  10607. template <typename Compressor>
  10608. static std::string compress_payload_for_parity(const std::string &in) {
  10609. std::string out;
  10610. Compressor compressor;
  10611. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10612. [&](const char *data, size_t n) {
  10613. out.append(data, n);
  10614. return true;
  10615. });
  10616. EXPECT_TRUE(ok);
  10617. return out;
  10618. }
  10619. // Helper function for compression parity tests
  10620. template <typename Compressor>
  10621. static void test_compression_parity(const std::string &original,
  10622. const std::string &path,
  10623. const std::string &encoding) {
  10624. const std::string compressed =
  10625. compress_payload_for_parity<Compressor>(original);
  10626. Server svr;
  10627. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10628. res.set_content(compressed, "application/octet-stream");
  10629. res.set_header("Content-Encoding", encoding);
  10630. });
  10631. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10632. auto se = detail::scope_exit([&] {
  10633. svr.stop();
  10634. t.join();
  10635. ASSERT_FALSE(svr.is_running());
  10636. });
  10637. svr.wait_until_ready();
  10638. Client cli(HOST, PORT);
  10639. // Non-streaming
  10640. {
  10641. auto res = cli.Get(path);
  10642. ASSERT_TRUE(res);
  10643. EXPECT_EQ(StatusCode::OK_200, res->status);
  10644. EXPECT_EQ(original, res->body);
  10645. }
  10646. // Streaming
  10647. {
  10648. auto h = cli.open_stream("GET", path);
  10649. ASSERT_TRUE(h.is_valid());
  10650. EXPECT_EQ(original, read_all(h));
  10651. }
  10652. }
  10653. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10654. TEST(ParityTest, Gzip) {
  10655. test_compression_parity<detail::gzip_compressor>(
  10656. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10657. }
  10658. #endif
  10659. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10660. TEST(ParityTest, Brotli) {
  10661. test_compression_parity<detail::brotli_compressor>(
  10662. "Hello, brotli parity test payload", "/parity-br", "br");
  10663. }
  10664. #endif
  10665. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10666. TEST(ParityTest, Zstd) {
  10667. test_compression_parity<detail::zstd_compressor>(
  10668. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10669. }
  10670. #endif
  10671. //==============================================================================
  10672. // New Stream API Tests
  10673. //==============================================================================
  10674. inline std::string read_body(httplib::stream::Result &result) {
  10675. std::string body;
  10676. while (result.next()) {
  10677. body.append(result.data(), result.size());
  10678. }
  10679. return body;
  10680. }
  10681. TEST(ClientConnectionTest, Basic) {
  10682. httplib::ClientConnection conn;
  10683. EXPECT_FALSE(conn.is_open());
  10684. conn.sock = 1;
  10685. EXPECT_TRUE(conn.is_open());
  10686. httplib::ClientConnection conn2(std::move(conn));
  10687. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10688. conn2.sock = INVALID_SOCKET;
  10689. }
  10690. // Unified test server for all stream::* tests
  10691. class StreamApiTest : public ::testing::Test {
  10692. protected:
  10693. void SetUp() override {
  10694. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10695. res.set_content("Hello World!", "text/plain");
  10696. });
  10697. svr_.Get("/echo-params",
  10698. [](const httplib::Request &req, httplib::Response &res) {
  10699. std::string r;
  10700. for (const auto &p : req.params) {
  10701. if (!r.empty()) r += "&";
  10702. r += p.first + "=" + p.second;
  10703. }
  10704. res.set_content(r, "text/plain");
  10705. });
  10706. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10707. res.set_content(req.body, req.get_header_value("Content-Type"));
  10708. });
  10709. svr_.Post("/echo-headers",
  10710. [](const httplib::Request &req, httplib::Response &res) {
  10711. std::string r;
  10712. for (const auto &h : req.headers)
  10713. r += h.first + ": " + h.second + "\n";
  10714. res.set_content(r, "text/plain");
  10715. });
  10716. svr_.Post("/echo-params",
  10717. [](const httplib::Request &req, httplib::Response &res) {
  10718. std::string r = "params:";
  10719. for (const auto &p : req.params)
  10720. r += p.first + "=" + p.second + ";";
  10721. res.set_content(r + " body:" + req.body, "text/plain");
  10722. });
  10723. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10724. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10725. });
  10726. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10727. res.set_content("PUT:" + req.body, "text/plain");
  10728. });
  10729. svr_.Patch("/echo",
  10730. [](const httplib::Request &req, httplib::Response &res) {
  10731. res.set_content("PATCH:" + req.body, "text/plain");
  10732. });
  10733. svr_.Delete(
  10734. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10735. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10736. "text/plain");
  10737. });
  10738. svr_.Get("/head-test",
  10739. [](const httplib::Request &, httplib::Response &res) {
  10740. res.set_content("body for HEAD", "text/plain");
  10741. });
  10742. svr_.Options("/options",
  10743. [](const httplib::Request &, httplib::Response &res) {
  10744. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10745. });
  10746. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10747. svr_.wait_until_ready();
  10748. }
  10749. void TearDown() override {
  10750. svr_.stop();
  10751. if (thread_.joinable()) thread_.join();
  10752. }
  10753. httplib::Server svr_;
  10754. std::thread thread_;
  10755. };
  10756. // stream::Get tests
  10757. TEST_F(StreamApiTest, GetBasic) {
  10758. httplib::Client cli(HOST, PORT);
  10759. auto result = httplib::stream::Get(cli, "/hello");
  10760. ASSERT_TRUE(result.is_valid());
  10761. EXPECT_EQ(200, result.status());
  10762. EXPECT_EQ("Hello World!", read_body(result));
  10763. }
  10764. TEST_F(StreamApiTest, GetWithParams) {
  10765. httplib::Client cli(HOST, PORT);
  10766. httplib::Params params{{"foo", "bar"}};
  10767. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10768. ASSERT_TRUE(result.is_valid());
  10769. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10770. }
  10771. TEST_F(StreamApiTest, GetConnectionError) {
  10772. httplib::Client cli(HOST, 9999);
  10773. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10774. }
  10775. TEST_F(StreamApiTest, Get404) {
  10776. httplib::Client cli(HOST, PORT);
  10777. auto result = httplib::stream::Get(cli, "/nonexistent");
  10778. EXPECT_TRUE(result.is_valid());
  10779. EXPECT_EQ(404, result.status());
  10780. }
  10781. // stream::Post tests
  10782. TEST_F(StreamApiTest, PostBasic) {
  10783. httplib::Client cli(HOST, PORT);
  10784. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10785. "application/json");
  10786. ASSERT_TRUE(result.is_valid());
  10787. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10788. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10789. }
  10790. TEST_F(StreamApiTest, PostWithHeaders) {
  10791. httplib::Client cli(HOST, PORT);
  10792. httplib::Headers headers{{"X-Custom", "value"}};
  10793. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10794. "text/plain");
  10795. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10796. }
  10797. TEST_F(StreamApiTest, PostWithParams) {
  10798. httplib::Client cli(HOST, PORT);
  10799. httplib::Params params{{"k", "v"}};
  10800. auto result =
  10801. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10802. auto body = read_body(result);
  10803. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10804. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10805. }
  10806. TEST_F(StreamApiTest, PostLarge) {
  10807. httplib::Client cli(HOST, PORT);
  10808. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10809. size_t total = 0;
  10810. while (result.next()) {
  10811. total += result.size();
  10812. }
  10813. EXPECT_EQ(100u * 1024u, total);
  10814. }
  10815. // stream::Put/Patch tests
  10816. TEST_F(StreamApiTest, PutAndPatch) {
  10817. httplib::Client cli(HOST, PORT);
  10818. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10819. EXPECT_EQ("PUT:test", read_body(put));
  10820. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10821. EXPECT_EQ("PATCH:test", read_body(patch));
  10822. }
  10823. // stream::Delete tests
  10824. TEST_F(StreamApiTest, Delete) {
  10825. httplib::Client cli(HOST, PORT);
  10826. auto del1 = httplib::stream::Delete(cli, "/resource");
  10827. EXPECT_EQ("Deleted", read_body(del1));
  10828. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10829. EXPECT_EQ("Deleted:data", read_body(del2));
  10830. }
  10831. // stream::Head/Options tests
  10832. TEST_F(StreamApiTest, HeadAndOptions) {
  10833. httplib::Client cli(HOST, PORT);
  10834. auto head = httplib::stream::Head(cli, "/head-test");
  10835. EXPECT_TRUE(head.is_valid());
  10836. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10837. auto opts = httplib::stream::Options(cli, "/options");
  10838. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10839. }
  10840. // SSL stream::* tests
  10841. #ifdef CPPHTTPLIB_SSL_ENABLED
  10842. class SSLStreamApiTest : public ::testing::Test {
  10843. protected:
  10844. void SetUp() override {
  10845. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10846. res.set_content("Hello SSL!", "text/plain");
  10847. });
  10848. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10849. res.set_content(req.body, "text/plain");
  10850. });
  10851. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10852. svr_.wait_until_ready();
  10853. }
  10854. void TearDown() override {
  10855. svr_.stop();
  10856. if (thread_.joinable()) thread_.join();
  10857. }
  10858. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10859. std::thread thread_;
  10860. };
  10861. TEST_F(SSLStreamApiTest, GetAndPost) {
  10862. httplib::SSLClient cli("127.0.0.1", 8803);
  10863. cli.enable_server_certificate_verification(false);
  10864. auto get = httplib::stream::Get(cli, "/hello");
  10865. EXPECT_EQ("Hello SSL!", read_body(get));
  10866. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10867. EXPECT_EQ("test", read_body(post));
  10868. }
  10869. #endif
  10870. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10871. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10872. // BodyReader
  10873. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10874. // Test that read timeout during streaming is detected
  10875. // Use a large content-length response where server delays mid-stream
  10876. Server svr;
  10877. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10878. // Send a large response with delay in the middle
  10879. res.set_content_provider(
  10880. 1000, // content_length
  10881. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10882. if (offset < 100) {
  10883. // Send first 100 bytes immediately
  10884. std::string data(100, 'A');
  10885. sink.write(data.c_str(), data.size());
  10886. return true;
  10887. }
  10888. // Then delay longer than client timeout
  10889. std::this_thread::sleep_for(std::chrono::seconds(3));
  10890. std::string data(900, 'B');
  10891. sink.write(data.c_str(), data.size());
  10892. return true;
  10893. });
  10894. });
  10895. auto port = 8091;
  10896. std::thread t([&]() { svr.listen("localhost", port); });
  10897. svr.wait_until_ready();
  10898. Client cli("localhost", port);
  10899. cli.set_read_timeout(1, 0); // 1 second timeout
  10900. auto handle = cli.open_stream("GET", "/slow-stream");
  10901. ASSERT_TRUE(handle.is_valid());
  10902. char buf[256];
  10903. ssize_t total = 0;
  10904. ssize_t n;
  10905. bool got_error = false;
  10906. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10907. total += n;
  10908. }
  10909. if (n < 0) {
  10910. got_error = true;
  10911. // Should be timeout or read error
  10912. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10913. handle.get_read_error() == Error::Read)
  10914. << "Actual error: " << to_string(handle.get_read_error());
  10915. }
  10916. // Either we got an error, or we got less data than expected
  10917. EXPECT_TRUE(got_error || total < 1000)
  10918. << "Expected timeout but got all " << total << " bytes";
  10919. svr.stop();
  10920. t.join();
  10921. }
  10922. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10923. // Test connection closed detection via BodyReader
  10924. Server svr;
  10925. std::atomic<bool> close_now{false};
  10926. svr.Get("/will-close", [&](const Request &, Response &res) {
  10927. res.set_content_provider(
  10928. 10000, // Large content_length that we won't fully send
  10929. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10930. if (offset < 100) {
  10931. std::string data(100, 'X');
  10932. sink.write(data.c_str(), data.size());
  10933. return true;
  10934. }
  10935. // Wait for signal then abort
  10936. while (!close_now) {
  10937. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10938. }
  10939. return false; // Abort - server will close connection
  10940. });
  10941. });
  10942. auto port = 8092;
  10943. std::thread t([&]() { svr.listen("localhost", port); });
  10944. svr.wait_until_ready();
  10945. Client cli("localhost", port);
  10946. auto handle = cli.open_stream("GET", "/will-close");
  10947. ASSERT_TRUE(handle.is_valid());
  10948. char buf[256];
  10949. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10950. EXPECT_GT(n, 0) << "First read should succeed";
  10951. // Signal server to close
  10952. close_now = true;
  10953. // Keep reading until error or EOF
  10954. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10955. // Keep reading
  10956. }
  10957. // Should get an error since content_length wasn't satisfied
  10958. if (n < 0) {
  10959. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10960. handle.get_read_error() == Error::Read)
  10961. << "Actual error: " << to_string(handle.get_read_error());
  10962. }
  10963. svr.stop();
  10964. t.join();
  10965. }
  10966. #ifdef CPPHTTPLIB_SSL_ENABLED
  10967. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10968. // Test that read timeout during SSL streaming is detected
  10969. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10970. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10971. res.set_content_provider(
  10972. 1000, "text/plain",
  10973. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10974. if (offset < 100) {
  10975. std::string data(100, 'A');
  10976. sink.write(data.c_str(), data.size());
  10977. return true;
  10978. }
  10979. std::this_thread::sleep_for(std::chrono::seconds(3));
  10980. std::string data(900, 'B');
  10981. sink.write(data.c_str(), data.size());
  10982. return true;
  10983. });
  10984. });
  10985. auto port = 8093;
  10986. std::thread t([&]() { svr.listen("localhost", port); });
  10987. svr.wait_until_ready();
  10988. SSLClient cli("localhost", port);
  10989. cli.enable_server_certificate_verification(false);
  10990. cli.set_read_timeout(1, 0); // 1 second timeout
  10991. auto handle = cli.open_stream("GET", "/slow-stream");
  10992. ASSERT_TRUE(handle.is_valid());
  10993. char buf[256];
  10994. ssize_t total = 0;
  10995. ssize_t n;
  10996. bool got_error = false;
  10997. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10998. total += n;
  10999. }
  11000. if (n < 0) {
  11001. got_error = true;
  11002. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11003. handle.get_read_error() == Error::Read)
  11004. << "Actual error: " << to_string(handle.get_read_error());
  11005. }
  11006. EXPECT_TRUE(got_error || total < 1000)
  11007. << "Expected timeout but got all " << total << " bytes";
  11008. svr.stop();
  11009. t.join();
  11010. }
  11011. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11012. // Test SSL connection closed detection
  11013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11014. std::atomic<bool> close_now{false};
  11015. svr.Get("/will-close", [&](const Request &, Response &res) {
  11016. res.set_content_provider(
  11017. 10000, "text/plain",
  11018. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11019. if (offset < 100) {
  11020. std::string data(100, 'X');
  11021. sink.write(data.c_str(), data.size());
  11022. return true;
  11023. }
  11024. while (!close_now) {
  11025. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11026. }
  11027. return false;
  11028. });
  11029. });
  11030. auto port = 8094;
  11031. std::thread t([&]() { svr.listen("localhost", port); });
  11032. svr.wait_until_ready();
  11033. SSLClient cli("localhost", port);
  11034. cli.enable_server_certificate_verification(false);
  11035. auto handle = cli.open_stream("GET", "/will-close");
  11036. ASSERT_TRUE(handle.is_valid());
  11037. char buf[256];
  11038. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11039. EXPECT_GT(n, 0);
  11040. // Signal server to close
  11041. close_now = true;
  11042. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11043. // Keep reading
  11044. }
  11045. if (n < 0) {
  11046. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11047. handle.get_read_error() == Error::Read)
  11048. << "Actual error: " << to_string(handle.get_read_error());
  11049. }
  11050. svr.stop();
  11051. t.join();
  11052. }
  11053. #endif
  11054. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  11055. using namespace httplib;
  11056. // Create a test file
  11057. const char *fname = "etag_testfile.txt";
  11058. const char *content = "etag-content";
  11059. {
  11060. std::ofstream ofs(fname);
  11061. ofs << content;
  11062. ASSERT_TRUE(ofs.good());
  11063. }
  11064. Server svr;
  11065. svr.set_mount_point("/static", ".");
  11066. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11067. svr.wait_until_ready();
  11068. Client cli(HOST, PORT);
  11069. // First request: should get 200 with ETag header
  11070. auto res1 = cli.Get("/static/etag_testfile.txt");
  11071. ASSERT_TRUE(res1);
  11072. ASSERT_EQ(200, res1->status);
  11073. ASSERT_TRUE(res1->has_header("ETag"));
  11074. std::string etag = res1->get_header_value("ETag");
  11075. EXPECT_FALSE(etag.empty());
  11076. // Verify ETag format: W/"hex-hex"
  11077. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  11078. EXPECT_EQ('W', etag[0]);
  11079. EXPECT_EQ('/', etag[1]);
  11080. EXPECT_EQ('"', etag[2]);
  11081. EXPECT_EQ('"', etag.back());
  11082. // Exact match: expect 304 Not Modified
  11083. Headers h2 = {{"If-None-Match", etag}};
  11084. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  11085. ASSERT_TRUE(res2);
  11086. EXPECT_EQ(304, res2->status);
  11087. // Wildcard match: expect 304 Not Modified
  11088. Headers h3 = {{"If-None-Match", "*"}};
  11089. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  11090. ASSERT_TRUE(res3);
  11091. EXPECT_EQ(304, res3->status);
  11092. // Non-matching ETag: expect 200
  11093. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  11094. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  11095. ASSERT_TRUE(res4);
  11096. EXPECT_EQ(200, res4->status);
  11097. // Multiple ETags with one matching: expect 304
  11098. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  11099. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  11100. ASSERT_TRUE(res5);
  11101. EXPECT_EQ(304, res5->status);
  11102. svr.stop();
  11103. t.join();
  11104. std::remove(fname);
  11105. }
  11106. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  11107. using namespace httplib;
  11108. Server svr;
  11109. svr.set_mount_point("/static", ".");
  11110. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11111. svr.wait_until_ready();
  11112. Client cli(HOST, PORT);
  11113. // Send If-None-Match: * to a non-existent file
  11114. Headers h = {{"If-None-Match", "*"}};
  11115. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  11116. ASSERT_TRUE(res);
  11117. EXPECT_EQ(404, res->status);
  11118. svr.stop();
  11119. t.join();
  11120. }
  11121. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  11122. using namespace httplib;
  11123. // Create a test file
  11124. const char *fname = "ims_testfile.txt";
  11125. const char *content = "if-modified-since-test";
  11126. {
  11127. std::ofstream ofs(fname);
  11128. ofs << content;
  11129. ASSERT_TRUE(ofs.good());
  11130. }
  11131. Server svr;
  11132. svr.set_mount_point("/static", ".");
  11133. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11134. svr.wait_until_ready();
  11135. Client cli(HOST, PORT);
  11136. // First request: should get 200 with Last-Modified header
  11137. auto res1 = cli.Get("/static/ims_testfile.txt");
  11138. ASSERT_TRUE(res1);
  11139. ASSERT_EQ(200, res1->status);
  11140. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11141. std::string last_modified = res1->get_header_value("Last-Modified");
  11142. EXPECT_FALSE(last_modified.empty());
  11143. // If-Modified-Since with same time: expect 304
  11144. Headers h2 = {{"If-Modified-Since", last_modified}};
  11145. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  11146. ASSERT_TRUE(res2);
  11147. EXPECT_EQ(304, res2->status);
  11148. // If-Modified-Since with future time: expect 304
  11149. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11150. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  11151. ASSERT_TRUE(res3);
  11152. EXPECT_EQ(304, res3->status);
  11153. // If-Modified-Since with past time: expect 200
  11154. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11155. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  11156. ASSERT_TRUE(res4);
  11157. EXPECT_EQ(200, res4->status);
  11158. // If-None-Match takes precedence over If-Modified-Since
  11159. // (send matching ETag with old If-Modified-Since -> should still be 304)
  11160. ASSERT_TRUE(res1->has_header("ETag"));
  11161. std::string etag = res1->get_header_value("ETag");
  11162. Headers h5 = {{"If-None-Match", etag},
  11163. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11164. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  11165. ASSERT_TRUE(res5);
  11166. EXPECT_EQ(304, res5->status);
  11167. svr.stop();
  11168. t.join();
  11169. std::remove(fname);
  11170. }
  11171. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  11172. using namespace httplib;
  11173. Server svr;
  11174. // Endpoint that returns compressible content
  11175. svr.Get("/compressible", [](const Request &, Response &res) {
  11176. // Return a large enough body to trigger compression
  11177. std::string body(1000, 'a');
  11178. res.set_content(body, "text/plain");
  11179. });
  11180. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11181. svr.wait_until_ready();
  11182. Client cli(HOST, PORT);
  11183. // Request with gzip support: should get Vary header when compressed
  11184. cli.set_compress(true);
  11185. auto res1 = cli.Get("/compressible");
  11186. ASSERT_TRUE(res1);
  11187. EXPECT_EQ(200, res1->status);
  11188. // If Content-Encoding is set, Vary should also be set
  11189. if (res1->has_header("Content-Encoding")) {
  11190. EXPECT_TRUE(res1->has_header("Vary"));
  11191. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  11192. }
  11193. // Request without Accept-Encoding header: should not have compression
  11194. Headers h_no_compress;
  11195. auto res2 = cli.Get("/compressible", h_no_compress);
  11196. ASSERT_TRUE(res2);
  11197. EXPECT_EQ(200, res2->status);
  11198. // Verify Vary header is present when compression is applied
  11199. // (the exact behavior depends on server configuration)
  11200. svr.stop();
  11201. t.join();
  11202. }
  11203. TEST(ETagTest, IfRangeWithETag) {
  11204. using namespace httplib;
  11205. // Create a test file with known content
  11206. const char *fname = "if_range_testfile.txt";
  11207. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  11208. {
  11209. std::ofstream ofs(fname);
  11210. ofs << content;
  11211. ASSERT_TRUE(ofs.good());
  11212. }
  11213. Server svr;
  11214. svr.set_mount_point("/static", ".");
  11215. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11216. svr.wait_until_ready();
  11217. Client cli(HOST, PORT);
  11218. // First request: get ETag
  11219. auto res1 = cli.Get("/static/if_range_testfile.txt");
  11220. ASSERT_TRUE(res1);
  11221. ASSERT_EQ(200, res1->status);
  11222. ASSERT_TRUE(res1->has_header("ETag"));
  11223. std::string etag = res1->get_header_value("ETag");
  11224. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  11225. // Since our server generates weak ETags (W/"..."), If-Range with our
  11226. // ETag should NOT result in partial content - it should return full content.
  11227. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  11228. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  11229. ASSERT_TRUE(res2);
  11230. // Weak ETag in If-Range -> full content (200), not partial (206)
  11231. EXPECT_EQ(200, res2->status);
  11232. EXPECT_EQ(content, res2->body);
  11233. EXPECT_FALSE(res2->has_header("Content-Range"));
  11234. // Range request with non-matching If-Range (ETag): should get 200 (full
  11235. // content)
  11236. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  11237. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  11238. ASSERT_TRUE(res3);
  11239. EXPECT_EQ(200, res3->status);
  11240. EXPECT_EQ(content, res3->body);
  11241. EXPECT_FALSE(res3->has_header("Content-Range"));
  11242. // Range request with strong ETag (hypothetical - our server doesn't generate
  11243. // strong ETags, but if client sends a strong ETag that doesn't match, it
  11244. // should return full content)
  11245. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  11246. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  11247. ASSERT_TRUE(res4);
  11248. EXPECT_EQ(200, res4->status);
  11249. EXPECT_EQ(content, res4->body);
  11250. EXPECT_FALSE(res4->has_header("Content-Range"));
  11251. svr.stop();
  11252. t.join();
  11253. std::remove(fname);
  11254. }
  11255. TEST(ETagTest, IfRangeWithDate) {
  11256. using namespace httplib;
  11257. // Create a test file
  11258. const char *fname = "if_range_date_testfile.txt";
  11259. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  11260. {
  11261. std::ofstream ofs(fname);
  11262. ofs << content;
  11263. ASSERT_TRUE(ofs.good());
  11264. }
  11265. Server svr;
  11266. svr.set_mount_point("/static", ".");
  11267. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11268. svr.wait_until_ready();
  11269. Client cli(HOST, PORT);
  11270. // First request: get Last-Modified
  11271. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  11272. ASSERT_TRUE(res1);
  11273. ASSERT_EQ(200, res1->status);
  11274. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11275. std::string last_modified = res1->get_header_value("Last-Modified");
  11276. // Range request with matching If-Range (date): should get 206
  11277. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  11278. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  11279. ASSERT_TRUE(res2);
  11280. EXPECT_EQ(206, res2->status);
  11281. EXPECT_EQ("FGHIJ", res2->body);
  11282. // Range request with old If-Range date: should get 200 (full content)
  11283. Headers h3 = {{"Range", "bytes=5-9"},
  11284. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11285. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11286. ASSERT_TRUE(res3);
  11287. EXPECT_EQ(200, res3->status);
  11288. EXPECT_EQ(content, res3->body);
  11289. // Range request with future If-Range date: should get 206
  11290. Headers h4 = {{"Range", "bytes=0-4"},
  11291. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11292. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11293. ASSERT_TRUE(res4);
  11294. EXPECT_EQ(206, res4->status);
  11295. EXPECT_EQ("ABCDE", res4->body);
  11296. svr.stop();
  11297. t.join();
  11298. std::remove(fname);
  11299. }
  11300. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11301. using namespace httplib;
  11302. const char *fname = "etag_malformed.txt";
  11303. const char *content = "malformed-etag";
  11304. {
  11305. std::ofstream ofs(fname);
  11306. ofs << content;
  11307. ASSERT_TRUE(ofs.good());
  11308. }
  11309. Server svr;
  11310. svr.set_mount_point("/static", ".");
  11311. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11312. svr.wait_until_ready();
  11313. Client cli(HOST, PORT);
  11314. // baseline: should get 200 and an ETag
  11315. auto res1 = cli.Get("/static/etag_malformed.txt");
  11316. ASSERT_TRUE(res1);
  11317. ASSERT_EQ(200, res1->status);
  11318. ASSERT_TRUE(res1->has_header("ETag"));
  11319. // Malformed ETag value (missing quotes) should be treated as non-matching
  11320. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  11321. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  11322. ASSERT_TRUE(res_bad);
  11323. EXPECT_EQ(200, res_bad->status);
  11324. // Whitespace-only header value should be considered invalid / non-matching
  11325. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  11326. "Host: localhost\r\n"
  11327. "If-None-Match: \r\n"
  11328. "Connection: close\r\n"
  11329. "\r\n";
  11330. std::string out;
  11331. ASSERT_TRUE(send_request(5, raw_req, &out));
  11332. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11333. svr.stop();
  11334. t.join();
  11335. std::remove(fname);
  11336. }
  11337. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  11338. using namespace httplib;
  11339. const char *fname = "ims_invalid_format.txt";
  11340. const char *content = "ims-bad-format";
  11341. {
  11342. std::ofstream ofs(fname);
  11343. ofs << content;
  11344. ASSERT_TRUE(ofs.good());
  11345. }
  11346. Server svr;
  11347. svr.set_mount_point("/static", ".");
  11348. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11349. svr.wait_until_ready();
  11350. Client cli(HOST, PORT);
  11351. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11352. ASSERT_TRUE(res1);
  11353. ASSERT_EQ(200, res1->status);
  11354. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11355. // If-Modified-Since with invalid format should not result in 304
  11356. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11357. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11358. ASSERT_TRUE(res_bad);
  11359. EXPECT_EQ(200, res_bad->status);
  11360. // If-Range with invalid date format should be treated as mismatch -> full
  11361. // content (200)
  11362. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11363. {"If-Range", "invalid-date"}};
  11364. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11365. ASSERT_TRUE(res_ifrange);
  11366. EXPECT_EQ(200, res_ifrange->status);
  11367. svr.stop();
  11368. t.join();
  11369. std::remove(fname);
  11370. }
  11371. TEST(ETagTest, IfRangeWithMalformedETag) {
  11372. using namespace httplib;
  11373. const char *fname = "ifrange_malformed.txt";
  11374. const std::string content = "0123456789";
  11375. {
  11376. std::ofstream ofs(fname);
  11377. ofs << content;
  11378. ASSERT_TRUE(ofs.good());
  11379. }
  11380. Server svr;
  11381. svr.set_mount_point("/static", ".");
  11382. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11383. svr.wait_until_ready();
  11384. Client cli(HOST, PORT);
  11385. // First request: get ETag
  11386. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11387. ASSERT_TRUE(res1);
  11388. ASSERT_EQ(200, res1->status);
  11389. ASSERT_TRUE(res1->has_header("ETag"));
  11390. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11391. // full content (200)
  11392. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11393. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11394. ASSERT_TRUE(res2);
  11395. EXPECT_EQ(200, res2->status);
  11396. EXPECT_EQ(content, res2->body);
  11397. svr.stop();
  11398. t.join();
  11399. std::remove(fname);
  11400. }
  11401. TEST(ETagTest, ExtremeLargeDateValues) {
  11402. using namespace httplib;
  11403. const char *fname = "ims_extreme_date.txt";
  11404. const char *content = "ims-extreme-date";
  11405. {
  11406. std::ofstream ofs(fname);
  11407. ofs << content;
  11408. ASSERT_TRUE(ofs.good());
  11409. }
  11410. Server svr;
  11411. svr.set_mount_point("/static", ".");
  11412. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11413. svr.wait_until_ready();
  11414. Client cli(HOST, PORT);
  11415. auto res1 = cli.Get(std::string("/static/") + fname);
  11416. ASSERT_TRUE(res1);
  11417. ASSERT_EQ(200, res1->status);
  11418. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11419. // Extremely large year that may overflow date parsing routines.
  11420. Headers h_large_date = {
  11421. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11422. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11423. ASSERT_TRUE(res_bad);
  11424. // Expect server to treat this as invalid/mismatch and return full content
  11425. EXPECT_EQ(200, res_bad->status);
  11426. // If-Range with extremely large date should be treated as mismatch -> full
  11427. // content (200)
  11428. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11429. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11430. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11431. ASSERT_TRUE(res_ifrange);
  11432. EXPECT_EQ(200, res_ifrange->status);
  11433. svr.stop();
  11434. t.join();
  11435. std::remove(fname);
  11436. }
  11437. TEST(ETagTest, NegativeFileModificationTime) {
  11438. using namespace httplib;
  11439. const char *fname = "ims_negative_mtime.txt";
  11440. const std::string content = "negative-mtime";
  11441. {
  11442. std::ofstream ofs(fname);
  11443. ofs << content;
  11444. ASSERT_TRUE(ofs.good());
  11445. }
  11446. // Try to set file mtime to a negative value. This may fail on some
  11447. // platforms/filesystems; if it fails, the test will still verify server
  11448. // behaves safely by performing a regular conditional request.
  11449. #if defined(__APPLE__) || defined(__linux__)
  11450. bool set_negative = false;
  11451. do {
  11452. struct timeval times[2];
  11453. // access time: now
  11454. times[0].tv_sec = time(nullptr);
  11455. times[0].tv_usec = 0;
  11456. // modification time: negative (e.g., -1)
  11457. times[1].tv_sec = -1;
  11458. times[1].tv_usec = 0;
  11459. if (utimes(fname, times) == 0) { set_negative = true; }
  11460. } while (0);
  11461. #else
  11462. bool set_negative = false;
  11463. #endif
  11464. Server svr;
  11465. svr.set_mount_point("/static", ".");
  11466. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11467. svr.wait_until_ready();
  11468. Client cli(HOST, PORT);
  11469. auto res1 = cli.Get(std::string("/static/") + fname);
  11470. ASSERT_TRUE(res1);
  11471. ASSERT_EQ(200, res1->status);
  11472. bool has_last_modified = res1->has_header("Last-Modified");
  11473. std::string last_modified;
  11474. if (has_last_modified) {
  11475. last_modified = res1->get_header_value("Last-Modified");
  11476. }
  11477. if (set_negative) {
  11478. // If we successfully set a negative mtime, ensure server returns a
  11479. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11480. // with an old date and ensure server handles it without crash.
  11481. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11482. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11483. ASSERT_TRUE(res2);
  11484. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11485. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11486. } else {
  11487. // Could not set negative mtime on this platform; fall back to verifying
  11488. // that normal invalid/malformed dates are treated safely (non-304).
  11489. Headers h_bad_date = {
  11490. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11491. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11492. ASSERT_TRUE(res_bad);
  11493. EXPECT_EQ(200, res_bad->status);
  11494. }
  11495. svr.stop();
  11496. t.join();
  11497. std::remove(fname);
  11498. }
  11499. //==============================================================================
  11500. // SSE Parsing Tests
  11501. //==============================================================================
  11502. class SSEParsingTest : public ::testing::Test {
  11503. protected:
  11504. // Test helper that mimics SSE parsing behavior
  11505. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11506. int &retry_ms) {
  11507. // Blank line signals end of event
  11508. if (line.empty() || line == "\r") { return true; }
  11509. // Lines starting with ':' are comments (ignored)
  11510. if (!line.empty() && line[0] == ':') { return false; }
  11511. // Find the colon separator
  11512. auto colon_pos = line.find(':');
  11513. if (colon_pos == std::string::npos) {
  11514. // Line with no colon is treated as field name with empty value
  11515. return false;
  11516. }
  11517. std::string field = line.substr(0, colon_pos);
  11518. std::string value;
  11519. // Value starts after colon, skip optional single space
  11520. if (colon_pos + 1 < line.size()) {
  11521. size_t value_start = colon_pos + 1;
  11522. if (line[value_start] == ' ') { value_start++; }
  11523. value = line.substr(value_start);
  11524. // Remove trailing \r if present
  11525. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11526. }
  11527. // Handle known fields
  11528. if (field == "event") {
  11529. msg.event = value;
  11530. } else if (field == "data") {
  11531. // Multiple data lines are concatenated with newlines
  11532. if (!msg.data.empty()) { msg.data += "\n"; }
  11533. msg.data += value;
  11534. } else if (field == "id") {
  11535. // Empty id is valid (clears the last event ID)
  11536. msg.id = value;
  11537. } else if (field == "retry") {
  11538. // Parse retry interval in milliseconds
  11539. {
  11540. int v = 0;
  11541. auto res =
  11542. detail::from_chars(value.data(), value.data() + value.size(), v);
  11543. if (res.ec == std::errc{}) { retry_ms = v; }
  11544. }
  11545. }
  11546. // Unknown fields are ignored per SSE spec
  11547. return false;
  11548. }
  11549. };
  11550. // Test: Single-line data
  11551. TEST_F(SSEParsingTest, SingleLineData) {
  11552. sse::SSEMessage msg;
  11553. int retry_ms = 3000;
  11554. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11555. EXPECT_EQ(msg.data, "hello");
  11556. EXPECT_EQ(msg.event, "message");
  11557. // Blank line ends event
  11558. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11559. }
  11560. // Test: Multi-line data
  11561. TEST_F(SSEParsingTest, MultiLineData) {
  11562. sse::SSEMessage msg;
  11563. int retry_ms = 3000;
  11564. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11565. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11566. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11567. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11568. }
  11569. // Test: Custom event types
  11570. TEST_F(SSEParsingTest, CustomEventType) {
  11571. sse::SSEMessage msg;
  11572. int retry_ms = 3000;
  11573. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11574. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11575. EXPECT_EQ(msg.event, "update");
  11576. EXPECT_EQ(msg.data, "payload");
  11577. }
  11578. // Test: Event ID handling
  11579. TEST_F(SSEParsingTest, EventIdHandling) {
  11580. sse::SSEMessage msg;
  11581. int retry_ms = 3000;
  11582. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11583. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11584. EXPECT_EQ(msg.id, "12345");
  11585. }
  11586. // Test: Empty event ID (clears last event ID)
  11587. TEST_F(SSEParsingTest, EmptyEventId) {
  11588. sse::SSEMessage msg;
  11589. msg.id = "previous";
  11590. int retry_ms = 3000;
  11591. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11592. EXPECT_EQ(msg.id, "");
  11593. }
  11594. // Test: Retry field parsing
  11595. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11596. sse::SSEMessage msg;
  11597. int retry_ms = 3000;
  11598. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11599. EXPECT_EQ(retry_ms, 5000);
  11600. }
  11601. // Test: Invalid retry value
  11602. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11603. sse::SSEMessage msg;
  11604. int retry_ms = 3000;
  11605. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11606. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11607. }
  11608. // Test: Comments (lines starting with :)
  11609. TEST_F(SSEParsingTest, CommentsIgnored) {
  11610. sse::SSEMessage msg;
  11611. int retry_ms = 3000;
  11612. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11613. EXPECT_EQ(msg.data, "");
  11614. EXPECT_EQ(msg.event, "message");
  11615. }
  11616. // Test: Colon in value
  11617. TEST_F(SSEParsingTest, ColonInValue) {
  11618. sse::SSEMessage msg;
  11619. int retry_ms = 3000;
  11620. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11621. EXPECT_EQ(msg.data, "hello:world:test");
  11622. }
  11623. // Test: Line with no colon (field name only)
  11624. TEST_F(SSEParsingTest, FieldNameOnly) {
  11625. sse::SSEMessage msg;
  11626. int retry_ms = 3000;
  11627. // According to SSE spec, this is treated as field name with empty value
  11628. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11629. // Since we don't recognize "data" without colon, data should be empty
  11630. EXPECT_EQ(msg.data, "");
  11631. }
  11632. // Test: Trailing \r handling
  11633. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11634. sse::SSEMessage msg;
  11635. int retry_ms = 3000;
  11636. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11637. EXPECT_EQ(msg.data, "hello");
  11638. }
  11639. // Test: Unknown fields ignored
  11640. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11641. sse::SSEMessage msg;
  11642. int retry_ms = 3000;
  11643. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11644. EXPECT_EQ(msg.data, "");
  11645. EXPECT_EQ(msg.event, "message");
  11646. }
  11647. // Test: Space after colon is optional
  11648. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11649. sse::SSEMessage msg1, msg2;
  11650. int retry_ms = 3000;
  11651. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11652. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11653. EXPECT_EQ(msg1.data, "hello");
  11654. EXPECT_EQ(msg2.data, "hello");
  11655. }
  11656. // Test: SSEMessage clear
  11657. TEST_F(SSEParsingTest, MessageClear) {
  11658. sse::SSEMessage msg;
  11659. msg.event = "custom";
  11660. msg.data = "some data";
  11661. msg.id = "123";
  11662. msg.clear();
  11663. EXPECT_EQ(msg.event, "message");
  11664. EXPECT_EQ(msg.data, "");
  11665. EXPECT_EQ(msg.id, "");
  11666. }
  11667. // Test: Complete event parsing
  11668. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11669. sse::SSEMessage msg;
  11670. int retry_ms = 3000;
  11671. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11672. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11673. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11674. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11675. // Blank line ends event
  11676. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11677. EXPECT_EQ(msg.event, "notification");
  11678. EXPECT_EQ(msg.id, "evt-42");
  11679. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11680. EXPECT_EQ(retry_ms, 1000);
  11681. }
  11682. //==============================================================================
  11683. // Integration Tests with Server
  11684. //==============================================================================
  11685. class SSEIntegrationTest : public ::testing::Test {
  11686. protected:
  11687. void SetUp() override {
  11688. stop_server_.store(false);
  11689. events_.clear();
  11690. server_ = httplib::detail::make_unique<Server>();
  11691. setup_server();
  11692. start_server();
  11693. }
  11694. void TearDown() override {
  11695. stop_server_.store(true);
  11696. event_cv_.notify_all();
  11697. server_->stop();
  11698. if (server_thread_.joinable()) { server_thread_.join(); }
  11699. }
  11700. void setup_server() {
  11701. // Simple SSE endpoint
  11702. server_->Get("/events", [this](const Request &req, Response &res) {
  11703. auto last_id = req.get_header_value("Last-Event-ID");
  11704. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11705. res.set_chunked_content_provider(
  11706. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11707. std::unique_lock<std::mutex> lock(event_mutex_);
  11708. if (event_cv_.wait_for(
  11709. lock, std::chrono::milliseconds(200), [this] {
  11710. return !events_.empty() || stop_server_.load();
  11711. })) {
  11712. if (stop_server_.load()) { return false; }
  11713. if (!events_.empty()) {
  11714. std::string event = events_.front();
  11715. events_.erase(events_.begin());
  11716. sink.write(event.data(), event.size());
  11717. return true;
  11718. }
  11719. }
  11720. return !stop_server_.load();
  11721. });
  11722. });
  11723. // Endpoint that returns error
  11724. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11725. res.status = 500;
  11726. res.set_content("Internal Server Error", "text/plain");
  11727. });
  11728. // Endpoint for custom event types
  11729. server_->Get("/custom-events", [](const Request &, Response &res) {
  11730. res.set_chunked_content_provider(
  11731. "text/event-stream", [](size_t offset, DataSink &sink) {
  11732. if (offset == 0) {
  11733. std::string event = "event: update\ndata: updated\n\n"
  11734. "event: delete\ndata: deleted\n\n";
  11735. sink.write(event.data(), event.size());
  11736. }
  11737. return false; // End stream after sending
  11738. });
  11739. });
  11740. }
  11741. void start_server() {
  11742. port_ = server_->bind_to_any_port(HOST);
  11743. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11744. // Wait for server to start
  11745. while (!server_->is_running()) {
  11746. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11747. }
  11748. }
  11749. int get_port() const { return port_; }
  11750. void send_event(const std::string &event) {
  11751. std::lock_guard<std::mutex> lock(event_mutex_);
  11752. events_.push_back(event);
  11753. event_cv_.notify_all();
  11754. }
  11755. std::unique_ptr<Server> server_;
  11756. std::thread server_thread_;
  11757. std::mutex event_mutex_;
  11758. std::condition_variable event_cv_;
  11759. std::vector<std::string> events_;
  11760. std::atomic<bool> stop_server_{false};
  11761. std::string last_received_event_id_;
  11762. int port_ = 0;
  11763. };
  11764. // Test: Successful connection and on_open callback
  11765. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11766. // Add a simple endpoint that sends one event and closes
  11767. server_->Get("/simple-event", [](const Request &, Response &res) {
  11768. res.set_chunked_content_provider(
  11769. "text/event-stream", [](size_t offset, DataSink &sink) {
  11770. if (offset == 0) {
  11771. std::string event = "data: hello\n\n";
  11772. sink.write(event.data(), event.size());
  11773. }
  11774. return false; // Close stream after sending
  11775. });
  11776. });
  11777. Client client("localhost", get_port());
  11778. sse::SSEClient sse(client, "/simple-event");
  11779. std::atomic<bool> open_called{false};
  11780. std::atomic<bool> message_received{false};
  11781. sse.on_open([&open_called]() { open_called.store(true); });
  11782. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11783. if (msg.data == "hello") { message_received.store(true); }
  11784. });
  11785. sse.set_reconnect_interval(100);
  11786. sse.set_max_reconnect_attempts(1);
  11787. // Start async
  11788. sse.start_async();
  11789. // Wait for message to be processed
  11790. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11791. sse.stop();
  11792. EXPECT_TRUE(open_called.load());
  11793. EXPECT_TRUE(message_received.load());
  11794. }
  11795. // Test: on_message callback
  11796. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11797. // Endpoint that sends multiple events then closes
  11798. server_->Get("/multi-event", [](const Request &, Response &res) {
  11799. res.set_chunked_content_provider(
  11800. "text/event-stream", [](size_t offset, DataSink &sink) {
  11801. if (offset == 0) {
  11802. std::string events = "data: message1\n\ndata: message2\n\n";
  11803. sink.write(events.data(), events.size());
  11804. }
  11805. return false;
  11806. });
  11807. });
  11808. Client client("localhost", get_port());
  11809. sse::SSEClient sse(client, "/multi-event");
  11810. std::vector<std::string> received_messages;
  11811. std::mutex messages_mutex;
  11812. sse.on_message([&](const sse::SSEMessage &msg) {
  11813. std::lock_guard<std::mutex> lock(messages_mutex);
  11814. received_messages.push_back(msg.data);
  11815. });
  11816. sse.set_reconnect_interval(100);
  11817. sse.set_max_reconnect_attempts(1);
  11818. sse.start_async();
  11819. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11820. sse.stop();
  11821. std::lock_guard<std::mutex> lock(messages_mutex);
  11822. EXPECT_GE(received_messages.size(), 2u);
  11823. if (received_messages.size() >= 2) {
  11824. EXPECT_EQ(received_messages[0], "message1");
  11825. EXPECT_EQ(received_messages[1], "message2");
  11826. }
  11827. }
  11828. // Test: on_event for specific types
  11829. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11830. Client client("localhost", get_port());
  11831. sse::SSEClient sse(client, "/custom-events");
  11832. std::atomic<bool> update_received{false};
  11833. std::atomic<bool> delete_received{false};
  11834. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11835. if (msg.data == "updated") { update_received.store(true); }
  11836. });
  11837. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11838. if (msg.data == "deleted") { delete_received.store(true); }
  11839. });
  11840. sse.set_max_reconnect_attempts(1);
  11841. sse.start_async();
  11842. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11843. sse.stop();
  11844. EXPECT_TRUE(update_received.load());
  11845. EXPECT_TRUE(delete_received.load());
  11846. }
  11847. // Test: on_error callback on connection failure
  11848. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11849. // Connect to a non-existent port
  11850. Client client("localhost", 59999);
  11851. sse::SSEClient sse(client, "/events");
  11852. std::atomic<bool> error_called{false};
  11853. Error received_error = Error::Success;
  11854. sse.on_error([&](Error err) {
  11855. error_called.store(true);
  11856. received_error = err;
  11857. });
  11858. sse.set_reconnect_interval(50);
  11859. sse.set_max_reconnect_attempts(1);
  11860. sse.start_async();
  11861. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11862. sse.stop();
  11863. EXPECT_TRUE(error_called.load());
  11864. EXPECT_NE(received_error, Error::Success);
  11865. }
  11866. // Test: Last-Event-ID header sent on reconnect
  11867. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11868. // Endpoint that sends event with ID
  11869. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11870. res.set_chunked_content_provider(
  11871. "text/event-stream", [](size_t offset, DataSink &sink) {
  11872. if (offset == 0) {
  11873. std::string event = "id: evt-123\ndata: test\n\n";
  11874. sink.write(event.data(), event.size());
  11875. }
  11876. return false;
  11877. });
  11878. });
  11879. Client client("localhost", get_port());
  11880. sse::SSEClient sse(client, "/event-with-id");
  11881. std::atomic<bool> id_received{false};
  11882. sse.on_message([&](const sse::SSEMessage &msg) {
  11883. if (!msg.id.empty()) { id_received.store(true); }
  11884. });
  11885. sse.set_reconnect_interval(100);
  11886. sse.set_max_reconnect_attempts(1);
  11887. sse.start_async();
  11888. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11889. sse.stop();
  11890. EXPECT_TRUE(id_received.load());
  11891. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11892. }
  11893. // Test: Manual stop
  11894. TEST_F(SSEIntegrationTest, ManualStop) {
  11895. // Endpoint that sends one event and stays open briefly
  11896. std::atomic<bool> handler_running{true};
  11897. server_->Get("/stay-open", [&handler_running](const Request &,
  11898. Response &res) {
  11899. res.set_chunked_content_provider(
  11900. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11901. if (offset == 0) {
  11902. std::string event = "data: connected\n\n";
  11903. sink.write(event.data(), event.size());
  11904. }
  11905. // Keep connection open while handler_running is true
  11906. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  11907. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11908. }
  11909. return false;
  11910. });
  11911. });
  11912. Client client("localhost", get_port());
  11913. sse::SSEClient sse(client, "/stay-open");
  11914. std::atomic<bool> connected{false};
  11915. sse.on_open([&connected]() { connected.store(true); });
  11916. sse.set_reconnect_interval(100);
  11917. sse.set_max_reconnect_attempts(1);
  11918. sse.start_async();
  11919. // Wait for connection to establish
  11920. for (int i = 0; i < 20 && !connected.load(); ++i) {
  11921. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11922. }
  11923. EXPECT_TRUE(connected.load());
  11924. EXPECT_TRUE(sse.is_connected());
  11925. // Signal handler to stop
  11926. handler_running.store(false);
  11927. // Stop SSE client
  11928. sse.stop();
  11929. EXPECT_FALSE(sse.is_connected());
  11930. }
  11931. // Test: SSEClient with custom headers
  11932. TEST_F(SSEIntegrationTest, CustomHeaders) {
  11933. // Setup a server endpoint that checks for custom header
  11934. std::atomic<bool> header_received{false};
  11935. server_->Get("/header-check", [&](const Request &req, Response &res) {
  11936. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  11937. header_received.store(true);
  11938. }
  11939. res.set_chunked_content_provider("text/event-stream",
  11940. [](size_t, DataSink &) { return false; });
  11941. });
  11942. Client client("localhost", get_port());
  11943. Headers headers = {{"X-Custom-Header", "custom-value"}};
  11944. sse::SSEClient sse(client, "/header-check", headers);
  11945. sse.set_max_reconnect_attempts(1);
  11946. sse.start_async();
  11947. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11948. sse.stop();
  11949. EXPECT_TRUE(header_received.load());
  11950. }
  11951. // Test: Reconnect interval configuration
  11952. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  11953. Client client("localhost", get_port());
  11954. sse::SSEClient sse(client, "/events");
  11955. auto &result = sse.set_reconnect_interval(500);
  11956. // Builder pattern should return reference to self
  11957. EXPECT_EQ(&result, &sse);
  11958. }
  11959. // Test: Max reconnect attempts
  11960. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  11961. // Connect to non-existent port to force reconnects
  11962. Client client("localhost", 59998);
  11963. sse::SSEClient sse(client, "/events");
  11964. std::atomic<int> error_count{0};
  11965. sse.on_error([&](Error) { error_count.fetch_add(1); });
  11966. sse.set_reconnect_interval(50);
  11967. sse.set_max_reconnect_attempts(2);
  11968. auto start = std::chrono::steady_clock::now();
  11969. sse.start(); // Blocking call
  11970. auto end = std::chrono::steady_clock::now();
  11971. // Should have stopped after 2 failed attempts
  11972. EXPECT_GE(error_count.load(), 2);
  11973. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  11974. auto duration =
  11975. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  11976. #ifdef _WIN32
  11977. // Windows is much slower for socket connection failures
  11978. EXPECT_LT(duration.count(), 7000);
  11979. #else
  11980. EXPECT_LT(duration.count(), 1000);
  11981. #endif
  11982. }
  11983. // Test: Multi-line data in integration
  11984. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  11985. // Endpoint with multi-line data
  11986. server_->Get("/multiline-data", [](const Request &, Response &res) {
  11987. res.set_chunked_content_provider(
  11988. "text/event-stream", [](size_t offset, DataSink &sink) {
  11989. if (offset == 0) {
  11990. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  11991. sink.write(event.data(), event.size());
  11992. }
  11993. return false;
  11994. });
  11995. });
  11996. Client client("localhost", get_port());
  11997. sse::SSEClient sse(client, "/multiline-data");
  11998. std::string received_data;
  11999. std::mutex data_mutex;
  12000. sse.on_message([&](const sse::SSEMessage &msg) {
  12001. std::lock_guard<std::mutex> lock(data_mutex);
  12002. received_data = msg.data;
  12003. });
  12004. sse.set_reconnect_interval(100);
  12005. sse.set_max_reconnect_attempts(1);
  12006. sse.start_async();
  12007. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12008. sse.stop();
  12009. std::lock_guard<std::mutex> lock(data_mutex);
  12010. EXPECT_EQ(received_data, "line1\nline2\nline3");
  12011. }
  12012. // Test: Auto-reconnect after server disconnection
  12013. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  12014. std::atomic<int> connection_count{0};
  12015. std::atomic<int> message_count{0};
  12016. // Endpoint that sends one event and closes, forcing reconnect
  12017. server_->Get("/reconnect-test",
  12018. [&connection_count](const Request &, Response &res) {
  12019. connection_count.fetch_add(1);
  12020. res.set_chunked_content_provider(
  12021. "text/event-stream", [](size_t offset, DataSink &sink) {
  12022. if (offset == 0) {
  12023. std::string event = "data: hello\n\n";
  12024. sink.write(event.data(), event.size());
  12025. }
  12026. return false; // Close connection after sending
  12027. });
  12028. });
  12029. Client client("localhost", get_port());
  12030. sse::SSEClient sse(client, "/reconnect-test");
  12031. sse.on_message([&message_count](const sse::SSEMessage &) {
  12032. message_count.fetch_add(1);
  12033. });
  12034. sse.set_reconnect_interval(100);
  12035. sse.set_max_reconnect_attempts(3);
  12036. sse.start_async();
  12037. // Wait long enough for multiple reconnects
  12038. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  12039. sse.stop();
  12040. // Should have connected multiple times (initial + reconnects)
  12041. EXPECT_GE(connection_count.load(), 2);
  12042. // Should have received messages from multiple connections
  12043. EXPECT_GE(message_count.load(), 2);
  12044. }
  12045. // Test: Last-Event-ID sent on reconnect
  12046. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  12047. std::atomic<int> connection_count{0};
  12048. std::vector<std::string> received_last_event_ids;
  12049. std::mutex id_mutex;
  12050. // Endpoint that checks Last-Event-ID header and sends event with ID
  12051. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  12052. int conn = connection_count.fetch_add(1);
  12053. // Capture the Last-Event-ID header from each connection
  12054. {
  12055. std::lock_guard<std::mutex> lock(id_mutex);
  12056. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  12057. }
  12058. res.set_chunked_content_provider(
  12059. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  12060. if (offset == 0) {
  12061. std::string event =
  12062. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  12063. sink.write(event.data(), event.size());
  12064. }
  12065. return false;
  12066. });
  12067. });
  12068. Client client("localhost", get_port());
  12069. sse::SSEClient sse(client, "/reconnect-with-id");
  12070. sse.set_reconnect_interval(100);
  12071. sse.set_max_reconnect_attempts(3);
  12072. sse.start_async();
  12073. // Wait for at least 2 connections
  12074. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12075. sse.stop();
  12076. // Verify behavior
  12077. std::lock_guard<std::mutex> lock(id_mutex);
  12078. EXPECT_GE(received_last_event_ids.size(), 2u);
  12079. // First connection should have no Last-Event-ID
  12080. if (!received_last_event_ids.empty()) {
  12081. EXPECT_EQ(received_last_event_ids[0], "");
  12082. }
  12083. // Second connection should have Last-Event-ID from first connection
  12084. if (received_last_event_ids.size() >= 2) {
  12085. EXPECT_EQ(received_last_event_ids[1], "event-0");
  12086. }
  12087. }
  12088. TEST(Issue2318Test, EmptyHostString) {
  12089. {
  12090. httplib::Client cli_empty("", PORT);
  12091. auto res = cli_empty.Get("/");
  12092. ASSERT_FALSE(res);
  12093. EXPECT_EQ(httplib::Error::Connection, res.error());
  12094. }
  12095. {
  12096. httplib::Client cli(" ", PORT);
  12097. auto res = cli.Get("/");
  12098. ASSERT_FALSE(res);
  12099. EXPECT_EQ(httplib::Error::Connection, res.error());
  12100. }
  12101. }
  12102. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12103. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  12104. Server svr;
  12105. // Set a small payload limit (1KB)
  12106. svr.set_payload_max_length(1024);
  12107. svr.Post("/test", [&](const Request &req, Response &res) {
  12108. res.set_content("Body size: " + std::to_string(req.body.size()),
  12109. "text/plain");
  12110. });
  12111. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12112. auto se = detail::scope_exit([&] {
  12113. svr.stop();
  12114. listen_thread.join();
  12115. });
  12116. svr.wait_until_ready();
  12117. // Create data that compresses well but exceeds limit when decompressed
  12118. // 8KB of repeated null bytes compresses to a very small size
  12119. std::string original_data(8 * 1024, '\0');
  12120. // Compress the data using gzip
  12121. std::string compressed_data;
  12122. detail::gzip_compressor compressor;
  12123. compressor.compress(original_data.data(), original_data.size(), true,
  12124. [&](const char *data, size_t size) {
  12125. compressed_data.append(data, size);
  12126. return true;
  12127. });
  12128. // Verify compression worked (compressed should be much smaller)
  12129. ASSERT_LT(compressed_data.size(), original_data.size());
  12130. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  12131. // Send compressed data with Content-Encoding: gzip
  12132. Client cli(HOST, PORT);
  12133. Headers headers = {{"Content-Encoding", "gzip"}};
  12134. auto res =
  12135. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  12136. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  12137. ASSERT_TRUE(res);
  12138. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12139. }
  12140. #endif
  12141. // ============================================================================
  12142. // OpenSSL-Specific Tests
  12143. // ============================================================================
  12144. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12145. X509 *readCertificate(const std::string &strFileName) {
  12146. std::ifstream inStream(strFileName);
  12147. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  12148. std::istreambuf_iterator<char>());
  12149. if (strCertPEM.empty()) return (nullptr);
  12150. BIO *pbCert = BIO_new(BIO_s_mem());
  12151. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  12152. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  12153. BIO_free(pbCert);
  12154. return (pCert);
  12155. }
  12156. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  12157. std::ifstream inStream(strFileName);
  12158. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  12159. std::istreambuf_iterator<char>());
  12160. if (strPrivateKeyPEM.empty()) return (nullptr);
  12161. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  12162. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  12163. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  12164. BIO_free(pbPrivKey);
  12165. return (pPrivateKey);
  12166. }
  12167. TEST(BindServerTest, UpdateCerts) {
  12168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12169. int port = svr.bind_to_any_port("0.0.0.0");
  12170. ASSERT_TRUE(svr.is_valid());
  12171. ASSERT_TRUE(port > 0);
  12172. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12173. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12174. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12175. ASSERT_TRUE(cert != nullptr);
  12176. ASSERT_TRUE(ca_cert != nullptr);
  12177. ASSERT_TRUE(key != nullptr);
  12178. X509_STORE *cert_store = X509_STORE_new();
  12179. X509_STORE_add_cert(cert_store, ca_cert);
  12180. // svr.update_certs(cert, key, cert_store); // deprecated
  12181. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12182. CLIENT_CA_CERT_FILE);
  12183. ASSERT_TRUE(svr.is_valid());
  12184. svr.stop();
  12185. X509_free(cert);
  12186. X509_free(ca_cert);
  12187. EVP_PKEY_free(key);
  12188. }
  12189. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  12190. // client CA list correctly for TLS handshake
  12191. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  12192. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12193. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12194. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12195. ASSERT_TRUE(cert != nullptr);
  12196. ASSERT_TRUE(ca_cert != nullptr);
  12197. ASSERT_TRUE(key != nullptr);
  12198. X509_STORE *cert_store = X509_STORE_new();
  12199. X509_STORE_add_cert(cert_store, ca_cert);
  12200. // Use X509-based constructor (deprecated but should still work correctly)
  12201. #pragma GCC diagnostic push
  12202. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  12203. SSLServer svr(cert, key, cert_store);
  12204. #pragma GCC diagnostic pop
  12205. ASSERT_TRUE(svr.is_valid());
  12206. // Verify that client CA list is set in SSL_CTX
  12207. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12208. ASSERT_TRUE(ssl_ctx != nullptr);
  12209. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12210. ASSERT_TRUE(ca_list != nullptr);
  12211. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12212. X509_free(cert);
  12213. X509_free(ca_cert);
  12214. EVP_PKEY_free(key);
  12215. }
  12216. // Test that update_certs() updates client CA list correctly
  12217. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  12218. // Start with file-based constructor
  12219. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12220. ASSERT_TRUE(svr.is_valid());
  12221. // Initially no client CA list should be set
  12222. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12223. ASSERT_TRUE(ssl_ctx != nullptr);
  12224. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  12225. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  12226. EXPECT_EQ(0, count_before);
  12227. // Now update with client CA (PEM string)
  12228. std::string cert_pem, key_pem, ca_pem;
  12229. read_file(SERVER_CERT_FILE, cert_pem);
  12230. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  12231. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  12232. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  12233. ASSERT_TRUE(svr.is_valid());
  12234. // Now client CA list should be set
  12235. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  12236. ASSERT_TRUE(ca_list_after != nullptr);
  12237. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  12238. }
  12239. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  12240. // Test that the file-path SSLServer constructor properly sets the client CA
  12241. // list that is sent to clients during the TLS handshake (CertificateRequest)
  12242. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12243. ASSERT_TRUE(svr.is_valid());
  12244. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12245. ASSERT_TRUE(ssl_ctx != nullptr);
  12246. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12247. ASSERT_TRUE(ca_list != nullptr);
  12248. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12249. }
  12250. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  12251. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  12252. // prepare large data
  12253. std::random_device seed_gen;
  12254. std::mt19937 random(seed_gen());
  12255. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  12256. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  12257. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  12258. // server
  12259. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12260. ASSERT_TRUE(svr.is_valid());
  12261. svr.Post("/binary", [&](const Request &req, Response &res) {
  12262. EXPECT_EQ(large_size_byte, req.body.size());
  12263. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  12264. res.set_content(req.body, "application/octet-stream");
  12265. });
  12266. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12267. auto se = detail::scope_exit([&] {
  12268. svr.stop();
  12269. listen_thread.join();
  12270. ASSERT_FALSE(svr.is_running());
  12271. });
  12272. svr.wait_until_ready();
  12273. // client POST
  12274. SSLClient cli("localhost", PORT);
  12275. cli.enable_server_certificate_verification(false);
  12276. cli.set_read_timeout(std::chrono::seconds(100));
  12277. cli.set_write_timeout(std::chrono::seconds(100));
  12278. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  12279. large_size_byte, "application/octet-stream");
  12280. // compare
  12281. EXPECT_EQ(StatusCode::OK_200, res->status);
  12282. EXPECT_EQ(large_size_byte, res->body.size());
  12283. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  12284. }
  12285. #endif
  12286. // ============================================================================
  12287. // MbedTLS-Specific Tests
  12288. // ============================================================================
  12289. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  12290. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  12291. using namespace httplib::tls;
  12292. // Track if callback was invoked
  12293. bool callback_invoked = false;
  12294. // The callback receives void* ctx which is actually MbedTlsContext*
  12295. // We can access the mbedtls_ssl_config via the context
  12296. auto setup_callback = [&callback_invoked](void *ctx) {
  12297. callback_invoked = true;
  12298. // Cast to MbedTlsContext* to access the ssl config
  12299. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  12300. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  12301. // Use static variables to hold certificate data (simplified for test)
  12302. static mbedtls_x509_crt own_cert;
  12303. static mbedtls_pk_context own_key;
  12304. static mbedtls_x509_crt ca_chain;
  12305. static bool initialized = false;
  12306. if (!initialized) {
  12307. mbedtls_x509_crt_init(&own_cert);
  12308. mbedtls_pk_init(&own_key);
  12309. mbedtls_x509_crt_init(&ca_chain);
  12310. // Load server certificate
  12311. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  12312. return false;
  12313. }
  12314. // Load server private key
  12315. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  12316. #if MBEDTLS_VERSION_MAJOR >= 3
  12317. ,
  12318. mbedtls_ctr_drbg_random, nullptr
  12319. #endif
  12320. ) != 0) {
  12321. return false;
  12322. }
  12323. // Load CA chain for client verification
  12324. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  12325. return false;
  12326. }
  12327. initialized = true;
  12328. }
  12329. // Configure the SSL config
  12330. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  12331. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  12332. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  12333. // Set minimum TLS version using mbedTLS native API
  12334. #if MBEDTLS_VERSION_MAJOR >= 3
  12335. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  12336. #else
  12337. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  12338. MBEDTLS_SSL_MINOR_VERSION_3);
  12339. #endif
  12340. return true;
  12341. };
  12342. SSLServer svr(setup_callback);
  12343. ASSERT_TRUE(svr.is_valid());
  12344. ASSERT_TRUE(callback_invoked);
  12345. svr.Get("/test", [&](const Request &req, Response &res) {
  12346. res.set_content("test", "text/plain");
  12347. auto cert = req.peer_cert();
  12348. ASSERT_TRUE(static_cast<bool>(cert));
  12349. auto common_name = cert.subject_cn();
  12350. EXPECT_EQ("Common Name", common_name);
  12351. });
  12352. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12353. auto se = detail::scope_exit([&] {
  12354. svr.stop();
  12355. t.join();
  12356. ASSERT_FALSE(svr.is_running());
  12357. });
  12358. svr.wait_until_ready();
  12359. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12360. cli.enable_server_certificate_verification(false);
  12361. cli.set_connection_timeout(30);
  12362. auto res = cli.Get("/test");
  12363. ASSERT_TRUE(res);
  12364. ASSERT_EQ(StatusCode::OK_200, res->status);
  12365. }
  12366. #endif