test.cc 356 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611
  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 <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <algorithm>
  13. #include <atomic>
  14. #include <chrono>
  15. #include <cstdio>
  16. #include <fstream>
  17. #include <future>
  18. #include <limits>
  19. #include <memory>
  20. #include <sstream>
  21. #include <stdexcept>
  22. #include <thread>
  23. #include <type_traits>
  24. #include <vector>
  25. #define SERVER_CERT_FILE "./cert.pem"
  26. #define SERVER_CERT2_FILE "./cert2.pem"
  27. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  28. #define CA_CERT_FILE "./ca-bundle.crt"
  29. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  30. #define CLIENT_CA_CERT_DIR "."
  31. #define CLIENT_CERT_FILE "./client.cert.pem"
  32. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  33. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  34. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  35. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  36. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  37. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  38. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  39. using namespace std;
  40. using namespace httplib;
  41. const char *HOST = "localhost";
  42. const int PORT = 1234;
  43. const string LONG_QUERY_VALUE = string(25000, '@');
  44. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  45. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  46. const string TOO_LONG_QUERY_URL =
  47. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  48. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  49. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  50. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  51. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  52. return file.name == key;
  53. });
  54. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  55. return *it;
  56. #else
  57. if (it != items.end()) { return *it; }
  58. throw std::runtime_error("invalid multipart form data name error");
  59. #endif
  60. }
  61. static void read_file(const std::string &path, std::string &out) {
  62. std::ifstream fs(path, std::ios_base::binary);
  63. if (!fs) throw std::runtime_error("File not found: " + path);
  64. fs.seekg(0, std::ios_base::end);
  65. auto size = fs.tellg();
  66. fs.seekg(0);
  67. out.resize(static_cast<size_t>(size));
  68. fs.read(&out[0], static_cast<std::streamsize>(size));
  69. }
  70. void performance_test(const char *host) {
  71. auto port = 1234;
  72. Server svr;
  73. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  74. res.set_content("Benchmark Response", "text/plain");
  75. });
  76. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  77. auto se = detail::scope_exit([&] {
  78. svr.stop();
  79. listen_thread.join();
  80. ASSERT_FALSE(svr.is_running());
  81. });
  82. svr.wait_until_ready();
  83. Client cli(host, port);
  84. // Warm-up request to establish connection and resolve DNS
  85. auto warmup_res = cli.Get("/benchmark");
  86. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  87. // Run multiple trials and collect timings
  88. const int num_trials = 20;
  89. std::vector<int64_t> timings;
  90. timings.reserve(num_trials);
  91. for (int i = 0; i < num_trials; i++) {
  92. auto start = std::chrono::high_resolution_clock::now();
  93. auto res = cli.Get("/benchmark");
  94. auto end = std::chrono::high_resolution_clock::now();
  95. auto elapsed =
  96. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  97. .count();
  98. // Assertions after timing measurement to avoid overhead
  99. ASSERT_TRUE(res);
  100. EXPECT_EQ(StatusCode::OK_200, res->status);
  101. timings.push_back(elapsed);
  102. }
  103. // Calculate 25th percentile (lower quartile)
  104. std::sort(timings.begin(), timings.end());
  105. auto p25 = timings[num_trials / 4];
  106. // Format timings for output
  107. std::ostringstream timings_str;
  108. timings_str << "[";
  109. for (size_t i = 0; i < timings.size(); i++) {
  110. if (i > 0) timings_str << ", ";
  111. timings_str << timings[i];
  112. }
  113. timings_str << "]";
  114. // Localhost HTTP GET should be fast even in CI environments
  115. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  116. << "ms (Issue #1777). Timings: " << timings_str.str();
  117. }
  118. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  119. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  120. class UnixSocketTest : public ::testing::Test {
  121. protected:
  122. void TearDown() override { std::remove(pathname_.c_str()); }
  123. void client_GET(const std::string &addr) {
  124. httplib::Client cli{addr};
  125. cli.set_address_family(AF_UNIX);
  126. ASSERT_TRUE(cli.is_valid());
  127. const auto &result = cli.Get(pattern_);
  128. ASSERT_TRUE(result) << "error: " << result.error();
  129. const auto &resp = result.value();
  130. EXPECT_EQ(resp.status, StatusCode::OK_200);
  131. EXPECT_EQ(resp.body, content_);
  132. }
  133. const std::string pathname_{"./httplib-server.sock"};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. }
  154. #if defined(__linux__) || \
  155. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  156. TEST_F(UnixSocketTest, PeerPid) {
  157. httplib::Server svr;
  158. std::string remote_port_val;
  159. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. remote_port_val = std::to_string(req.remote_port);
  162. });
  163. std::thread t{[&] {
  164. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  165. }};
  166. auto se = detail::scope_exit([&] {
  167. svr.stop();
  168. t.join();
  169. ASSERT_FALSE(svr.is_running());
  170. });
  171. svr.wait_until_ready();
  172. ASSERT_TRUE(svr.is_running());
  173. client_GET(pathname_);
  174. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  175. }
  176. #endif
  177. #ifdef __linux__
  178. TEST_F(UnixSocketTest, abstract) {
  179. constexpr char svr_path[]{"\x00httplib-server.sock"};
  180. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  181. httplib::Server svr;
  182. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  183. res.set_content(content_, "text/plain");
  184. });
  185. std::thread t{[&] {
  186. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  187. }};
  188. auto se = detail::scope_exit([&] {
  189. svr.stop();
  190. t.join();
  191. ASSERT_FALSE(svr.is_running());
  192. });
  193. svr.wait_until_ready();
  194. ASSERT_TRUE(svr.is_running());
  195. client_GET(abstract_addr);
  196. }
  197. #endif
  198. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  199. httplib::Server svr;
  200. std::string received_host_header;
  201. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  202. // Capture the Host header sent by the client
  203. auto host_iter = req.headers.find("Host");
  204. if (host_iter != req.headers.end()) {
  205. received_host_header = host_iter->second;
  206. }
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. // Test that Host header is automatically set to "localhost" for Unix socket
  220. // connections
  221. httplib::Client cli{pathname_};
  222. cli.set_address_family(AF_UNIX);
  223. ASSERT_TRUE(cli.is_valid());
  224. const auto &result = cli.Get(pattern_);
  225. ASSERT_TRUE(result) << "error: " << result.error();
  226. const auto &resp = result.value();
  227. EXPECT_EQ(resp.status, StatusCode::OK_200);
  228. EXPECT_EQ(resp.body, content_);
  229. // Verify that Host header was automatically set to "localhost"
  230. EXPECT_EQ(received_host_header, "localhost");
  231. }
  232. #ifndef _WIN32
  233. TEST(SocketStream, wait_writable_UNIX) {
  234. int fds[2];
  235. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  236. const auto asSocketStream = [&](socket_t fd,
  237. std::function<bool(Stream &)> func) {
  238. return detail::process_client_socket(
  239. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  240. };
  241. asSocketStream(fds[0], [&](Stream &s0) {
  242. EXPECT_EQ(s0.socket(), fds[0]);
  243. EXPECT_TRUE(s0.wait_writable());
  244. EXPECT_EQ(0, close(fds[1]));
  245. EXPECT_FALSE(s0.wait_writable());
  246. return true;
  247. });
  248. EXPECT_EQ(0, close(fds[0]));
  249. }
  250. TEST(SocketStream, wait_writable_INET) {
  251. sockaddr_in addr;
  252. memset(&addr, 0, sizeof(addr));
  253. addr.sin_family = AF_INET;
  254. addr.sin_port = htons(PORT + 1);
  255. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  256. int disconnected_svr_sock = -1;
  257. std::thread svr{[&] {
  258. const int s = socket(AF_INET, SOCK_STREAM, 0);
  259. ASSERT_LE(0, s);
  260. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  261. ASSERT_EQ(0, listen(s, 1));
  262. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  263. ASSERT_EQ(0, close(s));
  264. }};
  265. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  266. std::thread cli{[&] {
  267. const int s = socket(AF_INET, SOCK_STREAM, 0);
  268. ASSERT_LE(0, s);
  269. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, close(s));
  271. }};
  272. cli.join();
  273. svr.join();
  274. ASSERT_NE(disconnected_svr_sock, -1);
  275. const auto asSocketStream = [&](socket_t fd,
  276. std::function<bool(Stream &)> func) {
  277. return detail::process_client_socket(
  278. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  279. };
  280. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  281. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  282. EXPECT_FALSE(ss.wait_writable());
  283. return true;
  284. });
  285. ASSERT_EQ(0, close(disconnected_svr_sock));
  286. }
  287. #endif // #ifndef _WIN32
  288. TEST(ClientTest, MoveConstructible) {
  289. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  290. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  291. }
  292. TEST(ClientTest, MoveAssignable) {
  293. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  294. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  295. }
  296. #ifdef _WIN32
  297. TEST(StartupTest, WSAStartup) {
  298. WSADATA wsaData;
  299. int ret = WSAStartup(0x0002, &wsaData);
  300. ASSERT_EQ(0, ret);
  301. }
  302. #endif
  303. TEST(DecodePathTest, PercentCharacter) {
  304. EXPECT_EQ(
  305. decode_path_component(
  306. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  307. u8"descrip=Gastos áéíóúñÑ 6");
  308. }
  309. TEST(DecodePathTest, PercentCharacterNUL) {
  310. string expected;
  311. expected.push_back('x');
  312. expected.push_back('\0');
  313. expected.push_back('x');
  314. EXPECT_EQ(decode_path_component("x%00x"), expected);
  315. }
  316. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  317. string unescapedCharacters = "-_.!~*'()";
  318. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  319. }
  320. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  321. string reservedCharacters = ";,/?:@&=+$";
  322. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  323. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  324. }
  325. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  326. string chineseCharacters = u8"中国語";
  327. string russianCharacters = u8"дом";
  328. string brazilianCharacters = u8"óculos";
  329. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  330. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  331. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  332. "%D0%B4%D0%BE%D0%BC");
  333. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  334. }
  335. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  336. string unescapedCharacters = "-_.!~*'()";
  337. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  338. }
  339. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  340. string reservedCharacters = ";,/?:@&=+$";
  341. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  342. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  343. }
  344. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  345. string chineseCharacters = u8"中国語";
  346. string russianCharacters = u8"дом";
  347. string brazilianCharacters = u8"óculos";
  348. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  349. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  350. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  351. "%D0%B4%D0%BE%D0%BC");
  352. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  353. }
  354. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  355. // Issue #2082 use case: encoding path component with ampersand
  356. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  357. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  358. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  359. }
  360. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  361. string unescapedCharacters = "-_.!~*'()";
  362. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  363. }
  364. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  365. string reservedCharacters = ";,/?:@&=+$#";
  366. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  367. }
  368. TEST(EncodeUriTest, TestUTF8Characters) {
  369. string chineseCharacters = u8"中国語";
  370. string russianCharacters = u8"дом";
  371. string brazilianCharacters = u8"óculos";
  372. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  373. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  374. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  375. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  376. }
  377. TEST(EncodeUriTest, TestCompleteUri) {
  378. string uri =
  379. "https://example.com/path/to/resource?query=value&param=test#fragment";
  380. EXPECT_EQ(
  381. httplib::encode_uri(uri),
  382. "https://example.com/path/to/resource?query=value&param=test#fragment");
  383. }
  384. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  385. string uri =
  386. "https://example.com/path with spaces/file name.html?q=hello world";
  387. EXPECT_EQ(httplib::encode_uri(uri),
  388. "https://example.com/path%20with%20spaces/"
  389. "file%20name.html?q=hello%20world");
  390. }
  391. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  392. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  393. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  394. }
  395. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  396. string unescapedCharacters = "-_.!~*'()";
  397. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  398. }
  399. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  400. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  401. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  402. string encodedBrazilian = "%C3%B3culos";
  403. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  404. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  405. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  406. }
  407. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  408. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  409. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  410. "Piri Tommy Villiers - on & on");
  411. }
  412. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  413. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  414. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  415. }
  416. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  417. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  418. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  419. }
  420. TEST(DecodeUriTest, TestUTF8Characters) {
  421. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  422. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  423. string encodedBrazilian = "%C3%B3culos";
  424. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  425. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  426. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  427. }
  428. TEST(DecodeUriTest, TestCompleteUri) {
  429. string encodedUri = "https://example.com/path%20with%20spaces/"
  430. "file%20name.html?q=hello%20world";
  431. EXPECT_EQ(
  432. httplib::decode_uri(encodedUri),
  433. "https://example.com/path with spaces/file name.html?q=hello world");
  434. }
  435. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  436. string original =
  437. "https://example.com/path with spaces/file name.html?q=hello world";
  438. string encoded = httplib::encode_uri(original);
  439. string decoded = httplib::decode_uri(encoded);
  440. EXPECT_EQ(decoded, original);
  441. }
  442. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  443. string original = "Piri Tommy Villiers - on & on";
  444. string encoded = httplib::encode_uri_component(original);
  445. string decoded = httplib::decode_uri_component(encoded);
  446. EXPECT_EQ(decoded, original);
  447. }
  448. TEST(TrimTests, TrimStringTests) {
  449. EXPECT_EQ("abc", detail::trim_copy("abc"));
  450. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  451. EXPECT_TRUE(detail::trim_copy("").empty());
  452. }
  453. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  454. // Simple case without quality values
  455. std::vector<std::string> result1;
  456. EXPECT_TRUE(detail::parse_accept_header(
  457. "text/html,application/json,text/plain", result1));
  458. EXPECT_EQ(result1.size(), 3U);
  459. EXPECT_EQ(result1[0], "text/html");
  460. EXPECT_EQ(result1[1], "application/json");
  461. EXPECT_EQ(result1[2], "text/plain");
  462. // With quality values
  463. std::vector<std::string> result2;
  464. EXPECT_TRUE(detail::parse_accept_header(
  465. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  466. EXPECT_EQ(result2.size(), 3U);
  467. EXPECT_EQ(result2[0], "application/json"); // highest q value
  468. EXPECT_EQ(result2[1], "text/html");
  469. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  470. }
  471. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  472. // Mixed with and without quality values
  473. std::vector<std::string> result;
  474. EXPECT_TRUE(detail::parse_accept_header(
  475. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  476. EXPECT_EQ(result.size(), 3U);
  477. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  478. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  479. EXPECT_EQ(result[2], "application/json"); // q=0.5
  480. }
  481. TEST(ParseAcceptHeaderTest, EdgeCases) {
  482. // Empty header
  483. std::vector<std::string> empty_result;
  484. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  485. EXPECT_TRUE(empty_result.empty());
  486. // Single type
  487. std::vector<std::string> single_result;
  488. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  489. EXPECT_EQ(single_result.size(), 1U);
  490. EXPECT_EQ(single_result[0], "application/json");
  491. // Wildcard types
  492. std::vector<std::string> wildcard_result;
  493. EXPECT_TRUE(detail::parse_accept_header(
  494. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  495. EXPECT_EQ(wildcard_result.size(), 3U);
  496. EXPECT_EQ(wildcard_result[0], "application/json");
  497. EXPECT_EQ(wildcard_result[1], "text/*");
  498. EXPECT_EQ(wildcard_result[2], "*/*");
  499. }
  500. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  501. // Common browser Accept header
  502. std::vector<std::string> browser_result;
  503. EXPECT_TRUE(
  504. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  505. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  506. browser_result));
  507. EXPECT_EQ(browser_result.size(), 6U);
  508. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  509. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  510. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  511. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  512. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  513. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  514. // API client header
  515. std::vector<std::string> api_result;
  516. EXPECT_TRUE(detail::parse_accept_header(
  517. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  518. api_result));
  519. EXPECT_EQ(api_result.size(), 3U);
  520. EXPECT_EQ(api_result[0], "application/json");
  521. EXPECT_EQ(api_result[1], "application/xml");
  522. EXPECT_EQ(api_result[2], "text/plain");
  523. }
  524. TEST(ParseAcceptHeaderTest, SpecialCases) {
  525. // Quality value with 3 decimal places
  526. std::vector<std::string> decimal_result;
  527. EXPECT_TRUE(detail::parse_accept_header(
  528. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  529. EXPECT_EQ(decimal_result.size(), 2U);
  530. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  531. EXPECT_EQ(decimal_result[1], "text/html");
  532. // Zero quality (should still be included but with lowest priority)
  533. std::vector<std::string> zero_q_result;
  534. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  535. zero_q_result));
  536. EXPECT_EQ(zero_q_result.size(), 2U);
  537. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  538. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  539. // No spaces around commas
  540. std::vector<std::string> no_space_result;
  541. EXPECT_TRUE(detail::parse_accept_header(
  542. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  543. no_space_result));
  544. EXPECT_EQ(no_space_result.size(), 3U);
  545. EXPECT_EQ(no_space_result[0], "text/html");
  546. EXPECT_EQ(no_space_result[1], "application/json");
  547. EXPECT_EQ(no_space_result[2], "text/plain");
  548. }
  549. TEST(ParseAcceptHeaderTest, InvalidCases) {
  550. std::vector<std::string> result;
  551. // Invalid quality value (> 1.0)
  552. EXPECT_FALSE(
  553. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  554. // Invalid quality value (< 0.0)
  555. EXPECT_FALSE(
  556. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  557. // Invalid quality value (not a number)
  558. EXPECT_FALSE(detail::parse_accept_header(
  559. "text/html;q=invalid,application/json", result));
  560. // Empty quality value
  561. EXPECT_FALSE(
  562. detail::parse_accept_header("text/html;q=,application/json", result));
  563. // Invalid media type format (no slash and not wildcard)
  564. EXPECT_FALSE(
  565. detail::parse_accept_header("invalidtype,application/json", result));
  566. // Empty media type
  567. result.clear();
  568. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  569. // Only commas
  570. result.clear();
  571. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  572. // Valid cases should still work
  573. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  574. EXPECT_EQ(result.size(), 1U);
  575. EXPECT_EQ(result[0], "*/*");
  576. EXPECT_TRUE(detail::parse_accept_header("*", result));
  577. EXPECT_EQ(result.size(), 1U);
  578. EXPECT_EQ(result[0], "*");
  579. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  580. EXPECT_EQ(result.size(), 1U);
  581. EXPECT_EQ(result[0], "text/*");
  582. }
  583. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  584. Server svr;
  585. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  586. EXPECT_EQ(req.accept_content_types.size(), 3U);
  587. EXPECT_EQ(req.accept_content_types[0], "application/json");
  588. EXPECT_EQ(req.accept_content_types[1], "text/html");
  589. EXPECT_EQ(req.accept_content_types[2], "*/*");
  590. res.set_content("ok", "text/plain");
  591. });
  592. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  593. EXPECT_TRUE(false);
  594. res.set_content("bad request", "text/plain");
  595. });
  596. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  597. auto se = detail::scope_exit([&] {
  598. svr.stop();
  599. listen_thread.join();
  600. ASSERT_FALSE(svr.is_running());
  601. });
  602. svr.wait_until_ready();
  603. Client cli("localhost", PORT);
  604. {
  605. auto res =
  606. cli.Get("/accept_ok",
  607. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  608. ASSERT_TRUE(res);
  609. EXPECT_EQ(StatusCode::OK_200, res->status);
  610. }
  611. {
  612. auto res = cli.Get("/accept_bad_request",
  613. {{"Accept", "text/html;q=abc,application/json"}});
  614. ASSERT_TRUE(res);
  615. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  616. }
  617. }
  618. TEST(DivideTest, DivideStringTests) {
  619. auto divide = [](const std::string &str, char d) {
  620. std::string lhs;
  621. std::string rhs;
  622. detail::divide(str, d,
  623. [&](const char *lhs_data, std::size_t lhs_size,
  624. const char *rhs_data, std::size_t rhs_size) {
  625. lhs.assign(lhs_data, lhs_size);
  626. rhs.assign(rhs_data, rhs_size);
  627. });
  628. return std::make_pair(std::move(lhs), std::move(rhs));
  629. };
  630. {
  631. const auto res = divide("", '=');
  632. EXPECT_EQ(res.first, "");
  633. EXPECT_EQ(res.second, "");
  634. }
  635. {
  636. const auto res = divide("=", '=');
  637. EXPECT_EQ(res.first, "");
  638. EXPECT_EQ(res.second, "");
  639. }
  640. {
  641. const auto res = divide(" ", '=');
  642. EXPECT_EQ(res.first, " ");
  643. EXPECT_EQ(res.second, "");
  644. }
  645. {
  646. const auto res = divide("a", '=');
  647. EXPECT_EQ(res.first, "a");
  648. EXPECT_EQ(res.second, "");
  649. }
  650. {
  651. const auto res = divide("a=", '=');
  652. EXPECT_EQ(res.first, "a");
  653. EXPECT_EQ(res.second, "");
  654. }
  655. {
  656. const auto res = divide("=b", '=');
  657. EXPECT_EQ(res.first, "");
  658. EXPECT_EQ(res.second, "b");
  659. }
  660. {
  661. const auto res = divide("a=b", '=');
  662. EXPECT_EQ(res.first, "a");
  663. EXPECT_EQ(res.second, "b");
  664. }
  665. {
  666. const auto res = divide("a=b=", '=');
  667. EXPECT_EQ(res.first, "a");
  668. EXPECT_EQ(res.second, "b=");
  669. }
  670. {
  671. const auto res = divide("a=b=c", '=');
  672. EXPECT_EQ(res.first, "a");
  673. EXPECT_EQ(res.second, "b=c");
  674. }
  675. }
  676. TEST(SplitTest, ParseQueryString) {
  677. string s = "key1=val1&key2=val2&key3=val3";
  678. Params dic;
  679. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  680. [&](const char *b, const char *e) {
  681. string key, val;
  682. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  683. if (key.empty()) {
  684. key.assign(b2, e2);
  685. } else {
  686. val.assign(b2, e2);
  687. }
  688. });
  689. dic.emplace(key, val);
  690. });
  691. EXPECT_EQ("val1", dic.find("key1")->second);
  692. EXPECT_EQ("val2", dic.find("key2")->second);
  693. EXPECT_EQ("val3", dic.find("key3")->second);
  694. }
  695. TEST(SplitTest, ParseInvalidQueryTests) {
  696. {
  697. string s = " ";
  698. Params dict;
  699. detail::parse_query_text(s, dict);
  700. EXPECT_TRUE(dict.empty());
  701. }
  702. {
  703. string s = " = =";
  704. Params dict;
  705. detail::parse_query_text(s, dict);
  706. EXPECT_TRUE(dict.empty());
  707. }
  708. }
  709. TEST(ParseQueryTest, ParseQueryString) {
  710. {
  711. std::string s = "key1=val1&key2=val2&key3=val3";
  712. Params dic;
  713. detail::parse_query_text(s, dic);
  714. EXPECT_EQ("val1", dic.find("key1")->second);
  715. EXPECT_EQ("val2", dic.find("key2")->second);
  716. EXPECT_EQ("val3", dic.find("key3")->second);
  717. }
  718. {
  719. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  720. Params dic;
  721. detail::parse_query_text(s, dic);
  722. EXPECT_EQ("", dic.find("key1")->second);
  723. EXPECT_EQ("val1", dic.find("key2")->second);
  724. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  725. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  726. }
  727. }
  728. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  729. Params dic;
  730. EXPECT_EQ(detail::params_to_query_str(dic), "");
  731. dic.emplace("key1", "val1");
  732. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  733. dic.emplace("key2", "val2");
  734. dic.emplace("key3", "val3");
  735. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  736. }
  737. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  738. string content_type = "multipart/form-data; boundary=something";
  739. string boundary;
  740. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  741. EXPECT_TRUE(ret);
  742. EXPECT_EQ(boundary, "something");
  743. }
  744. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  745. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  746. string boundary;
  747. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  748. EXPECT_TRUE(ret);
  749. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  750. }
  751. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  752. string content_type =
  753. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  754. string boundary;
  755. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  756. EXPECT_TRUE(ret);
  757. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  758. }
  759. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  760. string content_type =
  761. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  762. string boundary;
  763. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  764. EXPECT_TRUE(ret);
  765. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  766. }
  767. TEST(GetHeaderValueTest, DefaultValue) {
  768. Headers headers = {{"Dummy", "Dummy"}};
  769. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  770. EXPECT_STREQ("text/plain", val);
  771. }
  772. TEST(GetHeaderValueTest, DefaultValueInt) {
  773. Headers headers = {{"Dummy", "Dummy"}};
  774. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  775. EXPECT_EQ(100ull, val);
  776. }
  777. TEST(GetHeaderValueTest, RegularValue) {
  778. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  779. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  780. EXPECT_STREQ("text/html", val);
  781. }
  782. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  783. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  784. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  785. EXPECT_STREQ("text/html", val);
  786. }
  787. TEST(GetHeaderValueTest, SetContent) {
  788. Response res;
  789. res.set_content("html", "text/html");
  790. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  791. res.set_content("text", "text/plain");
  792. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  793. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  794. }
  795. TEST(GetHeaderValueTest, RegularValueInt) {
  796. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  797. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  798. EXPECT_EQ(100ull, val);
  799. }
  800. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  801. Headers headers = {{"Content-Length", "x"}};
  802. auto is_invalid_value = false;
  803. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  804. is_invalid_value);
  805. EXPECT_EQ(0ull, val);
  806. EXPECT_TRUE(is_invalid_value);
  807. }
  808. TEST(GetHeaderValueTest, Range) {
  809. {
  810. Headers headers = {make_range_header({{1, -1}})};
  811. auto val = detail::get_header_value(headers, "Range", 0, 0);
  812. EXPECT_STREQ("bytes=1-", val);
  813. }
  814. {
  815. Headers headers = {make_range_header({{-1, 1}})};
  816. auto val = detail::get_header_value(headers, "Range", 0, 0);
  817. EXPECT_STREQ("bytes=-1", val);
  818. }
  819. {
  820. Headers headers = {make_range_header({{1, 10}})};
  821. auto val = detail::get_header_value(headers, "Range", 0, 0);
  822. EXPECT_STREQ("bytes=1-10", val);
  823. }
  824. {
  825. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  826. auto val = detail::get_header_value(headers, "Range", 0, 0);
  827. EXPECT_STREQ("bytes=1-10, 100-", val);
  828. }
  829. {
  830. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  831. auto val = detail::get_header_value(headers, "Range", 0, 0);
  832. EXPECT_STREQ("bytes=1-10, 100-200", val);
  833. }
  834. {
  835. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  836. auto val = detail::get_header_value(headers, "Range", 0, 0);
  837. EXPECT_STREQ("bytes=0-0, -1", val);
  838. }
  839. }
  840. TEST(ParseHeaderValueTest, Range) {
  841. {
  842. Ranges ranges;
  843. auto ret = detail::parse_range_header("bytes=1-", ranges);
  844. EXPECT_TRUE(ret);
  845. EXPECT_EQ(1u, ranges.size());
  846. EXPECT_EQ(1u, ranges[0].first);
  847. EXPECT_EQ(-1, ranges[0].second);
  848. }
  849. {
  850. Ranges ranges;
  851. auto ret = detail::parse_range_header("bytes=-1", ranges);
  852. EXPECT_TRUE(ret);
  853. EXPECT_EQ(1u, ranges.size());
  854. EXPECT_EQ(-1, ranges[0].first);
  855. EXPECT_EQ(1u, ranges[0].second);
  856. }
  857. {
  858. Ranges ranges;
  859. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  860. EXPECT_TRUE(ret);
  861. EXPECT_EQ(1u, ranges.size());
  862. EXPECT_EQ(1u, ranges[0].first);
  863. EXPECT_EQ(10u, ranges[0].second);
  864. }
  865. {
  866. Ranges ranges;
  867. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  868. EXPECT_FALSE(ret);
  869. }
  870. {
  871. Ranges ranges;
  872. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  873. EXPECT_TRUE(ret);
  874. EXPECT_EQ(2u, ranges.size());
  875. EXPECT_EQ(1u, ranges[0].first);
  876. EXPECT_EQ(10u, ranges[0].second);
  877. EXPECT_EQ(100u, ranges[1].first);
  878. EXPECT_EQ(-1, ranges[1].second);
  879. }
  880. {
  881. Ranges ranges;
  882. auto ret =
  883. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  884. EXPECT_TRUE(ret);
  885. EXPECT_EQ(3u, ranges.size());
  886. EXPECT_EQ(1u, ranges[0].first);
  887. EXPECT_EQ(10u, ranges[0].second);
  888. EXPECT_EQ(100u, ranges[1].first);
  889. EXPECT_EQ(200u, ranges[1].second);
  890. EXPECT_EQ(300u, ranges[2].first);
  891. EXPECT_EQ(400u, ranges[2].second);
  892. }
  893. {
  894. Ranges ranges;
  895. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  896. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  897. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  898. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  899. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  900. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  901. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  902. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  903. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  904. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  905. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  906. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  907. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  908. EXPECT_TRUE(ranges.empty());
  909. }
  910. }
  911. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  912. Request req;
  913. req.set_header("Accept-Encoding", "gzip");
  914. Response res;
  915. res.set_header("Content-Type", "text/plain");
  916. auto ret = detail::encoding_type(req, res);
  917. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  918. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  919. #else
  920. EXPECT_TRUE(ret == detail::EncodingType::None);
  921. #endif
  922. }
  923. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  924. Request req;
  925. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  926. Response res;
  927. res.set_header("Content-Type", "text/plain");
  928. auto ret = detail::encoding_type(req, res);
  929. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  930. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  931. #elif CPPHTTPLIB_ZLIB_SUPPORT
  932. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  933. #elif CPPHTTPLIB_ZSTD_SUPPORT
  934. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  935. #else
  936. EXPECT_TRUE(ret == detail::EncodingType::None);
  937. #endif
  938. }
  939. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  940. Request req;
  941. req.set_header("Accept-Encoding",
  942. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  943. Response res;
  944. res.set_header("Content-Type", "text/plain");
  945. auto ret = detail::encoding_type(req, res);
  946. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  947. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  948. #elif CPPHTTPLIB_ZLIB_SUPPORT
  949. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  950. #elif CPPHTTPLIB_ZSTD_SUPPORT
  951. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  952. #else
  953. EXPECT_TRUE(ret == detail::EncodingType::None);
  954. #endif
  955. }
  956. TEST(BufferStreamTest, read) {
  957. detail::BufferStream strm1;
  958. Stream &strm = strm1;
  959. EXPECT_EQ(5, strm.write("hello"));
  960. char buf[512];
  961. EXPECT_EQ(2, strm.read(buf, 2));
  962. EXPECT_EQ('h', buf[0]);
  963. EXPECT_EQ('e', buf[1]);
  964. EXPECT_EQ(2, strm.read(buf, 2));
  965. EXPECT_EQ('l', buf[0]);
  966. EXPECT_EQ('l', buf[1]);
  967. EXPECT_EQ(1, strm.read(buf, 1));
  968. EXPECT_EQ('o', buf[0]);
  969. EXPECT_EQ(0, strm.read(buf, 1));
  970. }
  971. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  972. auto host = "www.httpwatch.com";
  973. auto ip = hosted_at(host);
  974. EXPECT_EQ("23.96.13.243", ip);
  975. std::vector<std::string> addrs;
  976. hosted_at(host, addrs);
  977. EXPECT_EQ(1u, addrs.size());
  978. }
  979. #if 0 // It depends on each test environment...
  980. TEST(HostnameToIPConversionTest, YouTube_Online) {
  981. auto host = "www.youtube.com";
  982. std::vector<std::string> addrs;
  983. hosted_at(host, addrs);
  984. EXPECT_EQ(20u, addrs.size());
  985. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  986. EXPECT_TRUE(it != addrs.end());
  987. }
  988. #endif
  989. class ChunkedEncodingTest : public ::testing::Test {
  990. protected:
  991. ChunkedEncodingTest()
  992. : cli_(HOST, PORT)
  993. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  994. ,
  995. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  996. #endif
  997. {
  998. cli_.set_connection_timeout(2);
  999. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1000. cli_.enable_server_certificate_verification(false);
  1001. #endif
  1002. }
  1003. virtual void SetUp() {
  1004. read_file("./image.jpg", image_data_);
  1005. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1006. res.set_content("Hello World!", "text/plain");
  1007. });
  1008. svr_.Get(
  1009. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1010. res.set_chunked_content_provider(
  1011. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1012. size_t remaining = image_data_.size() - offset;
  1013. if (remaining == 0) {
  1014. sink.done();
  1015. } else {
  1016. constexpr size_t CHUNK_SIZE = 1024;
  1017. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1018. sink.write(&image_data_[offset], send_size);
  1019. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1020. }
  1021. return true;
  1022. });
  1023. });
  1024. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1025. svr_.wait_until_ready();
  1026. }
  1027. virtual void TearDown() {
  1028. svr_.stop();
  1029. if (!request_threads_.empty()) {
  1030. std::this_thread::sleep_for(std::chrono::seconds(1));
  1031. for (auto &t : request_threads_) {
  1032. t.join();
  1033. }
  1034. }
  1035. t_.join();
  1036. }
  1037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1038. SSLClient cli_;
  1039. SSLServer svr_;
  1040. #else
  1041. Client cli_;
  1042. Server svr_;
  1043. #endif
  1044. thread t_;
  1045. std::vector<thread> request_threads_;
  1046. std::string image_data_;
  1047. };
  1048. TEST_F(ChunkedEncodingTest, NormalGet) {
  1049. auto res = cli_.Get("/chunked");
  1050. ASSERT_TRUE(res);
  1051. std::string out;
  1052. read_file("./image.jpg", out);
  1053. EXPECT_EQ(StatusCode::OK_200, res->status);
  1054. EXPECT_EQ(out, res->body);
  1055. }
  1056. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1057. std::string body;
  1058. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1059. body.append(data, data_length);
  1060. return true;
  1061. });
  1062. ASSERT_TRUE(res);
  1063. std::string out;
  1064. read_file("./image.jpg", out);
  1065. EXPECT_EQ(StatusCode::OK_200, res->status);
  1066. EXPECT_EQ(out, body);
  1067. }
  1068. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1069. std::string body;
  1070. auto res = cli_.Get(
  1071. "/chunked",
  1072. [&](const Response &response) {
  1073. EXPECT_EQ(StatusCode::OK_200, response.status);
  1074. return true;
  1075. },
  1076. [&](const char *data, size_t data_length) {
  1077. body.append(data, data_length);
  1078. return true;
  1079. });
  1080. ASSERT_TRUE(res);
  1081. std::string out;
  1082. read_file("./image.jpg", out);
  1083. EXPECT_EQ(StatusCode::OK_200, res->status);
  1084. EXPECT_EQ(out, body);
  1085. }
  1086. TEST(RangeTest, FromHTTPBin_Online) {
  1087. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1088. auto host = "httpbin.org";
  1089. auto path = std::string{"/range/32"};
  1090. #else
  1091. auto host = "nghttp2.org";
  1092. auto path = std::string{"/httpbin/range/32"};
  1093. #endif
  1094. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1095. auto port = 443;
  1096. SSLClient cli(host, port);
  1097. #else
  1098. auto port = 80;
  1099. Client cli(host, port);
  1100. #endif
  1101. cli.set_connection_timeout(5);
  1102. {
  1103. auto res = cli.Get(path);
  1104. ASSERT_TRUE(res);
  1105. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1106. EXPECT_EQ(StatusCode::OK_200, res->status);
  1107. }
  1108. {
  1109. Headers headers = {make_range_header({{1, -1}})};
  1110. auto res = cli.Get(path, headers);
  1111. ASSERT_TRUE(res);
  1112. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1113. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1114. }
  1115. {
  1116. Headers headers = {make_range_header({{1, 10}})};
  1117. auto res = cli.Get(path, headers);
  1118. ASSERT_TRUE(res);
  1119. EXPECT_EQ("bcdefghijk", res->body);
  1120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1121. }
  1122. {
  1123. Headers headers = {make_range_header({{0, 31}})};
  1124. auto res = cli.Get(path, headers);
  1125. ASSERT_TRUE(res);
  1126. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1127. EXPECT_EQ(StatusCode::OK_200, res->status);
  1128. }
  1129. {
  1130. Headers headers = {make_range_header({{0, -1}})};
  1131. auto res = cli.Get(path, headers);
  1132. ASSERT_TRUE(res);
  1133. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1134. EXPECT_EQ(StatusCode::OK_200, res->status);
  1135. }
  1136. {
  1137. Headers headers = {make_range_header({{0, 32}})};
  1138. auto res = cli.Get(path, headers);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1141. }
  1142. }
  1143. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1144. auto host = "unresolvableaddress.local";
  1145. auto path = std::string{"/"};
  1146. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1147. auto port = 443;
  1148. SSLClient cli(host, port);
  1149. #else
  1150. auto port = 80;
  1151. Client cli(host, port);
  1152. #endif
  1153. cli.set_connection_timeout(1);
  1154. {
  1155. auto res = cli.Get(path);
  1156. ASSERT_FALSE(res);
  1157. }
  1158. std::this_thread::sleep_for(std::chrono::seconds(8));
  1159. }
  1160. TEST(ConnectionErrorTest, InvalidHost) {
  1161. auto host = "-abcde.com";
  1162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1163. auto port = 443;
  1164. SSLClient cli(host, port);
  1165. #else
  1166. auto port = 80;
  1167. Client cli(host, port);
  1168. #endif
  1169. cli.set_connection_timeout(std::chrono::seconds(2));
  1170. auto res = cli.Get("/");
  1171. ASSERT_TRUE(!res);
  1172. EXPECT_EQ(Error::Connection, res.error());
  1173. }
  1174. TEST(ConnectionErrorTest, InvalidHost2) {
  1175. auto host = "httpbin.org/";
  1176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1177. SSLClient cli(host);
  1178. #else
  1179. Client cli(host);
  1180. #endif
  1181. cli.set_connection_timeout(std::chrono::seconds(2));
  1182. auto res = cli.Get("/");
  1183. ASSERT_TRUE(!res);
  1184. EXPECT_EQ(Error::Connection, res.error());
  1185. }
  1186. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1187. auto host = "httpbin.org/";
  1188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1189. SSLClient cli(host);
  1190. #else
  1191. Client cli(host);
  1192. #endif
  1193. cli.set_connection_timeout(std::chrono::seconds(2));
  1194. auto res = cli.Get("/");
  1195. ASSERT_TRUE(!res);
  1196. stringstream s;
  1197. s << "error code: " << res.error();
  1198. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1199. }
  1200. TEST(ConnectionErrorTest, InvalidPort) {
  1201. auto host = "localhost";
  1202. auto port = 44380;
  1203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1204. SSLClient cli(host, port);
  1205. #else
  1206. Client cli(host, port);
  1207. #endif
  1208. cli.set_connection_timeout(std::chrono::seconds(2));
  1209. auto res = cli.Get("/");
  1210. ASSERT_TRUE(!res);
  1211. EXPECT_TRUE(Error::Connection == res.error() ||
  1212. Error::ConnectionTimeout == res.error());
  1213. }
  1214. TEST(ConnectionErrorTest, Timeout_Online) {
  1215. auto host = "google.com";
  1216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1217. auto port = 44380;
  1218. SSLClient cli(host, port);
  1219. #else
  1220. auto port = 8080;
  1221. Client cli(host, port);
  1222. #endif
  1223. cli.set_connection_timeout(std::chrono::seconds(2));
  1224. // only probe one address type so that the error reason
  1225. // correlates to the timed-out IPv4, not the unsupported
  1226. // IPv6 connection attempt
  1227. cli.set_address_family(AF_INET);
  1228. auto res = cli.Get("/");
  1229. ASSERT_TRUE(!res);
  1230. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1231. }
  1232. TEST(CancelTest, NoCancel_Online) {
  1233. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1234. auto host = "httpbin.org";
  1235. auto path = std::string{"/range/32"};
  1236. #else
  1237. auto host = "nghttp2.org";
  1238. auto path = std::string{"/httpbin/range/32"};
  1239. #endif
  1240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1241. auto port = 443;
  1242. SSLClient cli(host, port);
  1243. #else
  1244. auto port = 80;
  1245. Client cli(host, port);
  1246. #endif
  1247. cli.set_connection_timeout(std::chrono::seconds(5));
  1248. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1249. ASSERT_TRUE(res);
  1250. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1251. EXPECT_EQ(StatusCode::OK_200, res->status);
  1252. }
  1253. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1254. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1255. auto host = "httpbin.org";
  1256. auto path = std::string{"/range/32"};
  1257. #else
  1258. auto host = "nghttp2.org";
  1259. auto path = std::string{"/httpbin/range/32"};
  1260. #endif
  1261. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1262. auto port = 443;
  1263. SSLClient cli(host, port);
  1264. #else
  1265. auto port = 80;
  1266. Client cli(host, port);
  1267. #endif
  1268. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1269. cli.set_connection_timeout(std::chrono::seconds(5));
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::Canceled, res.error());
  1272. }
  1273. TEST(CancelTest, WithCancelLargePayload_Online) {
  1274. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1275. auto host = "httpbin.org";
  1276. auto path = std::string{"/range/65536"};
  1277. #else
  1278. auto host = "nghttp2.org";
  1279. auto path = std::string{"/httpbin/range/65536"};
  1280. #endif
  1281. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  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. uint32_t count = 0;
  1290. auto res =
  1291. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1292. ASSERT_TRUE(!res);
  1293. EXPECT_EQ(Error::Canceled, res.error());
  1294. }
  1295. TEST(CancelTest, NoCancelPost) {
  1296. Server svr;
  1297. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1298. res.set_content("Hello World!", "text/plain");
  1299. });
  1300. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1301. auto se = detail::scope_exit([&] {
  1302. svr.stop();
  1303. thread.join();
  1304. ASSERT_FALSE(svr.is_running());
  1305. });
  1306. svr.wait_until_ready();
  1307. Client cli(HOST, PORT);
  1308. cli.set_connection_timeout(std::chrono::seconds(5));
  1309. auto res =
  1310. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1311. "application/json", [](uint64_t, uint64_t) { return true; });
  1312. ASSERT_TRUE(res);
  1313. EXPECT_EQ("Hello World!", res->body);
  1314. EXPECT_EQ(StatusCode::OK_200, res->status);
  1315. }
  1316. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1317. Server svr;
  1318. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1319. res.set_content("Hello World!", "text/plain");
  1320. });
  1321. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1322. auto se = detail::scope_exit([&] {
  1323. svr.stop();
  1324. thread.join();
  1325. ASSERT_FALSE(svr.is_running());
  1326. });
  1327. svr.wait_until_ready();
  1328. Client cli(HOST, PORT);
  1329. cli.set_connection_timeout(std::chrono::seconds(5));
  1330. auto res =
  1331. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1332. "application/json", [](uint64_t, uint64_t) { return false; });
  1333. ASSERT_TRUE(!res);
  1334. EXPECT_EQ(Error::Canceled, res.error());
  1335. }
  1336. TEST(CancelTest, WithCancelLargePayloadPost) {
  1337. Server svr;
  1338. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content(LARGE_DATA, "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 false; });
  1353. ASSERT_TRUE(!res);
  1354. EXPECT_EQ(Error::Canceled, res.error());
  1355. }
  1356. TEST(CancelTest, NoCancelPut) {
  1357. Server svr;
  1358. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1359. res.set_content("Hello World!", "text/plain");
  1360. });
  1361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1362. auto se = detail::scope_exit([&] {
  1363. svr.stop();
  1364. thread.join();
  1365. ASSERT_FALSE(svr.is_running());
  1366. });
  1367. svr.wait_until_ready();
  1368. Client cli(HOST, PORT);
  1369. cli.set_connection_timeout(std::chrono::seconds(5));
  1370. auto res =
  1371. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1372. "application/json", [](uint64_t, uint64_t) { return true; });
  1373. ASSERT_TRUE(res);
  1374. EXPECT_EQ("Hello World!", res->body);
  1375. EXPECT_EQ(StatusCode::OK_200, res->status);
  1376. }
  1377. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1378. Server svr;
  1379. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1380. res.set_content("Hello World!", "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.Put("/", 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, WithCancelLargePayloadPut) {
  1398. Server svr;
  1399. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1400. res.set_content(LARGE_DATA, "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 false; });
  1414. ASSERT_TRUE(!res);
  1415. EXPECT_EQ(Error::Canceled, res.error());
  1416. }
  1417. TEST(CancelTest, NoCancelPatch) {
  1418. Server svr;
  1419. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1420. res.set_content("Hello World!", "text/plain");
  1421. });
  1422. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1423. auto se = detail::scope_exit([&] {
  1424. svr.stop();
  1425. thread.join();
  1426. ASSERT_FALSE(svr.is_running());
  1427. });
  1428. svr.wait_until_ready();
  1429. Client cli(HOST, PORT);
  1430. cli.set_connection_timeout(std::chrono::seconds(5));
  1431. auto res =
  1432. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1433. "application/json", [](uint64_t, uint64_t) { return true; });
  1434. ASSERT_TRUE(res);
  1435. EXPECT_EQ("Hello World!", res->body);
  1436. EXPECT_EQ(StatusCode::OK_200, res->status);
  1437. }
  1438. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1439. Server svr;
  1440. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1441. res.set_content("Hello World!", "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.Patch("/", 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, WithCancelLargePayloadPatch) {
  1459. Server svr;
  1460. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content(LARGE_DATA, "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 false; });
  1475. ASSERT_TRUE(!res);
  1476. EXPECT_EQ(Error::Canceled, res.error());
  1477. }
  1478. TEST(CancelTest, NoCancelDelete) {
  1479. Server svr;
  1480. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1481. res.set_content("Hello World!", "text/plain");
  1482. });
  1483. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. thread.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. Client cli(HOST, PORT);
  1491. cli.set_connection_timeout(std::chrono::seconds(5));
  1492. auto res =
  1493. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1494. "application/json", [](uint64_t, uint64_t) { return true; });
  1495. ASSERT_TRUE(res);
  1496. EXPECT_EQ("Hello World!", res->body);
  1497. EXPECT_EQ(StatusCode::OK_200, res->status);
  1498. }
  1499. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1500. Server svr;
  1501. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content("Hello World!", "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.Delete("/", 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, WithCancelLargePayloadDelete) {
  1520. Server svr;
  1521. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1522. res.set_content(LARGE_DATA, "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 false; });
  1536. ASSERT_TRUE(!res);
  1537. EXPECT_EQ(Error::Canceled, res.error());
  1538. }
  1539. static std::string remove_whitespace(const std::string &input) {
  1540. std::string output;
  1541. output.reserve(input.size());
  1542. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1543. [](unsigned char c) { return !std::isspace(c); });
  1544. return output;
  1545. }
  1546. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1547. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1548. auto host = "httpbin.org";
  1549. auto path = std::string{"/basic-auth/hello/world"};
  1550. #else
  1551. auto host = "nghttp2.org";
  1552. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1553. #endif
  1554. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1555. auto port = 443;
  1556. SSLClient cli(host, port);
  1557. #else
  1558. auto port = 80;
  1559. Client cli(host, port);
  1560. #endif
  1561. {
  1562. auto res = cli.Get(path);
  1563. ASSERT_TRUE(res);
  1564. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1565. }
  1566. {
  1567. auto res =
  1568. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1569. ASSERT_TRUE(res);
  1570. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1571. remove_whitespace(res->body));
  1572. EXPECT_EQ(StatusCode::OK_200, res->status);
  1573. }
  1574. {
  1575. cli.set_basic_auth("hello", "world");
  1576. auto res = cli.Get(path);
  1577. ASSERT_TRUE(res);
  1578. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1579. remove_whitespace(res->body));
  1580. EXPECT_EQ(StatusCode::OK_200, res->status);
  1581. }
  1582. {
  1583. cli.set_basic_auth("hello", "bad");
  1584. auto res = cli.Get(path);
  1585. ASSERT_TRUE(res);
  1586. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1587. }
  1588. {
  1589. cli.set_basic_auth("bad", "world");
  1590. auto res = cli.Get(path);
  1591. ASSERT_TRUE(res);
  1592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1593. }
  1594. }
  1595. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1596. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1597. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1598. auto host = "httpbin.org";
  1599. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1600. auto paths = std::vector<std::string>{
  1601. "/digest-auth/auth/hello/world/MD5",
  1602. "/digest-auth/auth/hello/world/SHA-256",
  1603. "/digest-auth/auth/hello/world/SHA-512",
  1604. "/digest-auth/auth-int/hello/world/MD5",
  1605. };
  1606. #else
  1607. auto host = "nghttp2.org";
  1608. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1609. auto paths = std::vector<std::string>{
  1610. "/httpbin/digest-auth/auth/hello/world/MD5",
  1611. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1612. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1613. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1614. };
  1615. #endif
  1616. auto port = 443;
  1617. SSLClient cli(host, port);
  1618. {
  1619. auto res = cli.Get(unauth_path);
  1620. ASSERT_TRUE(res);
  1621. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1622. }
  1623. {
  1624. cli.set_digest_auth("hello", "world");
  1625. for (const auto &path : paths) {
  1626. auto res = cli.Get(path.c_str());
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1629. remove_whitespace(res->body));
  1630. EXPECT_EQ(StatusCode::OK_200, res->status);
  1631. }
  1632. cli.set_digest_auth("hello", "bad");
  1633. for (const auto &path : paths) {
  1634. auto res = cli.Get(path.c_str());
  1635. ASSERT_TRUE(res);
  1636. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1637. }
  1638. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1639. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1640. // cli.set_digest_auth("bad", "world");
  1641. // for (const auto& path : paths) {
  1642. // auto res = cli.Get(path.c_str());
  1643. // ASSERT_TRUE(res);
  1644. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1645. // }
  1646. }
  1647. }
  1648. #endif
  1649. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1650. auto host = "google.com";
  1651. auto another_host = "example.com";
  1652. auto wrong_ip = "0.0.0.0";
  1653. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1654. SSLClient cli(host);
  1655. #else
  1656. Client cli(host);
  1657. #endif
  1658. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1659. auto res = cli.Get("/");
  1660. ASSERT_TRUE(res);
  1661. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1662. }
  1663. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1664. auto host = "google.com";
  1665. auto wrong_ip = "0.0.0.0";
  1666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1667. SSLClient cli(host);
  1668. #else
  1669. Client cli(host);
  1670. #endif
  1671. cli.set_hostname_addr_map({{host, wrong_ip}});
  1672. auto res = cli.Get("/");
  1673. ASSERT_TRUE(!res);
  1674. EXPECT_EQ(Error::Connection, res.error());
  1675. }
  1676. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1677. auto host = "nghttp2.org";
  1678. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1679. SSLClient cli(host);
  1680. #else
  1681. Client cli(host);
  1682. #endif
  1683. cli.set_follow_location(true);
  1684. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ(StatusCode::OK_200, res->status);
  1687. }
  1688. TEST(RedirectTest, Redirect_Online) {
  1689. auto host = "nghttp2.org";
  1690. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1691. SSLClient cli(host);
  1692. #else
  1693. Client cli(host);
  1694. #endif
  1695. cli.set_follow_location(true);
  1696. auto res = cli.Get("/httpbin/redirect/3");
  1697. ASSERT_TRUE(res);
  1698. EXPECT_EQ(StatusCode::OK_200, res->status);
  1699. }
  1700. TEST(RelativeRedirectTest, Redirect_Online) {
  1701. auto host = "nghttp2.org";
  1702. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1703. SSLClient cli(host);
  1704. #else
  1705. Client cli(host);
  1706. #endif
  1707. cli.set_follow_location(true);
  1708. auto res = cli.Get("/httpbin/relative-redirect/3");
  1709. ASSERT_TRUE(res);
  1710. EXPECT_EQ(StatusCode::OK_200, res->status);
  1711. }
  1712. TEST(TooManyRedirectTest, Redirect_Online) {
  1713. auto host = "nghttp2.org";
  1714. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1715. SSLClient cli(host);
  1716. #else
  1717. Client cli(host);
  1718. #endif
  1719. cli.set_follow_location(true);
  1720. auto res = cli.Get("/httpbin/redirect/21");
  1721. ASSERT_TRUE(!res);
  1722. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1723. }
  1724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1725. TEST(YahooRedirectTest, Redirect_Online) {
  1726. Client cli("yahoo.com");
  1727. auto res = cli.Get("/");
  1728. ASSERT_TRUE(res);
  1729. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1730. cli.set_follow_location(true);
  1731. res = cli.Get("/");
  1732. ASSERT_TRUE(res);
  1733. EXPECT_EQ(StatusCode::OK_200, res->status);
  1734. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1735. }
  1736. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1737. #define REDIR_HOST "httpbingo.org"
  1738. #define REDIR_PATH "/redirect-to"
  1739. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1740. SSLClient cli(REDIR_HOST);
  1741. cli.set_follow_location(true);
  1742. auto res =
  1743. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1744. ASSERT_TRUE(res);
  1745. EXPECT_EQ(StatusCode::OK_200, res->status);
  1746. }
  1747. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1748. SSLClient cli(REDIR_HOST);
  1749. cli.set_follow_location(true);
  1750. Params params;
  1751. params.emplace("url", "http://example.com");
  1752. params.emplace("status_code", "302");
  1753. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1754. ASSERT_TRUE(res);
  1755. EXPECT_EQ(StatusCode::OK_200, res->status);
  1756. }
  1757. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1758. SSLClient cli(REDIR_HOST);
  1759. cli.set_follow_location(true);
  1760. Params params;
  1761. params.emplace("url", "http://example.com");
  1762. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1763. ASSERT_TRUE(res);
  1764. EXPECT_EQ(StatusCode::OK_200, res->status);
  1765. }
  1766. TEST(UrlWithSpace, Redirect_Online) {
  1767. SSLClient cli("edge.forgecdn.net");
  1768. cli.set_follow_location(true);
  1769. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1770. ASSERT_TRUE(res);
  1771. EXPECT_EQ(StatusCode::OK_200, res->status);
  1772. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1773. }
  1774. #endif
  1775. #if !defined(_WIN32) && !defined(_WIN64)
  1776. TEST(ReceiveSignals, Signal) {
  1777. auto setupSignalHandlers = []() {
  1778. struct sigaction act;
  1779. sigemptyset(&act.sa_mask);
  1780. act.sa_flags = SA_SIGINFO;
  1781. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1782. switch (sig) {
  1783. case SIGINT:
  1784. default: break;
  1785. }
  1786. };
  1787. ::sigaction(SIGINT, &act, nullptr);
  1788. };
  1789. Server svr;
  1790. int port = 0;
  1791. auto thread = std::thread([&]() {
  1792. setupSignalHandlers();
  1793. port = svr.bind_to_any_port("localhost");
  1794. svr.listen_after_bind();
  1795. });
  1796. auto se = detail::scope_exit([&] {
  1797. svr.stop();
  1798. thread.join();
  1799. ASSERT_FALSE(svr.is_running());
  1800. });
  1801. svr.wait_until_ready();
  1802. ASSERT_TRUE(svr.is_running());
  1803. pthread_kill(thread.native_handle(), SIGINT);
  1804. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1805. ASSERT_TRUE(svr.is_running());
  1806. }
  1807. #endif
  1808. TEST(RedirectToDifferentPort, Redirect) {
  1809. Server svr1;
  1810. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1811. res.set_content("Hello World!", "text/plain");
  1812. });
  1813. int svr1_port = 0;
  1814. auto thread1 = std::thread([&]() {
  1815. svr1_port = svr1.bind_to_any_port("localhost");
  1816. svr1.listen_after_bind();
  1817. });
  1818. Server svr2;
  1819. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1820. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1821. });
  1822. int svr2_port = 0;
  1823. auto thread2 = std::thread([&]() {
  1824. svr2_port = svr2.bind_to_any_port("localhost");
  1825. svr2.listen_after_bind();
  1826. });
  1827. auto se = detail::scope_exit([&] {
  1828. svr2.stop();
  1829. thread2.join();
  1830. svr1.stop();
  1831. thread1.join();
  1832. ASSERT_FALSE(svr2.is_running());
  1833. ASSERT_FALSE(svr1.is_running());
  1834. });
  1835. svr1.wait_until_ready();
  1836. svr2.wait_until_ready();
  1837. Client cli("localhost", svr2_port);
  1838. cli.set_follow_location(true);
  1839. auto res = cli.Get("/2");
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. EXPECT_EQ("Hello World!", res->body);
  1843. }
  1844. TEST(RedirectFromPageWithContent, Redirect) {
  1845. Server svr;
  1846. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1847. res.set_content("___", "text/plain");
  1848. res.set_redirect("/2");
  1849. });
  1850. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1851. res.set_content("Hello World!", "text/plain");
  1852. });
  1853. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1854. auto se = detail::scope_exit([&] {
  1855. svr.stop();
  1856. th.join();
  1857. ASSERT_FALSE(svr.is_running());
  1858. });
  1859. svr.wait_until_ready();
  1860. {
  1861. Client cli("localhost", PORT);
  1862. cli.set_follow_location(true);
  1863. std::string body;
  1864. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1865. body.append(data, data_length);
  1866. return true;
  1867. });
  1868. ASSERT_TRUE(res);
  1869. EXPECT_EQ(StatusCode::OK_200, res->status);
  1870. EXPECT_EQ("Hello World!", body);
  1871. }
  1872. {
  1873. Client cli("localhost", PORT);
  1874. std::string body;
  1875. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1876. body.append(data, data_length);
  1877. return true;
  1878. });
  1879. ASSERT_TRUE(res);
  1880. EXPECT_EQ(StatusCode::Found_302, res->status);
  1881. EXPECT_EQ("___", body);
  1882. }
  1883. }
  1884. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1885. Server svr;
  1886. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1887. res.set_content("___", "text/plain");
  1888. // res.set_redirect("/2");
  1889. res.set_redirect("http://[::1]:1234/2");
  1890. });
  1891. svr.Get("/2", [&](const Request &req, Response &res) {
  1892. auto host_header = req.headers.find("Host");
  1893. ASSERT_TRUE(host_header != req.headers.end());
  1894. EXPECT_EQ("[::1]:1234", host_header->second);
  1895. res.set_content("Hello World!", "text/plain");
  1896. });
  1897. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1898. auto se = detail::scope_exit([&] {
  1899. svr.stop();
  1900. th.join();
  1901. ASSERT_FALSE(svr.is_running());
  1902. });
  1903. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1904. // actually starts anything, so the condition !svr.is_running() will
  1905. // always remain true, and the loop never stops.
  1906. // This basically counts how many milliseconds have passed since the
  1907. // call to svr.listen(), and if after 5 seconds nothing started yet
  1908. // aborts the test.
  1909. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1910. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1911. ASSERT_LT(milliseconds, 5000U);
  1912. }
  1913. {
  1914. Client cli("http://[::1]:1234");
  1915. cli.set_follow_location(true);
  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::OK_200, res->status);
  1923. EXPECT_EQ("Hello World!", body);
  1924. }
  1925. {
  1926. Client cli("http://[::1]:1234");
  1927. std::string body;
  1928. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1929. body.append(data, data_length);
  1930. return true;
  1931. });
  1932. ASSERT_TRUE(res);
  1933. EXPECT_EQ(StatusCode::Found_302, res->status);
  1934. EXPECT_EQ("___", body);
  1935. }
  1936. }
  1937. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1938. Server svr;
  1939. svr.Get("/foo", [](const Request &req, Response &res) {
  1940. auto a = req.params.find("a");
  1941. if (a != req.params.end()) {
  1942. res.set_content((*a).second, "text/plain");
  1943. res.status = StatusCode::OK_200;
  1944. } else {
  1945. res.status = StatusCode::BadRequest_400;
  1946. }
  1947. });
  1948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1949. auto se = detail::scope_exit([&] {
  1950. svr.stop();
  1951. thread.join();
  1952. ASSERT_FALSE(svr.is_running());
  1953. });
  1954. svr.wait_until_ready();
  1955. {
  1956. Client cli(HOST, PORT);
  1957. cli.set_path_encode(false);
  1958. auto res = cli.Get("/foo?a=explicitly+encoded");
  1959. ASSERT_TRUE(res);
  1960. EXPECT_EQ(StatusCode::OK_200, res->status);
  1961. // This expects it back with a space, as the `+` won't have been
  1962. // url-encoded, and server-side the params get decoded turning `+`
  1963. // into spaces.
  1964. EXPECT_EQ("explicitly encoded", res->body);
  1965. }
  1966. }
  1967. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1968. Server svr;
  1969. svr.Get("/", [](const Request &req, Response &) {
  1970. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1971. });
  1972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1973. auto se = detail::scope_exit([&] {
  1974. svr.stop();
  1975. thread.join();
  1976. ASSERT_FALSE(svr.is_running());
  1977. });
  1978. svr.wait_until_ready();
  1979. {
  1980. Client cli(HOST, PORT);
  1981. cli.set_path_encode(false);
  1982. auto res = cli.Get("/?something=%0A");
  1983. ASSERT_TRUE(res);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. }
  1986. }
  1987. TEST(BindServerTest, DISABLED_BindDualStack) {
  1988. Server svr;
  1989. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1990. res.set_content("Hello World!", "text/plain");
  1991. });
  1992. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1993. auto se = detail::scope_exit([&] {
  1994. svr.stop();
  1995. thread.join();
  1996. ASSERT_FALSE(svr.is_running());
  1997. });
  1998. svr.wait_until_ready();
  1999. {
  2000. Client cli("127.0.0.1", PORT);
  2001. auto res = cli.Get("/1");
  2002. ASSERT_TRUE(res);
  2003. EXPECT_EQ(StatusCode::OK_200, res->status);
  2004. EXPECT_EQ("Hello World!", res->body);
  2005. }
  2006. {
  2007. Client cli("::1", PORT);
  2008. auto res = cli.Get("/1");
  2009. ASSERT_TRUE(res);
  2010. EXPECT_EQ(StatusCode::OK_200, res->status);
  2011. EXPECT_EQ("Hello World!", res->body);
  2012. }
  2013. }
  2014. TEST(BindServerTest, BindAndListenSeparately) {
  2015. Server svr;
  2016. int port = svr.bind_to_any_port("0.0.0.0");
  2017. ASSERT_TRUE(svr.is_valid());
  2018. ASSERT_TRUE(port > 0);
  2019. svr.stop();
  2020. }
  2021. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2022. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2024. CLIENT_CA_CERT_DIR);
  2025. int port = svr.bind_to_any_port("0.0.0.0");
  2026. ASSERT_TRUE(svr.is_valid());
  2027. ASSERT_TRUE(port > 0);
  2028. svr.stop();
  2029. }
  2030. #endif
  2031. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2032. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2033. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2034. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2035. int port = svr.bind_to_any_port("0.0.0.0");
  2036. ASSERT_TRUE(svr.is_valid());
  2037. ASSERT_TRUE(port > 0);
  2038. svr.stop();
  2039. }
  2040. #endif
  2041. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2042. X509 *readCertificate(const std::string &strFileName) {
  2043. std::ifstream inStream(strFileName);
  2044. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2045. std::istreambuf_iterator<char>());
  2046. if (strCertPEM.empty()) return (nullptr);
  2047. BIO *pbCert = BIO_new(BIO_s_mem());
  2048. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2049. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2050. BIO_free(pbCert);
  2051. return (pCert);
  2052. }
  2053. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2054. std::ifstream inStream(strFileName);
  2055. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2056. std::istreambuf_iterator<char>());
  2057. if (strPrivateKeyPEM.empty()) return (nullptr);
  2058. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2059. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2060. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2061. BIO_free(pbPrivKey);
  2062. return (pPrivateKey);
  2063. }
  2064. TEST(BindServerTest, UpdateCerts) {
  2065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2066. int port = svr.bind_to_any_port("0.0.0.0");
  2067. ASSERT_TRUE(svr.is_valid());
  2068. ASSERT_TRUE(port > 0);
  2069. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2070. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2071. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2072. ASSERT_TRUE(cert != nullptr);
  2073. ASSERT_TRUE(ca_cert != nullptr);
  2074. ASSERT_TRUE(key != nullptr);
  2075. X509_STORE *cert_store = X509_STORE_new();
  2076. X509_STORE_add_cert(cert_store, ca_cert);
  2077. svr.update_certs(cert, key, cert_store);
  2078. ASSERT_TRUE(svr.is_valid());
  2079. svr.stop();
  2080. X509_free(cert);
  2081. X509_free(ca_cert);
  2082. EVP_PKEY_free(key);
  2083. }
  2084. #endif
  2085. TEST(ErrorHandlerTest, ContentLength) {
  2086. Server svr;
  2087. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2088. res.status = StatusCode::OK_200;
  2089. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2090. "text/html"); // <= Content-Length still 13
  2091. });
  2092. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2093. res.set_content("Hello World!\n", "text/plain");
  2094. res.status = 524;
  2095. });
  2096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2097. auto se = detail::scope_exit([&] {
  2098. svr.stop();
  2099. thread.join();
  2100. ASSERT_FALSE(svr.is_running());
  2101. });
  2102. svr.wait_until_ready();
  2103. {
  2104. Client cli(HOST, PORT);
  2105. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2106. ASSERT_TRUE(res);
  2107. EXPECT_EQ(StatusCode::OK_200, res->status);
  2108. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2109. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2110. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2111. }
  2112. }
  2113. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2114. TEST(ExceptionTest, WithoutExceptionHandler) {
  2115. Server svr;
  2116. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2117. throw std::runtime_error("exception...");
  2118. });
  2119. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2120. throw std::runtime_error("exception\r\n...");
  2121. });
  2122. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2123. auto se = detail::scope_exit([&] {
  2124. svr.stop();
  2125. listen_thread.join();
  2126. ASSERT_FALSE(svr.is_running());
  2127. });
  2128. svr.wait_until_ready();
  2129. Client cli("localhost", PORT);
  2130. {
  2131. auto res = cli.Get("/exception");
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2134. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2135. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2136. }
  2137. {
  2138. auto res = cli.Get("/unknown");
  2139. ASSERT_TRUE(res);
  2140. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2141. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2142. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2143. }
  2144. }
  2145. TEST(ExceptionTest, WithExceptionHandler) {
  2146. Server svr;
  2147. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2148. std::exception_ptr ep) {
  2149. EXPECT_FALSE(ep == nullptr);
  2150. try {
  2151. std::rethrow_exception(ep);
  2152. } catch (std::exception &e) {
  2153. EXPECT_EQ("abc", std::string(e.what()));
  2154. } catch (...) {}
  2155. res.status = StatusCode::InternalServerError_500;
  2156. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2157. "text/html"); // <= Content-Length still 13 at this point
  2158. });
  2159. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2160. res.set_content("Hello World!\n", "text/plain");
  2161. throw std::runtime_error("abc");
  2162. });
  2163. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2164. auto se = detail::scope_exit([&] {
  2165. svr.stop();
  2166. thread.join();
  2167. ASSERT_FALSE(svr.is_running());
  2168. });
  2169. svr.wait_until_ready();
  2170. for (size_t i = 0; i < 10; i++) {
  2171. Client cli(HOST, PORT);
  2172. for (size_t j = 0; j < 100; j++) {
  2173. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2174. ASSERT_TRUE(res);
  2175. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2176. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2177. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2178. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2179. }
  2180. cli.set_keep_alive(true);
  2181. for (size_t j = 0; j < 100; j++) {
  2182. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2183. ASSERT_TRUE(res);
  2184. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2185. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2186. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2187. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2188. }
  2189. }
  2190. }
  2191. TEST(ExceptionTest, AndErrorHandler) {
  2192. Server svr;
  2193. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2194. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2195. });
  2196. svr.set_exception_handler(
  2197. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2198. EXPECT_FALSE(ep == nullptr);
  2199. try {
  2200. std::rethrow_exception(ep);
  2201. } catch (std::exception &e) {
  2202. res.set_content(e.what(), "text/html");
  2203. } catch (...) {}
  2204. res.status = StatusCode::InternalServerError_500;
  2205. });
  2206. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2207. throw std::runtime_error("EXCEPTION");
  2208. });
  2209. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2210. res.set_content("ERROR", "text/html");
  2211. res.status = StatusCode::InternalServerError_500;
  2212. });
  2213. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2214. auto se = detail::scope_exit([&] {
  2215. svr.stop();
  2216. thread.join();
  2217. ASSERT_FALSE(svr.is_running());
  2218. });
  2219. svr.wait_until_ready();
  2220. Client cli(HOST, PORT);
  2221. {
  2222. auto res = cli.Get("/exception");
  2223. ASSERT_TRUE(res);
  2224. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2225. EXPECT_EQ("EXCEPTION", res->body);
  2226. }
  2227. {
  2228. auto res = cli.Get("/error");
  2229. ASSERT_TRUE(res);
  2230. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2231. EXPECT_EQ("ERROR", res->body);
  2232. }
  2233. {
  2234. auto res = cli.Get("/invalid");
  2235. ASSERT_TRUE(res);
  2236. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2237. EXPECT_EQ("NOT_FOUND", res->body);
  2238. }
  2239. }
  2240. #endif
  2241. TEST(NoContentTest, ContentLength) {
  2242. Server svr;
  2243. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2244. res.status = StatusCode::NoContent_204;
  2245. });
  2246. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2247. auto se = detail::scope_exit([&] {
  2248. svr.stop();
  2249. thread.join();
  2250. ASSERT_FALSE(svr.is_running());
  2251. });
  2252. svr.wait_until_ready();
  2253. {
  2254. Client cli(HOST, PORT);
  2255. auto res = cli.Get("/hi");
  2256. ASSERT_TRUE(res);
  2257. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2258. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2259. }
  2260. }
  2261. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2262. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2264. ASSERT_TRUE(svr.is_valid());
  2265. #else
  2266. Server svr;
  2267. #endif
  2268. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2269. if (req.path == "/routing_handler") {
  2270. res.set_header("PRE_ROUTING", "on");
  2271. res.set_content("Routing Handler", "text/plain");
  2272. return httplib::Server::HandlerResponse::Handled;
  2273. }
  2274. return httplib::Server::HandlerResponse::Unhandled;
  2275. });
  2276. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2277. res.set_content("Error", "text/html");
  2278. });
  2279. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2280. if (req.path == "/routing_handler") {
  2281. res.set_header("POST_ROUTING", "on");
  2282. }
  2283. });
  2284. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!\n", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. {
  2295. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2296. SSLClient cli(HOST, PORT);
  2297. cli.enable_server_certificate_verification(false);
  2298. #else
  2299. Client cli(HOST, PORT);
  2300. #endif
  2301. auto res = cli.Get("/routing_handler");
  2302. ASSERT_TRUE(res);
  2303. EXPECT_EQ(StatusCode::OK_200, res->status);
  2304. EXPECT_EQ("Routing Handler", res->body);
  2305. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2306. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2307. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2308. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2309. }
  2310. {
  2311. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2312. SSLClient cli(HOST, PORT);
  2313. cli.enable_server_certificate_verification(false);
  2314. #else
  2315. Client cli(HOST, PORT);
  2316. #endif
  2317. auto res = cli.Get("/hi");
  2318. ASSERT_TRUE(res);
  2319. EXPECT_EQ(StatusCode::OK_200, res->status);
  2320. EXPECT_EQ("Hello World!\n", res->body);
  2321. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2322. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2323. }
  2324. {
  2325. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2326. SSLClient cli(HOST, PORT);
  2327. cli.enable_server_certificate_verification(false);
  2328. #else
  2329. Client cli(HOST, PORT);
  2330. #endif
  2331. auto res = cli.Get("/aaa");
  2332. ASSERT_TRUE(res);
  2333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2334. EXPECT_EQ("Error", res->body);
  2335. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2336. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2337. }
  2338. }
  2339. TEST(RequestHandlerTest, PreRequestHandler) {
  2340. auto route_path = "/user/:user";
  2341. Server svr;
  2342. svr.Get("/hi", [](const Request &, Response &res) {
  2343. res.set_content("hi", "text/plain");
  2344. });
  2345. svr.Get(route_path, [](const Request &req, Response &res) {
  2346. res.set_content(req.path_params.at("user"), "text/plain");
  2347. });
  2348. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2349. if (req.matched_route == route_path) {
  2350. auto user = req.path_params.at("user");
  2351. if (user != "john") {
  2352. res.status = StatusCode::Forbidden_403;
  2353. res.set_content("error", "text/html");
  2354. return Server::HandlerResponse::Handled;
  2355. }
  2356. }
  2357. return Server::HandlerResponse::Unhandled;
  2358. });
  2359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2360. auto se = detail::scope_exit([&] {
  2361. svr.stop();
  2362. thread.join();
  2363. ASSERT_FALSE(svr.is_running());
  2364. });
  2365. svr.wait_until_ready();
  2366. Client cli(HOST, PORT);
  2367. {
  2368. auto res = cli.Get("/hi");
  2369. ASSERT_TRUE(res);
  2370. EXPECT_EQ(StatusCode::OK_200, res->status);
  2371. EXPECT_EQ("hi", res->body);
  2372. }
  2373. {
  2374. auto res = cli.Get("/user/john");
  2375. ASSERT_TRUE(res);
  2376. EXPECT_EQ(StatusCode::OK_200, res->status);
  2377. EXPECT_EQ("john", res->body);
  2378. }
  2379. {
  2380. auto res = cli.Get("/user/invalid-user");
  2381. ASSERT_TRUE(res);
  2382. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2383. EXPECT_EQ("error", res->body);
  2384. }
  2385. }
  2386. TEST(InvalidFormatTest, StatusCode) {
  2387. Server svr;
  2388. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2389. res.set_content("Hello World!\n", "text/plain");
  2390. res.status = 9999; // Status should be a three-digit code...
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. {
  2400. Client cli(HOST, PORT);
  2401. auto res = cli.Get("/hi");
  2402. ASSERT_FALSE(res);
  2403. }
  2404. }
  2405. TEST(URLFragmentTest, WithFragment) {
  2406. Server svr;
  2407. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2408. EXPECT_TRUE(req.target == "/hi");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. {
  2418. Client cli(HOST, PORT);
  2419. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2420. EXPECT_TRUE(res);
  2421. EXPECT_EQ(StatusCode::OK_200, res->status);
  2422. res = cli.Get("/hi%23key1=val1=key2=val2");
  2423. EXPECT_TRUE(res);
  2424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2425. }
  2426. }
  2427. TEST(HeaderWriter, SetHeaderWriter) {
  2428. Server svr;
  2429. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2430. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2431. return detail::write_headers(strm, hdrs);
  2432. });
  2433. svr.Get("/hi", [](const Request &req, Response &res) {
  2434. auto it = req.headers.find("CustomClientHeader");
  2435. EXPECT_TRUE(it != req.headers.end());
  2436. EXPECT_EQ(it->second, "CustomClientValue");
  2437. res.set_content("Hello World!\n", "text/plain");
  2438. });
  2439. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2440. auto se = detail::scope_exit([&] {
  2441. svr.stop();
  2442. thread.join();
  2443. ASSERT_FALSE(svr.is_running());
  2444. });
  2445. svr.wait_until_ready();
  2446. {
  2447. Client cli(HOST, PORT);
  2448. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2449. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2450. return detail::write_headers(strm, hdrs);
  2451. });
  2452. auto res = cli.Get("/hi");
  2453. EXPECT_TRUE(res);
  2454. EXPECT_EQ(StatusCode::OK_200, res->status);
  2455. auto it = res->headers.find("CustomServerHeader");
  2456. EXPECT_TRUE(it != res->headers.end());
  2457. EXPECT_EQ(it->second, "CustomServerValue");
  2458. }
  2459. }
  2460. class ServerTest : public ::testing::Test {
  2461. protected:
  2462. ServerTest()
  2463. : cli_(HOST, PORT)
  2464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2465. ,
  2466. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2467. #endif
  2468. {
  2469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2470. cli_.enable_server_certificate_verification(false);
  2471. #endif
  2472. }
  2473. virtual void SetUp() {
  2474. svr_.set_mount_point("/", "./www");
  2475. svr_.set_mount_point("/mount", "./www2");
  2476. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2477. svr_.Get("/hi",
  2478. [&](const Request & /*req*/, Response &res) {
  2479. res.set_content("Hello World!", "text/plain");
  2480. })
  2481. .Get("/file_content",
  2482. [&](const Request & /*req*/, Response &res) {
  2483. res.set_file_content("./www/dir/test.html");
  2484. })
  2485. .Get("/file_content_with_content_type",
  2486. [&](const Request & /*req*/, Response &res) {
  2487. res.set_file_content("./www/file", "text/plain");
  2488. })
  2489. .Get("/invalid_file_content",
  2490. [&](const Request & /*req*/, Response &res) {
  2491. res.set_file_content("./www/dir/invalid_file_path");
  2492. })
  2493. .Get("/http_response_splitting",
  2494. [&](const Request & /*req*/, Response &res) {
  2495. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2496. EXPECT_EQ(0U, res.headers.size());
  2497. EXPECT_FALSE(res.has_header("a"));
  2498. res.set_header("a", "1\nSet-Cookie: a=1");
  2499. EXPECT_EQ(0U, res.headers.size());
  2500. EXPECT_FALSE(res.has_header("a"));
  2501. res.set_header("a", "1\rSet-Cookie: a=1");
  2502. EXPECT_EQ(0U, res.headers.size());
  2503. EXPECT_FALSE(res.has_header("a"));
  2504. res.set_header("a\r\nb", "0");
  2505. EXPECT_EQ(0U, res.headers.size());
  2506. EXPECT_FALSE(res.has_header("a"));
  2507. res.set_header("a\rb", "0");
  2508. EXPECT_EQ(0U, res.headers.size());
  2509. EXPECT_FALSE(res.has_header("a"));
  2510. res.set_header("a\nb", "0");
  2511. EXPECT_EQ(0U, res.headers.size());
  2512. EXPECT_FALSE(res.has_header("a"));
  2513. res.set_redirect("1\r\nSet-Cookie: a=1");
  2514. EXPECT_EQ(0U, res.headers.size());
  2515. EXPECT_FALSE(res.has_header("Location"));
  2516. })
  2517. .Get("/slow",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. std::this_thread::sleep_for(std::chrono::seconds(2));
  2520. res.set_content("slow", "text/plain");
  2521. })
  2522. #if 0
  2523. .Post("/slowpost",
  2524. [&](const Request & /*req*/, Response &res) {
  2525. std::this_thread::sleep_for(std::chrono::seconds(2));
  2526. res.set_content("slow", "text/plain");
  2527. })
  2528. #endif
  2529. .Get("/remote_addr",
  2530. [&](const Request &req, Response &res) {
  2531. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2532. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2533. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2534. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2535. res.set_content(req.remote_addr, "text/plain");
  2536. })
  2537. .Get("/local_addr",
  2538. [&](const Request &req, Response &res) {
  2539. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2540. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2541. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2542. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2543. auto local_addr = req.local_addr;
  2544. auto local_port = std::to_string(req.local_port);
  2545. res.set_content(local_addr.append(":").append(local_port),
  2546. "text/plain");
  2547. })
  2548. .Get("/endwith%",
  2549. [&](const Request & /*req*/, Response &res) {
  2550. res.set_content("Hello World!", "text/plain");
  2551. })
  2552. .Get("/a\\+\\+b",
  2553. [&](const Request &req, Response &res) {
  2554. ASSERT_TRUE(req.has_param("a +b"));
  2555. auto val = req.get_param_value("a +b");
  2556. res.set_content(val, "text/plain");
  2557. })
  2558. .Get("/", [&](const Request & /*req*/,
  2559. Response &res) { res.set_redirect("/hi"); })
  2560. .Post("/1",
  2561. [](const Request & /*req*/, Response &res) {
  2562. res.set_redirect("/2", StatusCode::SeeOther_303);
  2563. })
  2564. .Get("/2",
  2565. [](const Request & /*req*/, Response &res) {
  2566. res.set_content("redirected.", "text/plain");
  2567. res.status = StatusCode::OK_200;
  2568. })
  2569. .Post("/person",
  2570. [&](const Request &req, Response &res) {
  2571. if (req.has_param("name") && req.has_param("note")) {
  2572. persons_[req.get_param_value("name")] =
  2573. req.get_param_value("note");
  2574. } else {
  2575. res.status = StatusCode::BadRequest_400;
  2576. }
  2577. })
  2578. .Put("/person",
  2579. [&](const Request &req, Response &res) {
  2580. if (req.has_param("name") && req.has_param("note")) {
  2581. persons_[req.get_param_value("name")] =
  2582. req.get_param_value("note");
  2583. } else {
  2584. res.status = StatusCode::BadRequest_400;
  2585. }
  2586. })
  2587. .Get("/person/(.*)",
  2588. [&](const Request &req, Response &res) {
  2589. string name = req.matches[1];
  2590. if (persons_.find(name) != persons_.end()) {
  2591. auto note = persons_[name];
  2592. res.set_content(note, "text/plain");
  2593. } else {
  2594. res.status = StatusCode::NotFound_404;
  2595. }
  2596. })
  2597. .Delete("/person",
  2598. [&](const Request &req, Response &res) {
  2599. if (req.has_param("name")) {
  2600. string name = req.get_param_value("name");
  2601. if (persons_.find(name) != persons_.end()) {
  2602. persons_.erase(name);
  2603. res.set_content("DELETED", "text/plain");
  2604. } else {
  2605. res.status = StatusCode::NotFound_404;
  2606. }
  2607. } else {
  2608. res.status = StatusCode::BadRequest_400;
  2609. }
  2610. })
  2611. .Post("/x-www-form-urlencoded-json",
  2612. [&](const Request &req, Response &res) {
  2613. auto json = req.get_param_value("json");
  2614. ASSERT_EQ(JSON_DATA, json);
  2615. res.set_content(json, "appliation/json");
  2616. res.status = StatusCode::OK_200;
  2617. })
  2618. .Get("/streamed-chunked",
  2619. [&](const Request & /*req*/, Response &res) {
  2620. res.set_chunked_content_provider(
  2621. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2622. sink.os << "123";
  2623. sink.os << "456";
  2624. sink.os << "789";
  2625. sink.done();
  2626. return true;
  2627. });
  2628. })
  2629. .Get("/streamed-chunked2",
  2630. [&](const Request & /*req*/, Response &res) {
  2631. auto i = new int(0);
  2632. res.set_chunked_content_provider(
  2633. "text/plain",
  2634. [i](size_t /*offset*/, DataSink &sink) {
  2635. switch (*i) {
  2636. case 0: sink.os << "123"; break;
  2637. case 1: sink.os << "456"; break;
  2638. case 2: sink.os << "789"; break;
  2639. case 3: sink.done(); break;
  2640. }
  2641. (*i)++;
  2642. return true;
  2643. },
  2644. [i](bool success) {
  2645. EXPECT_TRUE(success);
  2646. delete i;
  2647. });
  2648. })
  2649. .Get("/streamed-chunked-with-trailer",
  2650. [&](const Request & /*req*/, Response &res) {
  2651. auto i = new int(0);
  2652. res.set_header("Trailer", "Dummy1, Dummy2");
  2653. res.set_chunked_content_provider(
  2654. "text/plain",
  2655. [i](size_t /*offset*/, DataSink &sink) {
  2656. switch (*i) {
  2657. case 0: sink.os << "123"; break;
  2658. case 1: sink.os << "456"; break;
  2659. case 2: sink.os << "789"; break;
  2660. case 3: {
  2661. sink.done_with_trailer(
  2662. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2663. } break;
  2664. }
  2665. (*i)++;
  2666. return true;
  2667. },
  2668. [i](bool success) {
  2669. EXPECT_TRUE(success);
  2670. delete i;
  2671. });
  2672. })
  2673. .Get("/streamed",
  2674. [&](const Request & /*req*/, Response &res) {
  2675. res.set_content_provider(
  2676. 6, "text/plain",
  2677. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2678. sink.os << (offset < 3 ? "a" : "b");
  2679. return true;
  2680. });
  2681. })
  2682. .Get("/streamed-with-range",
  2683. [&](const Request &req, Response &res) {
  2684. auto data = new std::string("abcdefg");
  2685. res.set_content_provider(
  2686. data->size(), "text/plain",
  2687. [data](size_t offset, size_t length, DataSink &sink) {
  2688. size_t DATA_CHUNK_SIZE = 4;
  2689. const auto &d = *data;
  2690. auto out_len =
  2691. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2692. auto ret =
  2693. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2694. EXPECT_TRUE(ret);
  2695. return true;
  2696. },
  2697. [data, &req](bool success) {
  2698. EXPECT_EQ(success, !req.has_param("error"));
  2699. delete data;
  2700. });
  2701. })
  2702. .Get("/streamed-cancel",
  2703. [&](const Request & /*req*/, Response &res) {
  2704. res.set_content_provider(
  2705. size_t(-1), "text/plain",
  2706. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2707. sink.os << "data_chunk";
  2708. return true;
  2709. });
  2710. })
  2711. .Get("/regex-with-delimiter",
  2712. [&](const Request &req, Response & /*res*/) {
  2713. ASSERT_TRUE(req.has_param("key"));
  2714. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2715. })
  2716. .Get("/with-range",
  2717. [&](const Request & /*req*/, Response &res) {
  2718. res.set_content("abcdefg", "text/plain");
  2719. })
  2720. .Get("/test-start-time",
  2721. [&](const Request &req, Response & /*res*/) {
  2722. EXPECT_NE(req.start_time_,
  2723. std::chrono::steady_clock::time_point::min());
  2724. })
  2725. .Get("/with-range-customized-response",
  2726. [&](const Request & /*req*/, Response &res) {
  2727. res.status = StatusCode::BadRequest_400;
  2728. res.set_content(JSON_DATA, "application/json");
  2729. })
  2730. .Post("/chunked",
  2731. [&](const Request &req, Response & /*res*/) {
  2732. EXPECT_EQ(req.body, "dechunked post body");
  2733. })
  2734. .Post("/large-chunked",
  2735. [&](const Request &req, Response & /*res*/) {
  2736. std::string expected(6 * 30 * 1024u, 'a');
  2737. EXPECT_EQ(req.body, expected);
  2738. })
  2739. .Post("/multipart",
  2740. [&](const Request &req, Response & /*res*/) {
  2741. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2742. req.form.get_field_count("text2") +
  2743. req.form.get_field_count("file3") +
  2744. req.form.get_field_count("file4"));
  2745. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2746. req.form.get_file_count("file2"));
  2747. ASSERT_TRUE(!req.form.has_file("???"));
  2748. ASSERT_TRUE(!req.form.has_field("???"));
  2749. ASSERT_TRUE(req.body.empty());
  2750. {
  2751. const auto &text = req.form.get_field("text1");
  2752. EXPECT_EQ("text default", text);
  2753. }
  2754. {
  2755. const auto &text = req.form.get_field("text2");
  2756. EXPECT_EQ("aωb", text);
  2757. }
  2758. {
  2759. const auto &file = req.form.get_file("file1");
  2760. EXPECT_EQ("hello.txt", file.filename);
  2761. EXPECT_EQ("text/plain", file.content_type);
  2762. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2763. }
  2764. {
  2765. const auto &file = req.form.get_file("file2");
  2766. EXPECT_EQ("world.json", file.filename);
  2767. EXPECT_EQ("application/json", file.content_type);
  2768. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2769. }
  2770. {
  2771. const auto &text = req.form.get_field("file3");
  2772. EXPECT_EQ(0u, text.size());
  2773. }
  2774. {
  2775. const auto &text = req.form.get_field("file4");
  2776. EXPECT_EQ(0u, text.size());
  2777. }
  2778. })
  2779. .Post("/multipart/multi_file_values",
  2780. [&](const Request &req, Response & /*res*/) {
  2781. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2782. req.form.get_field_count("multi_text1"));
  2783. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2784. ASSERT_TRUE(!req.form.has_file("???"));
  2785. ASSERT_TRUE(!req.form.has_field("???"));
  2786. ASSERT_TRUE(req.body.empty());
  2787. {
  2788. const auto &text = req.form.get_field("text");
  2789. EXPECT_EQ("default text", text);
  2790. }
  2791. {
  2792. const auto &text1_values = req.form.get_fields("multi_text1");
  2793. EXPECT_EQ(2u, text1_values.size());
  2794. EXPECT_EQ("aaaaa", text1_values[0]);
  2795. EXPECT_EQ("bbbbb", text1_values[1]);
  2796. }
  2797. {
  2798. const auto &file1_values = req.form.get_files("multi_file1");
  2799. EXPECT_EQ(2u, file1_values.size());
  2800. auto file1 = file1_values[0];
  2801. EXPECT_EQ(file1.filename, "hello.txt");
  2802. EXPECT_EQ(file1.content_type, "text/plain");
  2803. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2804. auto file2 = file1_values[1];
  2805. EXPECT_EQ(file2.filename, "world.json");
  2806. EXPECT_EQ(file2.content_type, "application/json");
  2807. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2808. }
  2809. })
  2810. .Post("/empty",
  2811. [&](const Request &req, Response &res) {
  2812. EXPECT_EQ(req.body, "");
  2813. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2814. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2815. res.set_content("empty", "text/plain");
  2816. })
  2817. .Post("/empty-no-content-type",
  2818. [&](const Request &req, Response &res) {
  2819. EXPECT_EQ(req.body, "");
  2820. EXPECT_FALSE(req.has_header("Content-Type"));
  2821. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2822. res.set_content("empty-no-content-type", "text/plain");
  2823. })
  2824. .Post("/path-only",
  2825. [&](const Request &req, Response &res) {
  2826. EXPECT_EQ(req.body, "");
  2827. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2828. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2829. res.set_content("path-only", "text/plain");
  2830. })
  2831. .Post("/path-headers-only",
  2832. [&](const Request &req, Response &res) {
  2833. EXPECT_EQ(req.body, "");
  2834. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2835. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2836. EXPECT_EQ("world", req.get_header_value("hello"));
  2837. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2838. res.set_content("path-headers-only", "text/plain");
  2839. })
  2840. .Post("/post-large",
  2841. [&](const Request &req, Response &res) {
  2842. EXPECT_EQ(req.body, LARGE_DATA);
  2843. res.set_content(req.body, "text/plain");
  2844. })
  2845. .Post("/post-loopback",
  2846. [&](const Request &req, Response &res,
  2847. ContentReader const &content_reader) {
  2848. std::string body;
  2849. content_reader([&](const char *data, size_t data_length) {
  2850. body.append(data, data_length);
  2851. return true;
  2852. });
  2853. res.set_content(body, "text/plain");
  2854. })
  2855. .Put("/put-loopback",
  2856. [&](const Request &req, Response &res,
  2857. ContentReader const &content_reader) {
  2858. std::string body;
  2859. content_reader([&](const char *data, size_t data_length) {
  2860. body.append(data, data_length);
  2861. return true;
  2862. });
  2863. res.set_content(body, "text/plain");
  2864. })
  2865. .Patch("/patch-loopback",
  2866. [&](const Request &req, Response &res,
  2867. ContentReader const &content_reader) {
  2868. std::string body;
  2869. content_reader([&](const char *data, size_t data_length) {
  2870. body.append(data, data_length);
  2871. return true;
  2872. });
  2873. res.set_content(body, "text/plain");
  2874. })
  2875. .Put("/empty-no-content-type",
  2876. [&](const Request &req, Response &res) {
  2877. EXPECT_EQ(req.body, "");
  2878. EXPECT_FALSE(req.has_header("Content-Type"));
  2879. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2880. res.set_content("empty-no-content-type", "text/plain");
  2881. })
  2882. .Put("/put",
  2883. [&](const Request &req, Response &res) {
  2884. EXPECT_EQ(req.body, "PUT");
  2885. res.set_content(req.body, "text/plain");
  2886. })
  2887. .Put("/put-large",
  2888. [&](const Request &req, Response &res) {
  2889. EXPECT_EQ(req.body, LARGE_DATA);
  2890. res.set_content(req.body, "text/plain");
  2891. })
  2892. .Patch("/patch",
  2893. [&](const Request &req, Response &res) {
  2894. EXPECT_EQ(req.body, "PATCH");
  2895. res.set_content(req.body, "text/plain");
  2896. })
  2897. .Delete("/delete",
  2898. [&](const Request & /*req*/, Response &res) {
  2899. res.set_content("DELETE", "text/plain");
  2900. })
  2901. .Delete("/delete-body",
  2902. [&](const Request &req, Response &res) {
  2903. EXPECT_EQ(req.body, "content");
  2904. res.set_content(req.body, "text/plain");
  2905. })
  2906. .Options(R"(\*)",
  2907. [&](const Request & /*req*/, Response &res) {
  2908. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2909. })
  2910. .Get("/request-target",
  2911. [&](const Request &req, Response & /*res*/) {
  2912. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2913. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2914. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2915. })
  2916. .Get("/long-query-value",
  2917. [&](const Request &req, Response & /*res*/) {
  2918. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2919. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2920. })
  2921. .Get("/too-long-query-value",
  2922. [&](const Request &req, Response & /*res*/) {
  2923. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2924. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2925. })
  2926. .Get("/array-param",
  2927. [&](const Request &req, Response & /*res*/) {
  2928. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2929. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2930. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2931. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2932. })
  2933. .Post("/validate-no-multiple-headers",
  2934. [&](const Request &req, Response & /*res*/) {
  2935. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2936. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2937. })
  2938. .Post("/content_receiver",
  2939. [&](const Request &req, Response &res,
  2940. const ContentReader &content_reader) {
  2941. if (req.is_multipart_form_data()) {
  2942. std::vector<FormData> items;
  2943. content_reader(
  2944. [&](const FormData &file) {
  2945. items.push_back(file);
  2946. return true;
  2947. },
  2948. [&](const char *data, size_t data_length) {
  2949. items.back().content.append(data, data_length);
  2950. return true;
  2951. });
  2952. EXPECT_EQ(5u, items.size());
  2953. {
  2954. const auto &file = get_file_value(items, "text1");
  2955. EXPECT_TRUE(file.filename.empty());
  2956. EXPECT_EQ("text default", file.content);
  2957. }
  2958. {
  2959. const auto &file = get_file_value(items, "text2");
  2960. EXPECT_TRUE(file.filename.empty());
  2961. EXPECT_EQ("aωb", file.content);
  2962. }
  2963. {
  2964. const auto &file = get_file_value(items, "file1");
  2965. EXPECT_EQ("hello.txt", file.filename);
  2966. EXPECT_EQ("text/plain", file.content_type);
  2967. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2968. }
  2969. {
  2970. const auto &file = get_file_value(items, "file2");
  2971. EXPECT_EQ("world.json", file.filename);
  2972. EXPECT_EQ("application/json", file.content_type);
  2973. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2974. }
  2975. {
  2976. const auto &file = get_file_value(items, "file3");
  2977. EXPECT_TRUE(file.filename.empty());
  2978. EXPECT_EQ("application/octet-stream", file.content_type);
  2979. EXPECT_EQ(0u, file.content.size());
  2980. }
  2981. } else {
  2982. std::string body;
  2983. content_reader([&](const char *data, size_t data_length) {
  2984. EXPECT_EQ(7U, data_length);
  2985. body.append(data, data_length);
  2986. return true;
  2987. });
  2988. EXPECT_EQ(body, "content");
  2989. res.set_content(body, "text/plain");
  2990. }
  2991. })
  2992. .Put("/content_receiver",
  2993. [&](const Request & /*req*/, Response &res,
  2994. const ContentReader &content_reader) {
  2995. std::string body;
  2996. content_reader([&](const char *data, size_t data_length) {
  2997. body.append(data, data_length);
  2998. return true;
  2999. });
  3000. EXPECT_EQ(body, "content");
  3001. res.set_content(body, "text/plain");
  3002. })
  3003. .Patch("/content_receiver",
  3004. [&](const Request & /*req*/, Response &res,
  3005. const ContentReader &content_reader) {
  3006. std::string body;
  3007. content_reader([&](const char *data, size_t data_length) {
  3008. body.append(data, data_length);
  3009. return true;
  3010. });
  3011. EXPECT_EQ(body, "content");
  3012. res.set_content(body, "text/plain");
  3013. })
  3014. .Post("/query-string-and-body",
  3015. [&](const Request &req, Response & /*res*/) {
  3016. ASSERT_TRUE(req.has_param("key"));
  3017. EXPECT_EQ(req.get_param_value("key"), "value");
  3018. EXPECT_EQ(req.body, "content");
  3019. })
  3020. .Get("/last-request",
  3021. [&](const Request &req, Response & /*res*/) {
  3022. EXPECT_EQ("close", req.get_header_value("Connection"));
  3023. })
  3024. .Get(R"(/redirect/(\d+))",
  3025. [&](const Request &req, Response &res) {
  3026. auto num = std::stoi(req.matches[1]) + 1;
  3027. std::string url = "/redirect/" + std::to_string(num);
  3028. res.set_redirect(url);
  3029. })
  3030. .Post("/binary",
  3031. [&](const Request &req, Response &res) {
  3032. EXPECT_EQ(4U, req.body.size());
  3033. EXPECT_EQ("application/octet-stream",
  3034. req.get_header_value("Content-Type"));
  3035. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3036. res.set_content(req.body, "application/octet-stream");
  3037. })
  3038. .Put("/binary",
  3039. [&](const Request &req, Response &res) {
  3040. EXPECT_EQ(4U, req.body.size());
  3041. EXPECT_EQ("application/octet-stream",
  3042. req.get_header_value("Content-Type"));
  3043. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3044. res.set_content(req.body, "application/octet-stream");
  3045. })
  3046. .Patch("/binary",
  3047. [&](const Request &req, Response &res) {
  3048. EXPECT_EQ(4U, req.body.size());
  3049. EXPECT_EQ("application/octet-stream",
  3050. req.get_header_value("Content-Type"));
  3051. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3052. res.set_content(req.body, "application/octet-stream");
  3053. })
  3054. .Delete("/binary",
  3055. [&](const Request &req, Response &res) {
  3056. EXPECT_EQ(4U, req.body.size());
  3057. EXPECT_EQ("application/octet-stream",
  3058. req.get_header_value("Content-Type"));
  3059. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3060. res.set_content(req.body, "application/octet-stream");
  3061. })
  3062. .Get("/issue1772",
  3063. [&](const Request & /*req*/, Response &res) {
  3064. res.status = 401;
  3065. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3066. })
  3067. .Delete("/issue609",
  3068. [](const httplib::Request &, httplib::Response &res,
  3069. const httplib::ContentReader &) {
  3070. res.set_content("ok", "text/plain");
  3071. })
  3072. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3073. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3074. .Get("/compress",
  3075. [&](const Request & /*req*/, Response &res) {
  3076. res.set_content(
  3077. "12345678901234567890123456789012345678901234567890123456789"
  3078. "01234567890123456789012345678901234567890",
  3079. "text/plain");
  3080. })
  3081. .Get("/nocompress",
  3082. [&](const Request & /*req*/, Response &res) {
  3083. res.set_content(
  3084. "12345678901234567890123456789012345678901234567890123456789"
  3085. "01234567890123456789012345678901234567890",
  3086. "application/octet-stream");
  3087. })
  3088. .Post("/compress-multipart",
  3089. [&](const Request &req, Response & /*res*/) {
  3090. EXPECT_EQ(2u, req.form.fields.size());
  3091. ASSERT_TRUE(!req.form.has_field("???"));
  3092. {
  3093. const auto &text = req.form.get_field("key1");
  3094. EXPECT_EQ("test", text);
  3095. }
  3096. {
  3097. const auto &text = req.form.get_field("key2");
  3098. EXPECT_EQ("--abcdefg123", text);
  3099. }
  3100. })
  3101. #endif
  3102. ;
  3103. persons_["john"] = "programmer";
  3104. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3105. svr_.wait_until_ready();
  3106. }
  3107. virtual void TearDown() {
  3108. svr_.stop();
  3109. if (!request_threads_.empty()) {
  3110. std::this_thread::sleep_for(std::chrono::seconds(1));
  3111. for (auto &t : request_threads_) {
  3112. t.join();
  3113. }
  3114. }
  3115. t_.join();
  3116. }
  3117. map<string, string> persons_;
  3118. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3119. SSLClient cli_;
  3120. SSLServer svr_;
  3121. #else
  3122. Client cli_;
  3123. Server svr_;
  3124. #endif
  3125. thread t_;
  3126. std::vector<thread> request_threads_;
  3127. };
  3128. TEST_F(ServerTest, GetMethod200) {
  3129. auto res = cli_.Get("/hi");
  3130. ASSERT_TRUE(res);
  3131. EXPECT_EQ("HTTP/1.1", res->version);
  3132. EXPECT_EQ(StatusCode::OK_200, res->status);
  3133. EXPECT_EQ("OK", res->reason);
  3134. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3135. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3136. EXPECT_EQ("Hello World!", res->body);
  3137. }
  3138. TEST_F(ServerTest, GetEmptyFile) {
  3139. auto res = cli_.Get("/empty_file");
  3140. ASSERT_TRUE(res);
  3141. EXPECT_EQ(StatusCode::OK_200, res->status);
  3142. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3143. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3144. EXPECT_EQ("", res->body);
  3145. }
  3146. TEST_F(ServerTest, GetFileContent) {
  3147. auto res = cli_.Get("/file_content");
  3148. ASSERT_TRUE(res);
  3149. EXPECT_EQ(StatusCode::OK_200, res->status);
  3150. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3151. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3152. EXPECT_EQ("test.html", res->body);
  3153. }
  3154. TEST_F(ServerTest, GetFileContentWithRange) {
  3155. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3156. ASSERT_TRUE(res);
  3157. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3158. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3159. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3160. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3161. EXPECT_EQ("est", res->body);
  3162. }
  3163. TEST_F(ServerTest, GetFileContentWithContentType) {
  3164. auto res = cli_.Get("/file_content_with_content_type");
  3165. ASSERT_TRUE(res);
  3166. EXPECT_EQ(StatusCode::OK_200, res->status);
  3167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3168. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3169. EXPECT_EQ("file\n", res->body);
  3170. }
  3171. TEST_F(ServerTest, GetInvalidFileContent) {
  3172. auto res = cli_.Get("/invalid_file_content");
  3173. ASSERT_TRUE(res);
  3174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3175. }
  3176. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3177. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3178. ASSERT_TRUE(res);
  3179. EXPECT_EQ("HTTP/1.1", res->version);
  3180. EXPECT_EQ(StatusCode::OK_200, res->status);
  3181. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3182. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3183. EXPECT_EQ("Hello World!", res->body);
  3184. }
  3185. TEST_F(ServerTest, GetMethod302) {
  3186. auto res = cli_.Get("/");
  3187. ASSERT_TRUE(res);
  3188. EXPECT_EQ(StatusCode::Found_302, res->status);
  3189. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3190. }
  3191. TEST_F(ServerTest, GetMethod302Redirect) {
  3192. cli_.set_follow_location(true);
  3193. auto res = cli_.Get("/");
  3194. ASSERT_TRUE(res);
  3195. EXPECT_EQ(StatusCode::OK_200, res->status);
  3196. EXPECT_EQ("Hello World!", res->body);
  3197. EXPECT_EQ("/hi", res->location);
  3198. }
  3199. TEST_F(ServerTest, GetMethod404) {
  3200. auto res = cli_.Get("/invalid");
  3201. ASSERT_TRUE(res);
  3202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3203. }
  3204. TEST_F(ServerTest, HeadMethod200) {
  3205. auto res = cli_.Head("/hi");
  3206. ASSERT_TRUE(res);
  3207. EXPECT_EQ(StatusCode::OK_200, res->status);
  3208. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3209. EXPECT_TRUE(res->body.empty());
  3210. }
  3211. TEST_F(ServerTest, HeadMethod200Static) {
  3212. auto res = cli_.Head("/mount/dir/index.html");
  3213. ASSERT_TRUE(res);
  3214. EXPECT_EQ(StatusCode::OK_200, res->status);
  3215. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3216. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3217. EXPECT_TRUE(res->body.empty());
  3218. }
  3219. TEST_F(ServerTest, HeadMethod404) {
  3220. auto res = cli_.Head("/invalid");
  3221. ASSERT_TRUE(res);
  3222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3223. EXPECT_TRUE(res->body.empty());
  3224. }
  3225. TEST_F(ServerTest, GetMethodPersonJohn) {
  3226. auto res = cli_.Get("/person/john");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3230. EXPECT_EQ("programmer", res->body);
  3231. }
  3232. TEST_F(ServerTest, PostMethod1) {
  3233. auto res = cli_.Get("/person/john1");
  3234. ASSERT_TRUE(res);
  3235. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3236. res = cli_.Post("/person", "name=john1&note=coder",
  3237. "application/x-www-form-urlencoded");
  3238. ASSERT_TRUE(res);
  3239. ASSERT_EQ(StatusCode::OK_200, res->status);
  3240. res = cli_.Get("/person/john1");
  3241. ASSERT_TRUE(res);
  3242. ASSERT_EQ(StatusCode::OK_200, res->status);
  3243. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3244. ASSERT_EQ("coder", res->body);
  3245. }
  3246. TEST_F(ServerTest, PostMethod2) {
  3247. auto res = cli_.Get("/person/john2");
  3248. ASSERT_TRUE(res);
  3249. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3250. Params params;
  3251. params.emplace("name", "john2");
  3252. params.emplace("note", "coder");
  3253. res = cli_.Post("/person", params);
  3254. ASSERT_TRUE(res);
  3255. ASSERT_EQ(StatusCode::OK_200, res->status);
  3256. res = cli_.Get("/person/john2");
  3257. ASSERT_TRUE(res);
  3258. ASSERT_EQ(StatusCode::OK_200, res->status);
  3259. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3260. ASSERT_EQ("coder", res->body);
  3261. }
  3262. TEST_F(ServerTest, PutMethod3) {
  3263. auto res = cli_.Get("/person/john3");
  3264. ASSERT_TRUE(res);
  3265. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3266. Params params;
  3267. params.emplace("name", "john3");
  3268. params.emplace("note", "coder");
  3269. res = cli_.Put("/person", params);
  3270. ASSERT_TRUE(res);
  3271. ASSERT_EQ(StatusCode::OK_200, res->status);
  3272. res = cli_.Get("/person/john3");
  3273. ASSERT_TRUE(res);
  3274. ASSERT_EQ(StatusCode::OK_200, res->status);
  3275. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3276. ASSERT_EQ("coder", res->body);
  3277. }
  3278. TEST_F(ServerTest, DeleteMethod1) {
  3279. auto res = cli_.Get("/person/john4");
  3280. ASSERT_TRUE(res);
  3281. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3282. Params params;
  3283. params.emplace("name", "john4");
  3284. params.emplace("note", "coder");
  3285. res = cli_.Post("/person", params);
  3286. ASSERT_TRUE(res);
  3287. ASSERT_EQ(StatusCode::OK_200, res->status);
  3288. res = cli_.Get("/person/john4");
  3289. ASSERT_TRUE(res);
  3290. ASSERT_EQ(StatusCode::OK_200, res->status);
  3291. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3292. ASSERT_EQ("coder", res->body);
  3293. Params delete_params;
  3294. delete_params.emplace("name", "john4");
  3295. res = cli_.Delete("/person", delete_params);
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::OK_200, res->status);
  3298. ASSERT_EQ("DELETED", res->body);
  3299. res = cli_.Get("/person/john4");
  3300. ASSERT_TRUE(res);
  3301. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3302. }
  3303. TEST_F(ServerTest, DeleteMethod2) {
  3304. auto res = cli_.Get("/person/john5");
  3305. ASSERT_TRUE(res);
  3306. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3307. Params params;
  3308. params.emplace("name", "john5");
  3309. params.emplace("note", "developer");
  3310. res = cli_.Post("/person", params);
  3311. ASSERT_TRUE(res);
  3312. ASSERT_EQ(StatusCode::OK_200, res->status);
  3313. res = cli_.Get("/person/john5");
  3314. ASSERT_TRUE(res);
  3315. ASSERT_EQ(StatusCode::OK_200, res->status);
  3316. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3317. ASSERT_EQ("developer", res->body);
  3318. Params delete_params;
  3319. delete_params.emplace("name", "john5");
  3320. Headers headers;
  3321. headers.emplace("Custom-Header", "test-value");
  3322. res = cli_.Delete("/person", headers, delete_params);
  3323. ASSERT_TRUE(res);
  3324. ASSERT_EQ(StatusCode::OK_200, res->status);
  3325. ASSERT_EQ("DELETED", res->body);
  3326. res = cli_.Get("/person/john5");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3329. }
  3330. TEST_F(ServerTest, DeleteMethod3) {
  3331. auto res = cli_.Get("/person/john6");
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3334. Params params;
  3335. params.emplace("name", "john6");
  3336. params.emplace("note", "tester");
  3337. res = cli_.Post("/person", params);
  3338. ASSERT_TRUE(res);
  3339. ASSERT_EQ(StatusCode::OK_200, res->status);
  3340. res = cli_.Get("/person/john6");
  3341. ASSERT_TRUE(res);
  3342. ASSERT_EQ(StatusCode::OK_200, res->status);
  3343. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3344. ASSERT_EQ("tester", res->body);
  3345. Params delete_params;
  3346. delete_params.emplace("name", "john6");
  3347. Headers headers;
  3348. headers.emplace("Custom-Header", "test-value");
  3349. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3350. ASSERT_TRUE(res);
  3351. ASSERT_EQ(StatusCode::OK_200, res->status);
  3352. ASSERT_EQ("DELETED", res->body);
  3353. res = cli_.Get("/person/john6");
  3354. ASSERT_TRUE(res);
  3355. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3356. }
  3357. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3358. Params params;
  3359. params.emplace("json", JSON_DATA);
  3360. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3361. ASSERT_TRUE(res);
  3362. ASSERT_EQ(StatusCode::OK_200, res->status);
  3363. ASSERT_EQ(JSON_DATA, res->body);
  3364. }
  3365. TEST_F(ServerTest, PostEmptyContent) {
  3366. auto res = cli_.Post("/empty", "", "text/plain");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::OK_200, res->status);
  3369. ASSERT_EQ("empty", res->body);
  3370. }
  3371. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3372. auto res = cli_.Post("/empty-no-content-type");
  3373. ASSERT_TRUE(res);
  3374. ASSERT_EQ(StatusCode::OK_200, res->status);
  3375. ASSERT_EQ("empty-no-content-type", res->body);
  3376. }
  3377. TEST_F(ServerTest, PostPathOnly) {
  3378. auto res = cli_.Post("/path-only");
  3379. ASSERT_TRUE(res);
  3380. ASSERT_EQ(StatusCode::OK_200, res->status);
  3381. ASSERT_EQ("path-only", res->body);
  3382. }
  3383. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3384. auto res = cli_.Post("/path-headers-only",
  3385. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3386. ASSERT_TRUE(res);
  3387. ASSERT_EQ(StatusCode::OK_200, res->status);
  3388. ASSERT_EQ("path-headers-only", res->body);
  3389. }
  3390. TEST_F(ServerTest, PostLarge) {
  3391. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3392. ASSERT_TRUE(res);
  3393. ASSERT_EQ(StatusCode::OK_200, res->status);
  3394. EXPECT_EQ(LARGE_DATA, res->body);
  3395. }
  3396. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3397. auto res = cli_.Put("/empty-no-content-type");
  3398. ASSERT_TRUE(res);
  3399. ASSERT_EQ(StatusCode::OK_200, res->status);
  3400. ASSERT_EQ("empty-no-content-type", res->body);
  3401. }
  3402. TEST_F(ServerTest, GetMethodDir) {
  3403. auto res = cli_.Get("/dir/");
  3404. ASSERT_TRUE(res);
  3405. EXPECT_EQ(StatusCode::OK_200, res->status);
  3406. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3407. auto body = R"(<html>
  3408. <head>
  3409. </head>
  3410. <body>
  3411. <a href="/dir/test.html">Test</a>
  3412. <a href="/hi">hi</a>
  3413. </body>
  3414. </html>
  3415. )";
  3416. EXPECT_EQ(body, res->body);
  3417. }
  3418. TEST_F(ServerTest, GetMethodDirTest) {
  3419. auto res = cli_.Get("/dir/test.html");
  3420. ASSERT_TRUE(res);
  3421. EXPECT_EQ(StatusCode::OK_200, res->status);
  3422. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3423. EXPECT_EQ("test.html", res->body);
  3424. }
  3425. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3426. auto res = cli_.Get("/dir/../dir/test.html");
  3427. ASSERT_TRUE(res);
  3428. EXPECT_EQ(StatusCode::OK_200, res->status);
  3429. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3430. EXPECT_EQ("test.html", res->body);
  3431. }
  3432. TEST_F(ServerTest, GetMethodInvalidPath) {
  3433. auto res = cli_.Get("/dir/../test.html");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3436. }
  3437. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3438. auto res = cli_.Get("/../www/dir/test.html");
  3439. ASSERT_TRUE(res);
  3440. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3441. }
  3442. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3443. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3444. ASSERT_TRUE(res);
  3445. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3446. }
  3447. TEST_F(ServerTest, GetMethodDirMountTest) {
  3448. auto res = cli_.Get("/mount/dir/test.html");
  3449. ASSERT_TRUE(res);
  3450. EXPECT_EQ(StatusCode::OK_200, res->status);
  3451. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3452. EXPECT_EQ("test.html", res->body);
  3453. }
  3454. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3455. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3456. ASSERT_TRUE(res);
  3457. EXPECT_EQ(StatusCode::OK_200, res->status);
  3458. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3459. EXPECT_EQ("test.html", res->body);
  3460. }
  3461. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3462. auto res = cli_.Get("/mount/dir/../test.html");
  3463. ASSERT_TRUE(res);
  3464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3465. }
  3466. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3467. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3468. ASSERT_TRUE(res);
  3469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3470. }
  3471. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3472. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3473. ASSERT_TRUE(res);
  3474. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3475. }
  3476. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3477. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3478. ASSERT_TRUE(res);
  3479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3480. }
  3481. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3482. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3483. ASSERT_TRUE(res);
  3484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3485. }
  3486. TEST_F(ServerTest, PostMethod303) {
  3487. auto res = cli_.Post("/1", "body", "text/plain");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3490. EXPECT_EQ("/2", res->get_header_value("Location"));
  3491. }
  3492. TEST_F(ServerTest, PostMethod303Redirect) {
  3493. cli_.set_follow_location(true);
  3494. auto res = cli_.Post("/1", "body", "text/plain");
  3495. ASSERT_TRUE(res);
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ("redirected.", res->body);
  3498. EXPECT_EQ("/2", res->location);
  3499. }
  3500. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3501. auto res = cli_.Get("/dir/test.abcde");
  3502. ASSERT_TRUE(res);
  3503. EXPECT_EQ(StatusCode::OK_200, res->status);
  3504. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3505. EXPECT_EQ("abcde", res->body);
  3506. }
  3507. TEST_F(ServerTest, StaticFileRange) {
  3508. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3509. ASSERT_TRUE(res);
  3510. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3511. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3512. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3513. EXPECT_EQ(true, res->has_header("Content-Range"));
  3514. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3515. EXPECT_EQ(std::string("cd"), res->body);
  3516. }
  3517. TEST_F(ServerTest, StaticFileRanges) {
  3518. auto res =
  3519. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3520. ASSERT_TRUE(res);
  3521. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3522. EXPECT_TRUE(
  3523. res->get_header_value("Content-Type")
  3524. .find(
  3525. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3526. 0);
  3527. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3528. }
  3529. TEST_F(ServerTest, StaticFileRangeHead) {
  3530. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3531. ASSERT_TRUE(res);
  3532. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3533. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3534. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3535. EXPECT_EQ(true, res->has_header("Content-Range"));
  3536. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3537. }
  3538. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3539. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3540. ASSERT_TRUE(res);
  3541. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3543. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3544. EXPECT_EQ(true, res->has_header("Content-Range"));
  3545. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3546. res->get_header_value("Content-Range"));
  3547. EXPECT_EQ("LAST\n", res->body);
  3548. }
  3549. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3550. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3551. ASSERT_TRUE(res);
  3552. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3555. EXPECT_EQ(true, res->has_header("Content-Range"));
  3556. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3557. }
  3558. TEST_F(ServerTest, StaticFileBigFile) {
  3559. auto res = cli_.Get("/dir/1MB.txt");
  3560. ASSERT_TRUE(res);
  3561. EXPECT_EQ(StatusCode::OK_200, res->status);
  3562. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3563. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3564. }
  3565. TEST_F(ServerTest, InvalidBaseDirMount) {
  3566. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3567. }
  3568. TEST_F(ServerTest, Binary) {
  3569. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3570. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3571. "application/octet-stream");
  3572. ASSERT_TRUE(res);
  3573. ASSERT_EQ(StatusCode::OK_200, res->status);
  3574. ASSERT_EQ(4U, res->body.size());
  3575. res = cli_.Put("/binary", binary.data(), binary.size(),
  3576. "application/octet-stream");
  3577. ASSERT_TRUE(res);
  3578. ASSERT_EQ(StatusCode::OK_200, res->status);
  3579. ASSERT_EQ(4U, res->body.size());
  3580. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3581. "application/octet-stream");
  3582. ASSERT_TRUE(res);
  3583. ASSERT_EQ(StatusCode::OK_200, res->status);
  3584. ASSERT_EQ(4U, res->body.size());
  3585. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3586. "application/octet-stream");
  3587. ASSERT_TRUE(res);
  3588. ASSERT_EQ(StatusCode::OK_200, res->status);
  3589. ASSERT_EQ(4U, res->body.size());
  3590. }
  3591. TEST_F(ServerTest, BinaryString) {
  3592. auto binary = std::string("\x00\x01\x02\x03", 4);
  3593. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3594. ASSERT_TRUE(res);
  3595. ASSERT_EQ(StatusCode::OK_200, res->status);
  3596. ASSERT_EQ(4U, res->body.size());
  3597. res = cli_.Put("/binary", binary, "application/octet-stream");
  3598. ASSERT_TRUE(res);
  3599. ASSERT_EQ(StatusCode::OK_200, res->status);
  3600. ASSERT_EQ(4U, res->body.size());
  3601. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3602. ASSERT_TRUE(res);
  3603. ASSERT_EQ(StatusCode::OK_200, res->status);
  3604. ASSERT_EQ(4U, res->body.size());
  3605. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3606. ASSERT_TRUE(res);
  3607. ASSERT_EQ(StatusCode::OK_200, res->status);
  3608. ASSERT_EQ(4U, res->body.size());
  3609. }
  3610. TEST_F(ServerTest, EmptyRequest) {
  3611. auto res = cli_.Get("");
  3612. ASSERT_TRUE(!res);
  3613. EXPECT_EQ(Error::Connection, res.error());
  3614. }
  3615. TEST_F(ServerTest, LongRequest) {
  3616. std::string request;
  3617. for (size_t i = 0; i < 545; i++) {
  3618. request += "/TooLongRequest";
  3619. }
  3620. request += "OK";
  3621. auto res = cli_.Get(request.c_str());
  3622. ASSERT_TRUE(res);
  3623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3624. }
  3625. TEST_F(ServerTest, TooLongRequest) {
  3626. std::string request;
  3627. for (size_t i = 0; i < 546; i++) {
  3628. request += "/TooLongRequest";
  3629. }
  3630. request += "_NG";
  3631. auto start = std::chrono::high_resolution_clock::now();
  3632. cli_.set_keep_alive(true);
  3633. auto res = cli_.Get(request.c_str());
  3634. auto end = std::chrono::high_resolution_clock::now();
  3635. auto elapsed =
  3636. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3637. .count();
  3638. ASSERT_TRUE(res);
  3639. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3640. EXPECT_LE(elapsed, 100);
  3641. EXPECT_EQ("close", res->get_header_value("Connection"));
  3642. EXPECT_FALSE(cli_.is_socket_open());
  3643. }
  3644. TEST_F(ServerTest, AlmostTooLongRequest) {
  3645. // test for #2046 - URI length check shouldn't include other content on req
  3646. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3647. // leading /, space, HTTP/1.1)
  3648. std::string request =
  3649. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3650. auto res = cli_.Get(request.c_str());
  3651. ASSERT_TRUE(res);
  3652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3653. }
  3654. TEST_F(ServerTest, LongHeader) {
  3655. Request req;
  3656. req.method = "GET";
  3657. req.path = "/hi";
  3658. std::string host_and_port;
  3659. host_and_port += HOST;
  3660. host_and_port += ":";
  3661. host_and_port += std::to_string(PORT);
  3662. req.headers.emplace("Host", host_and_port.c_str());
  3663. req.headers.emplace("Accept", "*/*");
  3664. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3665. req.headers.emplace(
  3666. "Header-Name",
  3667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3695. "@@@@@@@@@@@@@@@@");
  3696. auto res = std::make_shared<Response>();
  3697. auto error = Error::Success;
  3698. auto ret = cli_.send(req, *res, error);
  3699. ASSERT_TRUE(ret);
  3700. EXPECT_EQ(StatusCode::OK_200, res->status);
  3701. }
  3702. TEST_F(ServerTest, LongQueryValue) {
  3703. auto start = std::chrono::high_resolution_clock::now();
  3704. cli_.set_keep_alive(true);
  3705. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3706. auto end = std::chrono::high_resolution_clock::now();
  3707. auto elapsed =
  3708. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3709. .count();
  3710. ASSERT_TRUE(res);
  3711. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3712. EXPECT_LE(elapsed, 100);
  3713. EXPECT_EQ("close", res->get_header_value("Connection"));
  3714. EXPECT_FALSE(cli_.is_socket_open());
  3715. }
  3716. TEST_F(ServerTest, TooLongQueryValue) {
  3717. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3718. ASSERT_FALSE(res);
  3719. EXPECT_EQ(Error::Read, res.error());
  3720. }
  3721. TEST_F(ServerTest, TooLongHeader) {
  3722. Request req;
  3723. req.method = "GET";
  3724. req.path = "/hi";
  3725. std::string host_and_port;
  3726. host_and_port += HOST;
  3727. host_and_port += ":";
  3728. host_and_port += std::to_string(PORT);
  3729. req.headers.emplace("Host", host_and_port.c_str());
  3730. req.headers.emplace("Accept", "*/*");
  3731. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3732. req.headers.emplace(
  3733. "Header-Name",
  3734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3762. "@@@@@@@@@@@@@@@@@");
  3763. auto res = std::make_shared<Response>();
  3764. auto error = Error::Success;
  3765. auto ret = cli_.send(req, *res, error);
  3766. ASSERT_TRUE(ret);
  3767. EXPECT_EQ(StatusCode::OK_200, res->status);
  3768. }
  3769. TEST_F(ServerTest, HeaderCountAtLimit) {
  3770. // Test with headers just under the 100 limit
  3771. httplib::Headers headers;
  3772. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3773. // This should keep us just under the 100 header limit
  3774. for (int i = 0; i < 95; i++) {
  3775. std::string name = "X-Test-Header-" + std::to_string(i);
  3776. std::string value = "value" + std::to_string(i);
  3777. headers.emplace(name, value);
  3778. }
  3779. // This should work fine as we're under the limit
  3780. auto res = cli_.Get("/hi", headers);
  3781. EXPECT_TRUE(res);
  3782. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3783. }
  3784. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3785. // Test with many headers to exceed the 100 limit
  3786. httplib::Headers headers;
  3787. // Add 150 headers to definitely exceed the 100 limit
  3788. for (int i = 0; i < 150; i++) {
  3789. std::string name = "X-Test-Header-" + std::to_string(i);
  3790. std::string value = "value" + std::to_string(i);
  3791. headers.emplace(name, value);
  3792. }
  3793. // This should fail due to exceeding header count limit
  3794. cli_.set_keep_alive(true);
  3795. auto res = cli_.Get("/hi", headers);
  3796. // The request should either fail or return 400 Bad Request
  3797. if (res) {
  3798. // If we get a response, it should be 400 Bad Request
  3799. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3800. } else {
  3801. // Or the request should fail entirely
  3802. EXPECT_FALSE(res);
  3803. }
  3804. EXPECT_EQ("close", res->get_header_value("Connection"));
  3805. EXPECT_FALSE(cli_.is_socket_open());
  3806. }
  3807. TEST_F(ServerTest, PercentEncoding) {
  3808. auto res = cli_.Get("/e%6edwith%");
  3809. ASSERT_TRUE(res);
  3810. EXPECT_EQ(StatusCode::OK_200, res->status);
  3811. }
  3812. TEST_F(ServerTest, PercentEncodingUnicode) {
  3813. auto res = cli_.Get("/e%u006edwith%");
  3814. ASSERT_TRUE(res);
  3815. EXPECT_EQ(StatusCode::OK_200, res->status);
  3816. }
  3817. TEST_F(ServerTest, InvalidPercentEncoding) {
  3818. auto res = cli_.Get("/%endwith%");
  3819. ASSERT_TRUE(res);
  3820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3821. }
  3822. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3823. auto res = cli_.Get("/%uendwith%");
  3824. ASSERT_TRUE(res);
  3825. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3826. }
  3827. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3828. auto res = cli_.Get("/hello?aaa=bbb%");
  3829. ASSERT_TRUE(res);
  3830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3831. }
  3832. TEST_F(ServerTest, PlusSignEncoding) {
  3833. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3834. ASSERT_TRUE(res);
  3835. EXPECT_EQ(StatusCode::OK_200, res->status);
  3836. EXPECT_EQ("a +b", res->body);
  3837. }
  3838. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3839. // This test simulates a potential DoS attack using many headers
  3840. // to verify our security fix prevents memory exhaustion
  3841. httplib::Headers attack_headers;
  3842. // Attempt to add many headers like an attacker would (200 headers to far
  3843. // exceed limit)
  3844. for (int i = 0; i < 200; i++) {
  3845. std::string name = "X-Attack-Header-" + std::to_string(i);
  3846. std::string value = "attack_payload_" + std::to_string(i);
  3847. attack_headers.emplace(name, value);
  3848. }
  3849. // Try to POST with excessive headers
  3850. cli_.set_keep_alive(true);
  3851. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3852. // Should either fail or return 400 Bad Request due to security limit
  3853. if (res) {
  3854. // If we get a response, it should be 400 Bad Request
  3855. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3856. } else {
  3857. // Request failed, which is the expected behavior for DoS protection
  3858. EXPECT_FALSE(res);
  3859. }
  3860. EXPECT_EQ("close", res->get_header_value("Connection"));
  3861. EXPECT_FALSE(cli_.is_socket_open());
  3862. }
  3863. TEST_F(ServerTest, MultipartFormData) {
  3864. UploadFormDataItems items = {
  3865. {"text1", "text default", "", ""},
  3866. {"text2", "aωb", "", ""},
  3867. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3868. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3869. {"file3", "", "", "application/octet-stream"},
  3870. {"file4", "", "", " application/json tmp-string "}};
  3871. auto res = cli_.Post("/multipart", items);
  3872. ASSERT_TRUE(res);
  3873. EXPECT_EQ(StatusCode::OK_200, res->status);
  3874. }
  3875. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3876. UploadFormDataItems items = {
  3877. {"text", "default text", "", ""},
  3878. {"multi_text1", "aaaaa", "", ""},
  3879. {"multi_text1", "bbbbb", "", ""},
  3880. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3881. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3882. "application/json"},
  3883. };
  3884. auto res = cli_.Post("/multipart/multi_file_values", items);
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::OK_200, res->status);
  3887. }
  3888. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3889. auto res = cli_.Get("/hi");
  3890. ASSERT_TRUE(res);
  3891. EXPECT_EQ(StatusCode::OK_200, res->status);
  3892. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3893. EXPECT_EQ("Hello World!", res->body);
  3894. }
  3895. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3896. Request req;
  3897. req.method = "POST";
  3898. req.path = "/chunked";
  3899. std::string host_and_port;
  3900. host_and_port += HOST;
  3901. host_and_port += ":";
  3902. host_and_port += std::to_string(PORT);
  3903. req.headers.emplace("Host", host_and_port.c_str());
  3904. req.headers.emplace("Accept", "*/*");
  3905. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3906. req.headers.emplace("Content-Type", "text/plain");
  3907. req.headers.emplace("Content-Length", "0");
  3908. req.headers.emplace(
  3909. "Transfer-Encoding",
  3910. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3911. // Client does not chunk, so make a chunked body manually.
  3912. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3913. auto res = std::make_shared<Response>();
  3914. auto error = Error::Success;
  3915. auto ret = cli_.send(req, *res, error);
  3916. ASSERT_TRUE(ret);
  3917. EXPECT_EQ(StatusCode::OK_200, res->status);
  3918. }
  3919. TEST_F(ServerTest, GetStreamed2) {
  3920. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3923. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3924. EXPECT_EQ(true, res->has_header("Content-Range"));
  3925. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3926. EXPECT_EQ(std::string("ab"), res->body);
  3927. }
  3928. TEST_F(ServerTest, GetStreamed) {
  3929. auto res = cli_.Get("/streamed");
  3930. ASSERT_TRUE(res);
  3931. EXPECT_EQ(StatusCode::OK_200, res->status);
  3932. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3933. EXPECT_EQ(std::string("aaabbb"), res->body);
  3934. }
  3935. TEST_F(ServerTest, GetStreamedWithRange1) {
  3936. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3937. ASSERT_TRUE(res);
  3938. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3939. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3940. EXPECT_EQ(true, res->has_header("Content-Range"));
  3941. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3942. EXPECT_EQ(std::string("def"), res->body);
  3943. }
  3944. TEST_F(ServerTest, GetStreamedWithRange2) {
  3945. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3946. ASSERT_TRUE(res);
  3947. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3948. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3949. EXPECT_EQ(true, res->has_header("Content-Range"));
  3950. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3951. EXPECT_EQ(std::string("bcdefg"), res->body);
  3952. }
  3953. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3954. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3955. ASSERT_TRUE(res);
  3956. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3957. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3958. EXPECT_EQ(true, res->has_header("Content-Range"));
  3959. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3960. EXPECT_EQ(std::string("efg"), res->body);
  3961. }
  3962. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3963. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3964. ASSERT_TRUE(res);
  3965. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3966. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3967. EXPECT_EQ(false, res->has_header("Content-Range"));
  3968. EXPECT_EQ(0U, res->body.size());
  3969. }
  3970. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3971. auto res = cli_.Get("/streamed-with-range",
  3972. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3973. "92233720368547758079223372036854775807"}});
  3974. ASSERT_TRUE(res);
  3975. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3976. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3977. EXPECT_EQ(false, res->has_header("Content-Range"));
  3978. EXPECT_EQ(0U, res->body.size());
  3979. }
  3980. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3981. auto res = cli_.Get(
  3982. "/with-range",
  3983. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3984. {"Accept-Encoding", ""}});
  3985. ASSERT_TRUE(res);
  3986. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3987. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3988. EXPECT_EQ(true, res->has_header("Content-Range"));
  3989. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3990. EXPECT_EQ(std::string("abcdefg"), res->body);
  3991. }
  3992. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3993. auto res = cli_.Get("/with-range", {
  3994. {"Range", "bytes=0-"},
  3995. {"Accept-Encoding", ""},
  3996. });
  3997. ASSERT_TRUE(res);
  3998. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3999. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4000. EXPECT_EQ(true, res->has_header("Content-Range"));
  4001. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4002. EXPECT_EQ(std::string("abcdefg"), res->body);
  4003. }
  4004. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4005. auto res =
  4006. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4007. ASSERT_TRUE(res);
  4008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4009. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4010. EXPECT_EQ(false, res->has_header("Content-Range"));
  4011. EXPECT_EQ(267U, res->body.size());
  4012. // Check that both range contents are present
  4013. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4014. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4015. // Check that Content-Range headers are present for both ranges
  4016. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4017. std::string::npos);
  4018. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4019. std::string::npos);
  4020. }
  4021. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4022. Ranges ranges;
  4023. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4024. ranges.emplace_back(0, -1);
  4025. }
  4026. auto res =
  4027. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4030. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4031. EXPECT_EQ(false, res->has_header("Content-Range"));
  4032. EXPECT_EQ(0U, res->body.size());
  4033. }
  4034. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4035. auto res =
  4036. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4037. ASSERT_TRUE(res);
  4038. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4039. EXPECT_EQ(5U, res->body.size());
  4040. // Check that overlapping ranges are coalesced into a single range
  4041. EXPECT_EQ("bcdef", res->body);
  4042. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4043. // Should be single range, not multipart
  4044. EXPECT_TRUE(res->has_header("Content-Range"));
  4045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4046. }
  4047. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4048. auto res =
  4049. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4050. ASSERT_TRUE(res);
  4051. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4052. EXPECT_EQ(268U, res->body.size());
  4053. // Check that both range contents are present
  4054. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4055. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4056. // Check that Content-Range headers are present for both ranges
  4057. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4058. std::string::npos);
  4059. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4060. std::string::npos);
  4061. }
  4062. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4063. auto res =
  4064. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4065. ASSERT_TRUE(res);
  4066. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4067. EXPECT_EQ(269U, res->body.size());
  4068. // Check that both duplicate range contents are present
  4069. size_t first_abc = res->body.find("abc\r\n");
  4070. EXPECT_TRUE(first_abc != std::string::npos);
  4071. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4072. EXPECT_TRUE(second_abc != std::string::npos);
  4073. // Check that Content-Range headers are present for both ranges
  4074. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4075. EXPECT_TRUE(first_range != std::string::npos);
  4076. size_t second_range =
  4077. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4078. EXPECT_TRUE(second_range != std::string::npos);
  4079. }
  4080. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4081. auto res = cli_.Get("/streamed-with-range?error",
  4082. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4083. ASSERT_TRUE(res);
  4084. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4085. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4086. EXPECT_EQ(false, res->has_header("Content-Range"));
  4087. EXPECT_EQ(0U, res->body.size());
  4088. }
  4089. TEST_F(ServerTest, GetStreamedEndless) {
  4090. uint64_t offset = 0;
  4091. auto res = cli_.Get("/streamed-cancel",
  4092. [&](const char * /*data*/, uint64_t data_length) {
  4093. if (offset < 100) {
  4094. offset += data_length;
  4095. return true;
  4096. }
  4097. return false;
  4098. });
  4099. ASSERT_TRUE(!res);
  4100. EXPECT_EQ(Error::Canceled, res.error());
  4101. }
  4102. TEST_F(ServerTest, ClientStop) {
  4103. std::atomic_size_t count{4};
  4104. std::vector<std::thread> threads;
  4105. for (auto i = count.load(); i != 0; --i) {
  4106. threads.emplace_back([&]() {
  4107. auto res = cli_.Get("/streamed-cancel",
  4108. [&](const char *, uint64_t) { return true; });
  4109. --count;
  4110. ASSERT_TRUE(!res);
  4111. EXPECT_TRUE(res.error() == Error::Canceled ||
  4112. res.error() == Error::Read || res.error() == Error::Write);
  4113. });
  4114. }
  4115. std::this_thread::sleep_for(std::chrono::seconds(2));
  4116. while (count != 0) {
  4117. cli_.stop();
  4118. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4119. }
  4120. for (auto &t : threads) {
  4121. t.join();
  4122. }
  4123. }
  4124. TEST_F(ServerTest, GetWithRange1) {
  4125. auto res = cli_.Get("/with-range", {
  4126. make_range_header({{3, 5}}),
  4127. {"Accept-Encoding", ""},
  4128. });
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4131. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4132. EXPECT_EQ(true, res->has_header("Content-Range"));
  4133. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4134. EXPECT_EQ(std::string("def"), res->body);
  4135. }
  4136. TEST_F(ServerTest, GetWithRange2) {
  4137. auto res = cli_.Get("/with-range", {
  4138. make_range_header({{1, -1}}),
  4139. {"Accept-Encoding", ""},
  4140. });
  4141. ASSERT_TRUE(res);
  4142. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4143. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4144. EXPECT_EQ(true, res->has_header("Content-Range"));
  4145. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4146. EXPECT_EQ(std::string("bcdefg"), res->body);
  4147. }
  4148. TEST_F(ServerTest, GetWithRange3) {
  4149. auto res = cli_.Get("/with-range", {
  4150. make_range_header({{0, 0}}),
  4151. {"Accept-Encoding", ""},
  4152. });
  4153. ASSERT_TRUE(res);
  4154. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4155. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4156. EXPECT_EQ(true, res->has_header("Content-Range"));
  4157. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4158. EXPECT_EQ(std::string("a"), res->body);
  4159. }
  4160. TEST_F(ServerTest, GetWithRange4) {
  4161. auto res = cli_.Get("/with-range", {
  4162. make_range_header({{-1, 2}}),
  4163. {"Accept-Encoding", ""},
  4164. });
  4165. ASSERT_TRUE(res);
  4166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4167. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4168. EXPECT_EQ(true, res->has_header("Content-Range"));
  4169. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4170. EXPECT_EQ(std::string("fg"), res->body);
  4171. }
  4172. TEST_F(ServerTest, GetWithRange5) {
  4173. auto res = cli_.Get("/with-range", {
  4174. make_range_header({{0, 5}}),
  4175. {"Accept-Encoding", ""},
  4176. });
  4177. ASSERT_TRUE(res);
  4178. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4179. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4180. EXPECT_EQ(true, res->has_header("Content-Range"));
  4181. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4182. EXPECT_EQ(std::string("abcdef"), res->body);
  4183. }
  4184. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4185. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4186. ASSERT_TRUE(res);
  4187. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4188. }
  4189. TEST_F(ServerTest, GetWithRangeMultipart) {
  4190. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4193. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4194. EXPECT_EQ(false, res->has_header("Content-Range"));
  4195. EXPECT_EQ(267U, res->body.size());
  4196. }
  4197. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4198. auto res =
  4199. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4200. ASSERT_TRUE(res);
  4201. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4202. }
  4203. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4204. auto res = cli_.Get("/with-range-customized-response",
  4205. {{make_range_header({{1, 2}})}});
  4206. ASSERT_TRUE(res);
  4207. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4208. EXPECT_EQ(true, res->has_header("Content-Length"));
  4209. EXPECT_EQ(false, res->has_header("Content-Range"));
  4210. EXPECT_EQ(JSON_DATA, res->body);
  4211. }
  4212. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4213. auto res = cli_.Get("/with-range-customized-response",
  4214. {{make_range_header({{1, 2}, {4, 5}})}});
  4215. ASSERT_TRUE(res);
  4216. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4217. EXPECT_EQ(true, res->has_header("Content-Length"));
  4218. EXPECT_EQ(false, res->has_header("Content-Range"));
  4219. EXPECT_EQ(JSON_DATA, res->body);
  4220. }
  4221. TEST_F(ServerTest, Issue1772) {
  4222. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4225. }
  4226. TEST_F(ServerTest, Issue609) {
  4227. auto res = cli_.Delete("/issue609");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. EXPECT_EQ(std::string("ok"), res->body);
  4231. }
  4232. TEST_F(ServerTest, GetStreamedChunked) {
  4233. auto res = cli_.Get("/streamed-chunked");
  4234. ASSERT_TRUE(res);
  4235. EXPECT_EQ(StatusCode::OK_200, res->status);
  4236. EXPECT_EQ(std::string("123456789"), res->body);
  4237. }
  4238. TEST_F(ServerTest, GetStreamedChunked2) {
  4239. auto res = cli_.Get("/streamed-chunked2");
  4240. ASSERT_TRUE(res);
  4241. EXPECT_EQ(StatusCode::OK_200, res->status);
  4242. EXPECT_EQ(std::string("123456789"), res->body);
  4243. }
  4244. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4245. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4246. ASSERT_TRUE(res);
  4247. EXPECT_EQ(StatusCode::OK_200, res->status);
  4248. EXPECT_EQ(std::string("123456789"), res->body);
  4249. EXPECT_TRUE(res->has_header("Trailer"));
  4250. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4251. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4252. // Trailers are now stored separately from headers (security fix)
  4253. EXPECT_EQ(2U, res->trailers.size());
  4254. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4255. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4256. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4257. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4258. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4259. // Verify trailers are NOT in headers (security verification)
  4260. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4261. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4262. }
  4263. TEST_F(ServerTest, LargeChunkedPost) {
  4264. Request req;
  4265. req.method = "POST";
  4266. req.path = "/large-chunked";
  4267. std::string host_and_port;
  4268. host_and_port += HOST;
  4269. host_and_port += ":";
  4270. host_and_port += std::to_string(PORT);
  4271. req.headers.emplace("Host", host_and_port.c_str());
  4272. req.headers.emplace("Accept", "*/*");
  4273. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4274. req.headers.emplace("Content-Type", "text/plain");
  4275. req.headers.emplace("Content-Length", "0");
  4276. req.headers.emplace("Transfer-Encoding", "chunked");
  4277. std::string long_string(30 * 1024u, 'a');
  4278. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4279. // Attempt to make a large enough post to exceed OS buffers, to test that
  4280. // the server handles short reads if the full chunk data isn't available.
  4281. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4282. auto res = std::make_shared<Response>();
  4283. auto error = Error::Success;
  4284. auto ret = cli_.send(req, *res, error);
  4285. ASSERT_TRUE(ret);
  4286. EXPECT_EQ(StatusCode::OK_200, res->status);
  4287. }
  4288. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4289. auto res = cli_.Get("/remote_addr");
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ(StatusCode::OK_200, res->status);
  4292. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4293. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4294. }
  4295. TEST_F(ServerTest, GetMethodLocalAddr) {
  4296. auto res = cli_.Get("/local_addr");
  4297. ASSERT_TRUE(res);
  4298. EXPECT_EQ(StatusCode::OK_200, res->status);
  4299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4300. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4301. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4302. }
  4303. TEST_F(ServerTest, HTTPResponseSplitting) {
  4304. auto res = cli_.Get("/http_response_splitting");
  4305. ASSERT_TRUE(res);
  4306. EXPECT_EQ(StatusCode::OK_200, res->status);
  4307. }
  4308. TEST_F(ServerTest, SlowRequest) {
  4309. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4310. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4311. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4312. }
  4313. #if 0
  4314. TEST_F(ServerTest, SlowPost) {
  4315. char buffer[64 * 1024];
  4316. memset(buffer, 0x42, sizeof(buffer));
  4317. auto res = cli_.Post(
  4318. "/slowpost", 64 * 1024 * 1024,
  4319. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4320. auto ret = sink.write(buffer, sizeof(buffer));
  4321. EXPECT_TRUE(ret);
  4322. return true;
  4323. },
  4324. "text/plain");
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. }
  4328. TEST_F(ServerTest, SlowPostFail) {
  4329. char buffer[64 * 1024];
  4330. memset(buffer, 0x42, sizeof(buffer));
  4331. cli_.set_write_timeout(std::chrono::seconds(0));
  4332. auto res = cli_.Post(
  4333. "/slowpost", 64 * 1024 * 1024,
  4334. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4335. sink.write(buffer, sizeof(buffer));
  4336. return true;
  4337. },
  4338. "text/plain");
  4339. ASSERT_TRUE(!res);
  4340. EXPECT_EQ(Error::Write, res.error());
  4341. }
  4342. #endif
  4343. TEST_F(ServerTest, Put) {
  4344. auto res = cli_.Put("/put", "PUT", "text/plain");
  4345. ASSERT_TRUE(res);
  4346. EXPECT_EQ(StatusCode::OK_200, res->status);
  4347. EXPECT_EQ("PUT", res->body);
  4348. }
  4349. TEST_F(ServerTest, PutWithContentProvider) {
  4350. auto res = cli_.Put(
  4351. "/put", 3,
  4352. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4353. sink.os << "PUT";
  4354. return true;
  4355. },
  4356. "text/plain");
  4357. ASSERT_TRUE(res);
  4358. EXPECT_EQ(StatusCode::OK_200, res->status);
  4359. EXPECT_EQ("PUT", res->body);
  4360. }
  4361. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4362. auto res = cli_.Post(
  4363. "/post", 42,
  4364. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4365. return false;
  4366. },
  4367. "text/plain");
  4368. ASSERT_TRUE(!res);
  4369. EXPECT_EQ(Error::Canceled, res.error());
  4370. }
  4371. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4372. auto res = cli_.Put(
  4373. "/put",
  4374. [](size_t /*offset*/, DataSink &sink) {
  4375. sink.os << "PUT";
  4376. sink.done();
  4377. return true;
  4378. },
  4379. "text/plain");
  4380. ASSERT_TRUE(res);
  4381. EXPECT_EQ(StatusCode::OK_200, res->status);
  4382. EXPECT_EQ("PUT", res->body);
  4383. }
  4384. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4385. auto res = cli_.Post(
  4386. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4387. "text/plain");
  4388. ASSERT_TRUE(!res);
  4389. EXPECT_EQ(Error::Canceled, res.error());
  4390. }
  4391. TEST_F(ServerTest, PostLoopBack) {
  4392. std::string body;
  4393. auto res = cli_.Post(
  4394. "/post-loopback", 9,
  4395. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4396. EXPECT_EQ(9u, length);
  4397. sink.write("123", 3);
  4398. sink.write("456", 3);
  4399. sink.write("789", 3);
  4400. return true;
  4401. },
  4402. "text/plain",
  4403. [&body](const char *data, size_t data_length) {
  4404. body.append(data, data_length);
  4405. return true;
  4406. });
  4407. ASSERT_TRUE(res);
  4408. EXPECT_EQ(StatusCode::OK_200, res->status);
  4409. EXPECT_EQ("123456789", body);
  4410. }
  4411. TEST_F(ServerTest, PutLoopBack) {
  4412. std::string body;
  4413. auto res = cli_.Put(
  4414. "/put-loopback", 9,
  4415. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4416. EXPECT_EQ(9u, length);
  4417. sink.write("123", 3);
  4418. sink.write("456", 3);
  4419. sink.write("789", 3);
  4420. return true;
  4421. },
  4422. "text/plain",
  4423. [&body](const char *data, size_t data_length) {
  4424. body.append(data, data_length);
  4425. return true;
  4426. });
  4427. ASSERT_TRUE(res);
  4428. EXPECT_EQ(StatusCode::OK_200, res->status);
  4429. EXPECT_EQ("123456789", body);
  4430. }
  4431. TEST_F(ServerTest, PatchLoopBack) {
  4432. std::string body;
  4433. auto res = cli_.Patch(
  4434. "/patch-loopback", 9,
  4435. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4436. EXPECT_EQ(9u, length);
  4437. sink.write("123", 3);
  4438. sink.write("456", 3);
  4439. sink.write("789", 3);
  4440. return true;
  4441. },
  4442. "text/plain",
  4443. [&body](const char *data, size_t data_length) {
  4444. body.append(data, data_length);
  4445. return true;
  4446. });
  4447. ASSERT_TRUE(res);
  4448. EXPECT_EQ(StatusCode::OK_200, res->status);
  4449. EXPECT_EQ("123456789", body);
  4450. }
  4451. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4452. std::string body;
  4453. auto res = cli_.Post(
  4454. "/post-loopback",
  4455. [](size_t /*offset*/, DataSink &sink) {
  4456. sink.write("123", 3);
  4457. sink.write("456", 3);
  4458. sink.write("789", 3);
  4459. sink.done();
  4460. return true;
  4461. },
  4462. "text/plain",
  4463. [&body](const char *data, size_t data_length) {
  4464. body.append(data, data_length);
  4465. return true;
  4466. });
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::OK_200, res->status);
  4469. EXPECT_EQ("123456789", body);
  4470. }
  4471. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4472. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4473. cli_.set_compress(true);
  4474. auto res = cli_.Put(
  4475. "/put", 3,
  4476. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4477. sink.os << "PUT";
  4478. return true;
  4479. },
  4480. "text/plain");
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::OK_200, res->status);
  4483. EXPECT_EQ("PUT", res->body);
  4484. }
  4485. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4486. cli_.set_compress(true);
  4487. auto res = cli_.Post(
  4488. "/post", 42,
  4489. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4490. return false;
  4491. },
  4492. "text/plain");
  4493. ASSERT_TRUE(!res);
  4494. EXPECT_EQ(Error::Canceled, res.error());
  4495. }
  4496. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4497. cli_.set_compress(true);
  4498. auto res = cli_.Put(
  4499. "/put",
  4500. [](size_t /*offset*/, DataSink &sink) {
  4501. sink.os << "PUT";
  4502. sink.done();
  4503. return true;
  4504. },
  4505. "text/plain");
  4506. ASSERT_TRUE(res);
  4507. EXPECT_EQ(StatusCode::OK_200, res->status);
  4508. EXPECT_EQ("PUT", res->body);
  4509. }
  4510. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4511. cli_.set_compress(true);
  4512. auto res = cli_.Post(
  4513. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4514. "text/plain");
  4515. ASSERT_TRUE(!res);
  4516. EXPECT_EQ(Error::Canceled, res.error());
  4517. }
  4518. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4519. cli_.set_compress(true);
  4520. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ(LARGE_DATA, res->body);
  4524. }
  4525. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4527. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4528. Client cli(s.c_str());
  4529. cli.enable_server_certificate_verification(false);
  4530. #else
  4531. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4532. Client cli(s.c_str());
  4533. #endif
  4534. cli.set_compress(true);
  4535. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ(StatusCode::OK_200, res->status);
  4538. EXPECT_EQ(LARGE_DATA, res->body);
  4539. // The compressed size should be less than a 10th of the original. May vary
  4540. // depending on the zlib library.
  4541. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4542. static_cast<uint64_t>(10 * 1024 * 1024));
  4543. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4544. }
  4545. TEST_F(ServerTest, PutContentWithDeflate) {
  4546. cli_.set_compress(false);
  4547. Headers headers;
  4548. headers.emplace("Content-Encoding", "deflate");
  4549. // PUT in deflate format:
  4550. auto res = cli_.Put("/put", headers,
  4551. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4552. ASSERT_TRUE(res);
  4553. EXPECT_EQ(StatusCode::OK_200, res->status);
  4554. EXPECT_EQ("PUT", res->body);
  4555. }
  4556. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4557. Headers headers;
  4558. headers.emplace("Accept-Encoding", "gzip, deflate");
  4559. auto res = cli_.Get("/streamed-chunked", headers);
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ(std::string("123456789"), res->body);
  4563. }
  4564. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4565. Headers headers;
  4566. headers.emplace("Accept-Encoding", "gzip, deflate");
  4567. auto res = cli_.Get("/streamed-chunked2", headers);
  4568. ASSERT_TRUE(res);
  4569. EXPECT_EQ(StatusCode::OK_200, res->status);
  4570. EXPECT_EQ(std::string("123456789"), res->body);
  4571. }
  4572. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4573. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4574. ASSERT_TRUE(res);
  4575. EXPECT_EQ(StatusCode::OK_200, res->status);
  4576. }
  4577. TEST(GzipDecompressor, ChunkedDecompression) {
  4578. std::string data;
  4579. for (size_t i = 0; i < 32 * 1024; ++i) {
  4580. data.push_back(static_cast<char>('a' + i % 26));
  4581. }
  4582. std::string compressed_data;
  4583. {
  4584. httplib::detail::gzip_compressor compressor;
  4585. bool result = compressor.compress(
  4586. data.data(), data.size(),
  4587. /*last=*/true,
  4588. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4589. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4590. compressed_data_size);
  4591. return true;
  4592. });
  4593. ASSERT_TRUE(result);
  4594. }
  4595. std::string decompressed_data;
  4596. {
  4597. httplib::detail::gzip_decompressor decompressor;
  4598. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4599. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4600. size_t chunk_size = 130;
  4601. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4602. chunk_begin += chunk_size) {
  4603. size_t current_chunk_size =
  4604. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4605. bool result = decompressor.decompress(
  4606. compressed_data.data() + chunk_begin, current_chunk_size,
  4607. [&](const char *decompressed_data_chunk,
  4608. size_t decompressed_data_chunk_size) {
  4609. decompressed_data.insert(decompressed_data.size(),
  4610. decompressed_data_chunk,
  4611. decompressed_data_chunk_size);
  4612. return true;
  4613. });
  4614. ASSERT_TRUE(result);
  4615. }
  4616. }
  4617. ASSERT_EQ(data, decompressed_data);
  4618. }
  4619. TEST(GzipDecompressor, DeflateDecompression) {
  4620. std::string original_text = "Raw deflate without gzip";
  4621. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4622. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4623. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4624. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4625. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4626. std::string decompressed_data;
  4627. {
  4628. httplib::detail::gzip_decompressor decompressor;
  4629. bool result = decompressor.decompress(
  4630. compressed_data.data(), compressed_data.size(),
  4631. [&](const char *decompressed_data_chunk,
  4632. size_t decompressed_data_chunk_size) {
  4633. decompressed_data.insert(decompressed_data.size(),
  4634. decompressed_data_chunk,
  4635. decompressed_data_chunk_size);
  4636. return true;
  4637. });
  4638. ASSERT_TRUE(result);
  4639. }
  4640. ASSERT_EQ(original_text, decompressed_data);
  4641. }
  4642. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4643. std::string original_text = "Raw deflate without gzip";
  4644. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4645. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4646. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4647. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4648. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4649. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4650. std::string decompressed_data;
  4651. {
  4652. httplib::detail::gzip_decompressor decompressor;
  4653. bool result = decompressor.decompress(
  4654. compressed_data.data(), compressed_data.size(),
  4655. [&](const char *decompressed_data_chunk,
  4656. size_t decompressed_data_chunk_size) {
  4657. decompressed_data.insert(decompressed_data.size(),
  4658. decompressed_data_chunk,
  4659. decompressed_data_chunk_size);
  4660. return true;
  4661. });
  4662. ASSERT_TRUE(result);
  4663. }
  4664. ASSERT_EQ(original_text, decompressed_data);
  4665. }
  4666. #ifdef _WIN32
  4667. TEST(GzipDecompressor, LargeRandomData) {
  4668. // prepare large random data that is difficult to be compressed and is
  4669. // expected to have large size even when compressed
  4670. std::random_device seed_gen;
  4671. std::mt19937 random(seed_gen());
  4672. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4673. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4674. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4675. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4676. // compress data over 4GiB
  4677. std::string compressed_data;
  4678. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4679. httplib::detail::gzip_compressor compressor;
  4680. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4681. data.size() * sizeof(std::uint32_t), true,
  4682. [&](const char *data, size_t size) {
  4683. compressed_data.insert(
  4684. compressed_data.size(), data, size);
  4685. return true;
  4686. });
  4687. ASSERT_TRUE(result);
  4688. // FIXME: compressed data size is expected to be greater than 4GiB,
  4689. // but there is no guarantee
  4690. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4691. // decompress data over 4GiB
  4692. std::string decompressed_data;
  4693. decompressed_data.reserve(data_size);
  4694. httplib::detail::gzip_decompressor decompressor;
  4695. result = decompressor.decompress(
  4696. compressed_data.data(), compressed_data.size(),
  4697. [&](const char *data, size_t size) {
  4698. decompressed_data.insert(decompressed_data.size(), data, size);
  4699. return true;
  4700. });
  4701. ASSERT_TRUE(result);
  4702. // compare
  4703. ASSERT_EQ(data_size, decompressed_data.size());
  4704. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4705. 0);
  4706. }
  4707. #endif
  4708. #endif
  4709. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4710. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4711. Headers headers;
  4712. headers.emplace("Accept-Encoding", "br");
  4713. auto res = cli_.Get("/streamed-chunked", headers);
  4714. ASSERT_TRUE(res);
  4715. EXPECT_EQ(StatusCode::OK_200, res->status);
  4716. EXPECT_EQ(std::string("123456789"), res->body);
  4717. }
  4718. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4719. Headers headers;
  4720. headers.emplace("Accept-Encoding", "br");
  4721. auto res = cli_.Get("/streamed-chunked2", headers);
  4722. ASSERT_TRUE(res);
  4723. EXPECT_EQ(StatusCode::OK_200, res->status);
  4724. EXPECT_EQ(std::string("123456789"), res->body);
  4725. }
  4726. #endif
  4727. TEST_F(ServerTest, Patch) {
  4728. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4729. ASSERT_TRUE(res);
  4730. EXPECT_EQ(StatusCode::OK_200, res->status);
  4731. EXPECT_EQ("PATCH", res->body);
  4732. }
  4733. TEST_F(ServerTest, Delete) {
  4734. auto res = cli_.Delete("/delete");
  4735. ASSERT_TRUE(res);
  4736. EXPECT_EQ(StatusCode::OK_200, res->status);
  4737. EXPECT_EQ("DELETE", res->body);
  4738. }
  4739. TEST_F(ServerTest, DeleteContentReceiver) {
  4740. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4741. ASSERT_TRUE(res);
  4742. EXPECT_EQ(StatusCode::OK_200, res->status);
  4743. EXPECT_EQ("content", res->body);
  4744. }
  4745. TEST_F(ServerTest, Options) {
  4746. auto res = cli_.Options("*");
  4747. ASSERT_TRUE(res);
  4748. EXPECT_EQ(StatusCode::OK_200, res->status);
  4749. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4750. EXPECT_TRUE(res->body.empty());
  4751. }
  4752. TEST_F(ServerTest, URL) {
  4753. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4754. ASSERT_TRUE(res);
  4755. EXPECT_EQ(StatusCode::OK_200, res->status);
  4756. }
  4757. TEST_F(ServerTest, ArrayParam) {
  4758. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4759. ASSERT_TRUE(res);
  4760. EXPECT_EQ(StatusCode::OK_200, res->status);
  4761. }
  4762. TEST_F(ServerTest, NoMultipleHeaders) {
  4763. Headers headers = {{"Content-Length", "5"}};
  4764. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4765. "text/plain");
  4766. ASSERT_TRUE(res);
  4767. EXPECT_EQ(StatusCode::OK_200, res->status);
  4768. }
  4769. TEST_F(ServerTest, PostContentReceiver) {
  4770. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4771. ASSERT_TRUE(res);
  4772. ASSERT_EQ(StatusCode::OK_200, res->status);
  4773. ASSERT_EQ("content", res->body);
  4774. }
  4775. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4776. UploadFormDataItems items = {
  4777. {"text1", "text default", "", ""},
  4778. {"text2", "aωb", "", ""},
  4779. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4780. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4781. {"file3", "", "", "application/octet-stream"},
  4782. };
  4783. auto res = cli_.Post("/content_receiver", items);
  4784. ASSERT_TRUE(res);
  4785. EXPECT_EQ(StatusCode::OK_200, res->status);
  4786. }
  4787. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4788. UploadFormDataItems items = {
  4789. {"text1", "text default", "", ""},
  4790. {"text2", "aωb", "", ""},
  4791. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4792. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4793. {"file3", "", "", "application/octet-stream"},
  4794. };
  4795. auto boundary = std::string("+++++");
  4796. std::string body;
  4797. for (const auto &item : items) {
  4798. body += "--" + boundary + "\r\n";
  4799. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4800. if (!item.filename.empty()) {
  4801. body += "; filename=\"" + item.filename + "\"";
  4802. }
  4803. body += "\r\n";
  4804. if (!item.content_type.empty()) {
  4805. body += "Content-Type: " + item.content_type + "\r\n";
  4806. }
  4807. body += "\r\n";
  4808. body += item.content + "\r\n";
  4809. }
  4810. body += "--" + boundary + "--\r\n";
  4811. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4812. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. }
  4816. TEST_F(ServerTest, PostContentReceiverGzip) {
  4817. cli_.set_compress(true);
  4818. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4819. ASSERT_TRUE(res);
  4820. ASSERT_EQ(StatusCode::OK_200, res->status);
  4821. ASSERT_EQ("content", res->body);
  4822. }
  4823. TEST_F(ServerTest, PutContentReceiver) {
  4824. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4825. ASSERT_TRUE(res);
  4826. ASSERT_EQ(StatusCode::OK_200, res->status);
  4827. ASSERT_EQ("content", res->body);
  4828. }
  4829. TEST_F(ServerTest, PatchContentReceiver) {
  4830. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4831. ASSERT_TRUE(res);
  4832. ASSERT_EQ(StatusCode::OK_200, res->status);
  4833. ASSERT_EQ("content", res->body);
  4834. }
  4835. template <typename ClientType>
  4836. void TestWithHeadersAndContentReceiver(
  4837. ClientType &cli,
  4838. std::function<Result(ClientType &, const std::string &, const Headers &,
  4839. const std::string &, const std::string &,
  4840. ContentReceiver, DownloadProgress)>
  4841. request_func) {
  4842. Headers headers;
  4843. headers.emplace("X-Custom-Header", "test-value");
  4844. std::string received_body;
  4845. auto res = request_func(
  4846. cli, "/content_receiver", headers, "content", "application/json",
  4847. [&](const char *data, size_t data_length) {
  4848. received_body.append(data, data_length);
  4849. return true;
  4850. },
  4851. nullptr);
  4852. ASSERT_TRUE(res);
  4853. EXPECT_EQ(StatusCode::OK_200, res->status);
  4854. EXPECT_EQ("content", received_body);
  4855. }
  4856. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4857. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4858. using ClientT = SSLClient;
  4859. #else
  4860. using ClientT = Client;
  4861. #endif
  4862. TestWithHeadersAndContentReceiver<ClientT>(
  4863. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4864. const std::string &body, const std::string &content_type,
  4865. ContentReceiver receiver, DownloadProgress progress) {
  4866. return cli.Post(path, headers, body, content_type, receiver, progress);
  4867. });
  4868. }
  4869. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4870. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4871. using ClientT = SSLClient;
  4872. #else
  4873. using ClientT = Client;
  4874. #endif
  4875. TestWithHeadersAndContentReceiver<ClientT>(
  4876. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4877. const std::string &body, const std::string &content_type,
  4878. ContentReceiver receiver, DownloadProgress progress) {
  4879. return cli.Put(path, headers, body, content_type, receiver, progress);
  4880. });
  4881. }
  4882. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4883. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4884. using ClientT = SSLClient;
  4885. #else
  4886. using ClientT = Client;
  4887. #endif
  4888. TestWithHeadersAndContentReceiver<ClientT>(
  4889. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4890. const std::string &body, const std::string &content_type,
  4891. ContentReceiver receiver, DownloadProgress progress) {
  4892. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4893. });
  4894. }
  4895. template <typename ClientType>
  4896. void TestWithHeadersAndContentReceiverWithProgress(
  4897. ClientType &cli,
  4898. std::function<Result(ClientType &, const std::string &, const Headers &,
  4899. const std::string &, const std::string &,
  4900. ContentReceiver, DownloadProgress)>
  4901. request_func) {
  4902. Headers headers;
  4903. headers.emplace("X-Test-Header", "progress-test");
  4904. std::string received_body;
  4905. auto progress_called = false;
  4906. auto res = request_func(
  4907. cli, "/content_receiver", headers, "content", "text/plain",
  4908. [&](const char *data, size_t data_length) {
  4909. received_body.append(data, data_length);
  4910. return true;
  4911. },
  4912. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4913. progress_called = true;
  4914. return true;
  4915. });
  4916. ASSERT_TRUE(res);
  4917. EXPECT_EQ(StatusCode::OK_200, res->status);
  4918. EXPECT_EQ("content", received_body);
  4919. EXPECT_TRUE(progress_called);
  4920. }
  4921. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4922. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4923. using ClientT = SSLClient;
  4924. #else
  4925. using ClientT = Client;
  4926. #endif
  4927. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4928. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4929. const std::string &body, const std::string &content_type,
  4930. ContentReceiver receiver, DownloadProgress progress) {
  4931. return cli.Post(path, headers, body, content_type, receiver, progress);
  4932. });
  4933. }
  4934. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4935. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4936. using ClientT = SSLClient;
  4937. #else
  4938. using ClientT = Client;
  4939. #endif
  4940. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4941. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4942. const std::string &body, const std::string &content_type,
  4943. ContentReceiver receiver, DownloadProgress progress) {
  4944. return cli.Put(path, headers, body, content_type, receiver, progress);
  4945. });
  4946. }
  4947. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4949. using ClientT = SSLClient;
  4950. #else
  4951. using ClientT = Client;
  4952. #endif
  4953. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4954. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4955. const std::string &body, const std::string &content_type,
  4956. ContentReceiver receiver, DownloadProgress progress) {
  4957. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4958. });
  4959. }
  4960. template <typename ClientType>
  4961. void TestWithHeadersAndContentReceiverError(
  4962. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4963. const Headers &, const std::string &,
  4964. const std::string &, ContentReceiver)>
  4965. request_func) {
  4966. Headers headers;
  4967. headers.emplace("X-Error-Test", "true");
  4968. std::string received_body;
  4969. auto receiver_failed = false;
  4970. auto res =
  4971. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4972. [&](const char *data, size_t data_length) {
  4973. received_body.append(data, data_length);
  4974. receiver_failed = true;
  4975. return false;
  4976. });
  4977. ASSERT_FALSE(res);
  4978. EXPECT_TRUE(receiver_failed);
  4979. }
  4980. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4981. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4982. using ClientT = SSLClient;
  4983. #else
  4984. using ClientT = Client;
  4985. #endif
  4986. TestWithHeadersAndContentReceiverError<ClientT>(
  4987. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4988. const std::string &body, const std::string &content_type,
  4989. ContentReceiver receiver) {
  4990. return cli.Post(path, headers, body, content_type, receiver);
  4991. });
  4992. }
  4993. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4994. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4995. using ClientT = SSLClient;
  4996. #else
  4997. using ClientT = Client;
  4998. #endif
  4999. TestWithHeadersAndContentReceiverError<ClientT>(
  5000. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5001. const std::string &body, const std::string &content_type,
  5002. ContentReceiver receiver) {
  5003. return cli.Put(path, headers, body, content_type, receiver);
  5004. });
  5005. }
  5006. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5007. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5008. using ClientT = SSLClient;
  5009. #else
  5010. using ClientT = Client;
  5011. #endif
  5012. TestWithHeadersAndContentReceiverError<ClientT>(
  5013. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5014. const std::string &body, const std::string &content_type,
  5015. ContentReceiver receiver) {
  5016. return cli.Patch(path, headers, body, content_type, receiver);
  5017. });
  5018. }
  5019. TEST_F(ServerTest, PostQueryStringAndBody) {
  5020. auto res =
  5021. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5022. ASSERT_TRUE(res);
  5023. ASSERT_EQ(StatusCode::OK_200, res->status);
  5024. }
  5025. TEST_F(ServerTest, HTTP2Magic) {
  5026. Request req;
  5027. req.method = "PRI";
  5028. req.path = "*";
  5029. req.body = "SM";
  5030. auto res = std::make_shared<Response>();
  5031. auto error = Error::Success;
  5032. auto ret = cli_.send(req, *res, error);
  5033. ASSERT_TRUE(ret);
  5034. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5035. }
  5036. TEST_F(ServerTest, KeepAlive) {
  5037. auto res = cli_.Get("/hi");
  5038. ASSERT_TRUE(res);
  5039. EXPECT_EQ(StatusCode::OK_200, res->status);
  5040. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5041. EXPECT_EQ("Hello World!", res->body);
  5042. res = cli_.Get("/hi");
  5043. ASSERT_TRUE(res);
  5044. EXPECT_EQ(StatusCode::OK_200, res->status);
  5045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5046. EXPECT_EQ("Hello World!", res->body);
  5047. res = cli_.Get("/hi");
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ(StatusCode::OK_200, res->status);
  5050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5051. EXPECT_EQ("Hello World!", res->body);
  5052. res = cli_.Get("/not-exist");
  5053. ASSERT_TRUE(res);
  5054. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5055. res = cli_.Post("/empty", "", "text/plain");
  5056. ASSERT_TRUE(res);
  5057. EXPECT_EQ(StatusCode::OK_200, res->status);
  5058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5059. EXPECT_EQ("empty", res->body);
  5060. EXPECT_EQ("close", res->get_header_value("Connection"));
  5061. res = cli_.Post(
  5062. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5063. "text/plain");
  5064. ASSERT_TRUE(res);
  5065. EXPECT_EQ(StatusCode::OK_200, res->status);
  5066. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5067. EXPECT_EQ("empty", res->body);
  5068. cli_.set_keep_alive(false);
  5069. res = cli_.Get("/last-request");
  5070. ASSERT_TRUE(res);
  5071. EXPECT_EQ(StatusCode::OK_200, res->status);
  5072. EXPECT_EQ("close", res->get_header_value("Connection"));
  5073. }
  5074. TEST_F(ServerTest, TooManyRedirect) {
  5075. cli_.set_follow_location(true);
  5076. auto res = cli_.Get("/redirect/0");
  5077. ASSERT_TRUE(!res);
  5078. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5079. }
  5080. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5081. Request req;
  5082. req.method = "FOOBAR";
  5083. req.path = "/hi";
  5084. cli_.set_keep_alive(true);
  5085. auto res = cli_.send(req);
  5086. ASSERT_TRUE(res);
  5087. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5088. EXPECT_EQ("close", res->get_header_value("Connection"));
  5089. EXPECT_FALSE(cli_.is_socket_open());
  5090. }
  5091. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5092. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5093. TEST_F(ServerTest, Gzip) {
  5094. Headers headers;
  5095. headers.emplace("Accept-Encoding", "gzip, deflate");
  5096. auto res = cli_.Get("/compress", headers);
  5097. ASSERT_TRUE(res);
  5098. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5100. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5101. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5102. "7890123456789012345678901234567890",
  5103. res->body);
  5104. EXPECT_EQ(StatusCode::OK_200, res->status);
  5105. }
  5106. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5107. Headers headers;
  5108. headers.emplace("Accept-Encoding", "");
  5109. auto res = cli_.Get("/compress", headers);
  5110. ASSERT_TRUE(res);
  5111. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5113. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5114. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5115. "7890123456789012345678901234567890",
  5116. res->body);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. }
  5119. TEST_F(ServerTest, GzipWithContentReceiver) {
  5120. Headers headers;
  5121. headers.emplace("Accept-Encoding", "gzip, deflate");
  5122. std::string body;
  5123. auto res = cli_.Get("/compress", headers,
  5124. [&](const char *data, uint64_t data_length) {
  5125. EXPECT_EQ(100U, data_length);
  5126. body.append(data, data_length);
  5127. return true;
  5128. });
  5129. ASSERT_TRUE(res);
  5130. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5131. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5132. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5133. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5134. "7890123456789012345678901234567890",
  5135. body);
  5136. EXPECT_EQ(StatusCode::OK_200, res->status);
  5137. }
  5138. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5139. Headers headers;
  5140. headers.emplace("Accept-Encoding", "gzip, deflate");
  5141. cli_.set_decompress(false);
  5142. auto res = cli_.Get("/compress", headers);
  5143. ASSERT_TRUE(res);
  5144. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5145. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5146. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5147. EXPECT_EQ(33U, res->body.size());
  5148. EXPECT_EQ(StatusCode::OK_200, res->status);
  5149. }
  5150. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5151. Headers headers;
  5152. headers.emplace("Accept-Encoding", "");
  5153. std::string body;
  5154. auto res = cli_.Get("/compress", headers,
  5155. [&](const char *data, uint64_t data_length) {
  5156. EXPECT_EQ(100U, data_length);
  5157. body.append(data, data_length);
  5158. return true;
  5159. });
  5160. ASSERT_TRUE(res);
  5161. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5162. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5163. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5164. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5165. "7890123456789012345678901234567890",
  5166. body);
  5167. EXPECT_EQ(StatusCode::OK_200, res->status);
  5168. }
  5169. TEST_F(ServerTest, NoGzip) {
  5170. Headers headers;
  5171. headers.emplace("Accept-Encoding", "gzip, deflate");
  5172. auto res = cli_.Get("/nocompress", headers);
  5173. ASSERT_TRUE(res);
  5174. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5175. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5176. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5177. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5178. "7890123456789012345678901234567890",
  5179. res->body);
  5180. EXPECT_EQ(StatusCode::OK_200, res->status);
  5181. }
  5182. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5183. Headers headers;
  5184. headers.emplace("Accept-Encoding", "gzip, deflate");
  5185. std::string body;
  5186. auto res = cli_.Get("/nocompress", headers,
  5187. [&](const char *data, uint64_t data_length) {
  5188. EXPECT_EQ(100U, data_length);
  5189. body.append(data, data_length);
  5190. return true;
  5191. });
  5192. ASSERT_TRUE(res);
  5193. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5194. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5195. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5196. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5197. "7890123456789012345678901234567890",
  5198. body);
  5199. EXPECT_EQ(StatusCode::OK_200, res->status);
  5200. }
  5201. TEST_F(ServerTest, MultipartFormDataGzip) {
  5202. UploadFormDataItems items = {
  5203. {"key1", "test", "", ""},
  5204. {"key2", "--abcdefg123", "", ""},
  5205. };
  5206. cli_.set_compress(true);
  5207. auto res = cli_.Post("/compress-multipart", items);
  5208. ASSERT_TRUE(res);
  5209. EXPECT_EQ(StatusCode::OK_200, res->status);
  5210. }
  5211. #endif
  5212. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5213. TEST_F(ServerTest, Brotli) {
  5214. Headers headers;
  5215. headers.emplace("Accept-Encoding", "br");
  5216. auto res = cli_.Get("/compress", headers);
  5217. ASSERT_TRUE(res);
  5218. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5219. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5220. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5221. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5222. "7890123456789012345678901234567890",
  5223. res->body);
  5224. EXPECT_EQ(StatusCode::OK_200, res->status);
  5225. }
  5226. #endif
  5227. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5228. TEST_F(ServerTest, Zstd) {
  5229. Headers headers;
  5230. headers.emplace("Accept-Encoding", "zstd");
  5231. auto res = cli_.Get("/compress", headers);
  5232. ASSERT_TRUE(res);
  5233. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5235. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5236. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5237. "7890123456789012345678901234567890",
  5238. res->body);
  5239. EXPECT_EQ(StatusCode::OK_200, res->status);
  5240. }
  5241. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5242. Headers headers;
  5243. headers.emplace("Accept-Encoding", "");
  5244. auto res = cli_.Get("/compress", headers);
  5245. ASSERT_TRUE(res);
  5246. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5247. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5249. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5250. "7890123456789012345678901234567890",
  5251. res->body);
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. }
  5254. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5255. Headers headers;
  5256. headers.emplace("Accept-Encoding", "zstd");
  5257. std::string body;
  5258. auto res = cli_.Get("/compress", headers,
  5259. [&](const char *data, uint64_t data_length) {
  5260. EXPECT_EQ(100U, data_length);
  5261. body.append(data, data_length);
  5262. return true;
  5263. });
  5264. ASSERT_TRUE(res);
  5265. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5266. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5267. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5268. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5269. "7890123456789012345678901234567890",
  5270. body);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. }
  5273. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5274. Headers headers;
  5275. headers.emplace("Accept-Encoding", "zstd");
  5276. cli_.set_decompress(false);
  5277. auto res = cli_.Get("/compress", headers);
  5278. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5279. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5280. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5281. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5282. ASSERT_TRUE(res);
  5283. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5285. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. ASSERT_EQ(26U, res->body.size());
  5288. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5289. 0);
  5290. }
  5291. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5292. Headers headers;
  5293. headers.emplace("Accept-Encoding", "");
  5294. std::string body;
  5295. auto res = cli_.Get("/compress", headers,
  5296. [&](const char *data, uint64_t data_length) {
  5297. EXPECT_EQ(100U, data_length);
  5298. body.append(data, data_length);
  5299. return true;
  5300. });
  5301. ASSERT_TRUE(res);
  5302. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5304. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5305. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5306. "7890123456789012345678901234567890",
  5307. body);
  5308. EXPECT_EQ(StatusCode::OK_200, res->status);
  5309. }
  5310. TEST_F(ServerTest, NoZstd) {
  5311. Headers headers;
  5312. headers.emplace("Accept-Encoding", "zstd");
  5313. auto res = cli_.Get("/nocompress", headers);
  5314. ASSERT_TRUE(res);
  5315. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5316. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5317. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5318. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5319. "7890123456789012345678901234567890",
  5320. res->body);
  5321. EXPECT_EQ(StatusCode::OK_200, res->status);
  5322. }
  5323. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5324. Headers headers;
  5325. headers.emplace("Accept-Encoding", "zstd");
  5326. std::string body;
  5327. auto res = cli_.Get("/nocompress", headers,
  5328. [&](const char *data, uint64_t data_length) {
  5329. EXPECT_EQ(100U, data_length);
  5330. body.append(data, data_length);
  5331. return true;
  5332. });
  5333. ASSERT_TRUE(res);
  5334. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5335. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5336. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5337. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5338. "7890123456789012345678901234567890",
  5339. body);
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. }
  5342. // TODO: How to enable zstd ??
  5343. TEST_F(ServerTest, MultipartFormDataZstd) {
  5344. UploadFormDataItems items = {
  5345. {"key1", "test", "", ""},
  5346. {"key2", "--abcdefg123", "", ""},
  5347. };
  5348. Headers headers;
  5349. headers.emplace("Accept-Encoding", "zstd");
  5350. cli_.set_compress(true);
  5351. auto res = cli_.Post("/compress-multipart", headers, items);
  5352. ASSERT_TRUE(res);
  5353. EXPECT_EQ(StatusCode::OK_200, res->status);
  5354. }
  5355. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5356. Headers headers;
  5357. headers.emplace("Accept-Encoding", "zstd");
  5358. cli_.set_compress(true);
  5359. auto res = cli_.Put(
  5360. "/put", headers, 3,
  5361. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5362. sink.os << "PUT";
  5363. return true;
  5364. },
  5365. "text/plain");
  5366. ASSERT_TRUE(res);
  5367. EXPECT_EQ(StatusCode::OK_200, res->status);
  5368. EXPECT_EQ("PUT", res->body);
  5369. }
  5370. // Pre-compression logging tests
  5371. TEST_F(ServerTest, PreCompressionLogging) {
  5372. // Test data for compression (matches the actual /compress endpoint content)
  5373. const std::string test_content =
  5374. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5375. "3456789012345678901234567890";
  5376. // Variables to capture logging data
  5377. std::string pre_compression_body;
  5378. std::string pre_compression_content_type;
  5379. std::string pre_compression_content_encoding;
  5380. std::string post_compression_body;
  5381. std::string post_compression_content_type;
  5382. std::string post_compression_content_encoding;
  5383. // Set up pre-compression logger
  5384. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5385. const Response &res) {
  5386. pre_compression_body = res.body;
  5387. pre_compression_content_type = res.get_header_value("Content-Type");
  5388. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5389. });
  5390. // Set up post-compression logger
  5391. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5392. post_compression_body = res.body;
  5393. post_compression_content_type = res.get_header_value("Content-Type");
  5394. post_compression_content_encoding =
  5395. res.get_header_value("Content-Encoding");
  5396. });
  5397. // Test with gzip compression
  5398. Headers headers;
  5399. headers.emplace("Accept-Encoding", "gzip");
  5400. auto res = cli_.Get("/compress", headers);
  5401. // Verify response was compressed
  5402. ASSERT_TRUE(res);
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5405. // Verify pre-compression logger captured uncompressed content
  5406. EXPECT_EQ(test_content, pre_compression_body);
  5407. EXPECT_EQ("text/plain", pre_compression_content_type);
  5408. EXPECT_TRUE(pre_compression_content_encoding
  5409. .empty()); // No encoding header before compression
  5410. // Verify post-compression logger captured compressed content
  5411. EXPECT_NE(test_content,
  5412. post_compression_body); // Should be different after compression
  5413. EXPECT_EQ("text/plain", post_compression_content_type);
  5414. EXPECT_EQ("gzip", post_compression_content_encoding);
  5415. // Verify compressed content is smaller
  5416. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5417. }
  5418. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5419. const std::string test_content =
  5420. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5421. "3456789012345678901234567890";
  5422. std::string pre_compression_body;
  5423. std::string post_compression_body;
  5424. svr_.set_pre_compression_logger(
  5425. [&](const Request & /*req*/, const Response &res) {
  5426. pre_compression_body = res.body;
  5427. });
  5428. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5429. post_compression_body = res.body;
  5430. });
  5431. Headers headers;
  5432. headers.emplace("Accept-Encoding", "br");
  5433. auto res = cli_.Get("/compress", headers);
  5434. ASSERT_TRUE(res);
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5437. // Verify pre-compression content is uncompressed
  5438. EXPECT_EQ(test_content, pre_compression_body);
  5439. // Verify post-compression content is compressed
  5440. EXPECT_NE(test_content, post_compression_body);
  5441. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5442. }
  5443. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5444. const std::string test_content =
  5445. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5446. "3456789012345678901234567890";
  5447. std::string pre_compression_body;
  5448. std::string post_compression_body;
  5449. svr_.set_pre_compression_logger(
  5450. [&](const Request & /*req*/, const Response &res) {
  5451. pre_compression_body = res.body;
  5452. });
  5453. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5454. post_compression_body = res.body;
  5455. });
  5456. // Request without compression (use /nocompress endpoint)
  5457. Headers headers;
  5458. auto res = cli_.Get("/nocompress", headers);
  5459. ASSERT_TRUE(res);
  5460. EXPECT_EQ(StatusCode::OK_200, res->status);
  5461. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5462. // Pre-compression logger should not be called when no compression is applied
  5463. EXPECT_TRUE(
  5464. pre_compression_body.empty()); // Pre-compression logger not called
  5465. EXPECT_EQ(
  5466. test_content,
  5467. post_compression_body); // Post-compression logger captures final content
  5468. }
  5469. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5470. const std::string test_content =
  5471. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5472. "3456789012345678901234567890";
  5473. std::string pre_compression_body;
  5474. bool pre_logger_called = false;
  5475. // Set only pre-compression logger
  5476. svr_.set_pre_compression_logger(
  5477. [&](const Request & /*req*/, const Response &res) {
  5478. pre_compression_body = res.body;
  5479. pre_logger_called = true;
  5480. });
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "gzip");
  5483. auto res = cli_.Get("/compress", headers);
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5487. // Verify pre-compression logger was called
  5488. EXPECT_TRUE(pre_logger_called);
  5489. EXPECT_EQ(test_content, pre_compression_body);
  5490. }
  5491. TEST(ZstdDecompressor, ChunkedDecompression) {
  5492. std::string data;
  5493. for (size_t i = 0; i < 32 * 1024; ++i) {
  5494. data.push_back(static_cast<char>('a' + i % 26));
  5495. }
  5496. std::string compressed_data;
  5497. {
  5498. httplib::detail::zstd_compressor compressor;
  5499. bool result = compressor.compress(
  5500. data.data(), data.size(),
  5501. /*last=*/true,
  5502. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5503. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5504. compressed_data_size);
  5505. return true;
  5506. });
  5507. ASSERT_TRUE(result);
  5508. }
  5509. std::string decompressed_data;
  5510. {
  5511. httplib::detail::zstd_decompressor decompressor;
  5512. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5513. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5514. size_t chunk_size = 130;
  5515. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5516. chunk_begin += chunk_size) {
  5517. size_t current_chunk_size =
  5518. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5519. bool result = decompressor.decompress(
  5520. compressed_data.data() + chunk_begin, current_chunk_size,
  5521. [&](const char *decompressed_data_chunk,
  5522. size_t decompressed_data_chunk_size) {
  5523. decompressed_data.insert(decompressed_data.size(),
  5524. decompressed_data_chunk,
  5525. decompressed_data_chunk_size);
  5526. return true;
  5527. });
  5528. ASSERT_TRUE(result);
  5529. }
  5530. }
  5531. ASSERT_EQ(data, decompressed_data);
  5532. }
  5533. TEST(ZstdDecompressor, Decompress) {
  5534. std::string original_text = "Compressed with ZSTD";
  5535. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5536. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5537. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5538. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5539. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5540. std::string decompressed_data;
  5541. {
  5542. httplib::detail::zstd_decompressor decompressor;
  5543. bool result = decompressor.decompress(
  5544. compressed_data.data(), compressed_data.size(),
  5545. [&](const char *decompressed_data_chunk,
  5546. size_t decompressed_data_chunk_size) {
  5547. decompressed_data.insert(decompressed_data.size(),
  5548. decompressed_data_chunk,
  5549. decompressed_data_chunk_size);
  5550. return true;
  5551. });
  5552. ASSERT_TRUE(result);
  5553. }
  5554. ASSERT_EQ(original_text, decompressed_data);
  5555. }
  5556. #endif
  5557. // Sends a raw request to a server listening at HOST:PORT.
  5558. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5559. std::string *resp = nullptr) {
  5560. auto error = Error::Success;
  5561. auto client_sock = detail::create_client_socket(
  5562. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5563. /*connection_timeout_sec=*/5, 0,
  5564. /*read_timeout_sec=*/5, 0,
  5565. /*write_timeout_sec=*/5, 0, std::string(), error);
  5566. if (client_sock == INVALID_SOCKET) { return false; }
  5567. auto ret = detail::process_client_socket(
  5568. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5569. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5570. if (req.size() !=
  5571. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5572. return false;
  5573. }
  5574. char buf[512];
  5575. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5576. while (line_reader.getline()) {
  5577. if (resp) { *resp += line_reader.ptr(); }
  5578. }
  5579. return true;
  5580. });
  5581. detail::close_socket(client_sock);
  5582. return ret;
  5583. }
  5584. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5585. Server svr;
  5586. std::string header_value;
  5587. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5588. header_value = req.get_header_value("foo");
  5589. res.set_content("ok", "text/plain");
  5590. });
  5591. thread t = thread([&] { svr.listen(HOST, PORT); });
  5592. auto se = detail::scope_exit([&] {
  5593. svr.stop();
  5594. t.join();
  5595. ASSERT_FALSE(svr.is_running());
  5596. });
  5597. svr.wait_until_ready();
  5598. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5599. // like characters are not treated the same - use vertical tab and escape.
  5600. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5601. "foo: \t \v bar \x1B\t \r\n"
  5602. "Connection: close\r\n"
  5603. "\r\n";
  5604. std::string res;
  5605. ASSERT_TRUE(send_request(5, req, &res));
  5606. EXPECT_EQ(header_value, "");
  5607. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5608. }
  5609. // Sends a raw request and verifies that there isn't a crash or exception.
  5610. static void test_raw_request(const std::string &req,
  5611. std::string *out = nullptr) {
  5612. Server svr;
  5613. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5614. res.set_content("ok", "text/plain");
  5615. });
  5616. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5617. res.set_content("ok", "text/plain");
  5618. });
  5619. svr.Get("/header_field_value_check",
  5620. [&](const Request & /*req*/, Response &res) {
  5621. res.set_content("ok", "text/plain");
  5622. });
  5623. // Server read timeout must be longer than the client read timeout for the
  5624. // bug to reproduce, probably to force the server to process a request
  5625. // without a trailing blank line.
  5626. const time_t client_read_timeout_sec = 1;
  5627. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5628. bool listen_thread_ok = false;
  5629. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5630. auto se = detail::scope_exit([&] {
  5631. svr.stop();
  5632. t.join();
  5633. ASSERT_FALSE(svr.is_running());
  5634. EXPECT_TRUE(listen_thread_ok);
  5635. });
  5636. svr.wait_until_ready();
  5637. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5638. }
  5639. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5640. // A certain header line causes an exception if the header property is parsed
  5641. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5642. test_raw_request(
  5643. "GET /hi HTTP/1.1\r\n"
  5644. " : "
  5645. " "
  5646. " ");
  5647. }
  5648. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5649. // A certain header line causes an exception if the header property *name* is
  5650. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5651. // greedy matcher and requires backtracking when there are a lot of ":"
  5652. // characters.
  5653. // This occurs with libc++ but not libstdc++.
  5654. test_raw_request(
  5655. "GET /hi HTTP/1.1\r\n"
  5656. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5657. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5658. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5659. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5660. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5661. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5662. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5663. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5664. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5665. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5666. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5667. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5668. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5669. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5670. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5671. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5672. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5673. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5674. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5675. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5676. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5677. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5678. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5679. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5680. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5681. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5682. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5683. "&&&%%%");
  5684. }
  5685. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5686. // Make sure this doesn't crash the server.
  5687. // In a previous version of the header line regex, the "\r" rendered the line
  5688. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5689. // a new position where the leading white space ended and the field value
  5690. // began.
  5691. // The crash occurs with libc++ but not libstdc++.
  5692. test_raw_request("GET /hi HTTP/1.1\r\n"
  5693. "a:" +
  5694. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5695. "\r\n"
  5696. "\r\n");
  5697. }
  5698. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5699. std::string out;
  5700. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5701. "Content-Type: text/plain\r\n"
  5702. "Transfer-Encoding: chunked\r\n"
  5703. "\r\n"
  5704. "nothex\r\n",
  5705. &out);
  5706. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5707. }
  5708. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5709. std::string out;
  5710. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5711. "Content-Type: text/plain\r\n"
  5712. "Transfer-Encoding: chunked\r\n"
  5713. "\r\n"
  5714. "3\r\n"
  5715. "xyz\r\n"
  5716. "NaN\r\n",
  5717. &out);
  5718. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5719. }
  5720. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5721. std::string out;
  5722. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5723. "Content-Type: text/plain\r\n"
  5724. "Transfer-Encoding: chunked\r\n"
  5725. "\r\n"
  5726. // Length is too large for 64 bits.
  5727. "1ffffffffffffffff\r\n"
  5728. "xyz\r\n",
  5729. &out);
  5730. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5731. }
  5732. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5733. test_raw_request("GET /hi HTTP/1.1\r\n"
  5734. "Content-Type: text/plain\r\n\r");
  5735. }
  5736. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5737. std::string out;
  5738. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5739. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5740. }
  5741. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5742. std::string out;
  5743. std::string request(
  5744. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5745. test_raw_request(request, &out);
  5746. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5747. }
  5748. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5749. std::string out;
  5750. std::string request(
  5751. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5752. test_raw_request(request, &out);
  5753. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5754. }
  5755. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5756. std::string out;
  5757. std::string request(
  5758. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5759. test_raw_request(request, &out);
  5760. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5761. }
  5762. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5763. std::string out;
  5764. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5765. "Test: \r\n\r\n",
  5766. &out);
  5767. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5768. }
  5769. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5770. Server svr;
  5771. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5772. res.set_header("Cache-Control", "no-cache");
  5773. res.set_chunked_content_provider(
  5774. "text/event-stream", [](size_t offset, DataSink &sink) {
  5775. std::string s = "data:";
  5776. s += std::to_string(offset);
  5777. s += "\n\n";
  5778. auto ret = sink.write(s.data(), s.size());
  5779. EXPECT_TRUE(ret);
  5780. std::this_thread::sleep_for(std::chrono::seconds(1));
  5781. return true;
  5782. });
  5783. });
  5784. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5785. svr.wait_until_ready();
  5786. Client client(HOST, PORT);
  5787. const Headers headers = {{"Accept", "text/event-stream"}};
  5788. auto get_thread = std::thread([&client, &headers]() {
  5789. auto res = client.Get(
  5790. "/events", headers,
  5791. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5792. });
  5793. auto se = detail::scope_exit([&] {
  5794. svr.stop();
  5795. get_thread.join();
  5796. listen_thread.join();
  5797. ASSERT_FALSE(svr.is_running());
  5798. });
  5799. // Give GET time to get a few messages.
  5800. std::this_thread::sleep_for(std::chrono::seconds(2));
  5801. }
  5802. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5803. httplib::Server svr;
  5804. svr.Post("/hi",
  5805. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5806. res.status = StatusCode::OK_200;
  5807. });
  5808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5809. svr.wait_until_ready();
  5810. Client cli(HOST, PORT);
  5811. auto res = cli.Post("/hi", "data", "text/plain");
  5812. ASSERT_TRUE(res);
  5813. EXPECT_EQ(StatusCode::OK_200, res->status);
  5814. svr.stop();
  5815. thread.join();
  5816. ASSERT_FALSE(svr.is_running());
  5817. res = cli.Post("/hi", "data", "text/plain");
  5818. ASSERT_FALSE(res);
  5819. }
  5820. TEST(ServerStopTest, ListenFailure) {
  5821. Server svr;
  5822. auto t = thread([&]() {
  5823. auto ret = svr.listen("????", PORT);
  5824. EXPECT_FALSE(ret);
  5825. });
  5826. svr.wait_until_ready();
  5827. svr.stop();
  5828. t.join();
  5829. }
  5830. TEST(ServerStopTest, Decommision) {
  5831. Server svr;
  5832. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5833. for (int i = 0; i < 4; i++) {
  5834. auto is_even = !(i % 2);
  5835. std::thread t{[&] {
  5836. try {
  5837. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5838. if (is_even) {
  5839. throw std::runtime_error("Some thing that happens to go wrong.");
  5840. }
  5841. svr.listen(HOST, PORT);
  5842. } catch (...) { svr.decommission(); }
  5843. }};
  5844. svr.wait_until_ready();
  5845. // Server is up
  5846. {
  5847. Client cli(HOST, PORT);
  5848. auto res = cli.Get("/hi");
  5849. if (is_even) {
  5850. EXPECT_FALSE(res);
  5851. } else {
  5852. EXPECT_TRUE(res);
  5853. EXPECT_EQ("hi...", res->body);
  5854. }
  5855. }
  5856. svr.stop();
  5857. t.join();
  5858. // Server is down...
  5859. {
  5860. Client cli(HOST, PORT);
  5861. auto res = cli.Get("/hi");
  5862. EXPECT_FALSE(res);
  5863. }
  5864. }
  5865. }
  5866. // Helper function for string body upload progress tests
  5867. template <typename SetupHandler, typename ClientCall>
  5868. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5869. ClientCall &&client_call,
  5870. const string &body) {
  5871. Server svr;
  5872. setup_handler(svr);
  5873. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5874. auto se = detail::scope_exit([&] {
  5875. svr.stop();
  5876. t.join();
  5877. });
  5878. svr.wait_until_ready();
  5879. Client cli(HOST, PORT);
  5880. vector<uint64_t> progress_values;
  5881. bool progress_called = false;
  5882. auto res =
  5883. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5884. progress_values.push_back(current);
  5885. progress_called = true;
  5886. return true;
  5887. });
  5888. ASSERT_TRUE(res);
  5889. EXPECT_EQ(200, res->status);
  5890. EXPECT_TRUE(progress_called);
  5891. }
  5892. TEST(UploadProgressTest, PostStringBodyBasic) {
  5893. TestStringBodyUploadProgress(
  5894. [](Server &svr) {
  5895. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5896. res.set_content("received", "text/plain");
  5897. });
  5898. },
  5899. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5900. return cli.Post("/test", body, "text/plain", progress_callback);
  5901. },
  5902. "test data for upload progress");
  5903. }
  5904. TEST(UploadProgressTest, PutStringBodyBasic) {
  5905. TestStringBodyUploadProgress(
  5906. [](Server &svr) {
  5907. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5908. res.set_content("put received", "text/plain");
  5909. });
  5910. },
  5911. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5912. return cli.Put("/test", body, "text/plain", progress_callback);
  5913. },
  5914. "put test data for upload progress");
  5915. }
  5916. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5917. TestStringBodyUploadProgress(
  5918. [](Server &svr) {
  5919. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5920. res.set_content("patch received", "text/plain");
  5921. });
  5922. },
  5923. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5924. return cli.Patch("/test", body, "text/plain", progress_callback);
  5925. },
  5926. "patch test data for upload progress");
  5927. }
  5928. // Helper function for content provider upload progress tests
  5929. template <typename SetupHandler, typename ClientCall>
  5930. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5931. ClientCall &&client_call) {
  5932. Server svr;
  5933. setup_handler(svr);
  5934. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5935. auto se = detail::scope_exit([&] {
  5936. svr.stop();
  5937. t.join();
  5938. });
  5939. svr.wait_until_ready();
  5940. Client cli(HOST, PORT);
  5941. vector<uint64_t> progress_values;
  5942. auto res =
  5943. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5944. progress_values.push_back(current);
  5945. return true;
  5946. });
  5947. ASSERT_TRUE(res);
  5948. EXPECT_EQ(200, res->status);
  5949. EXPECT_FALSE(progress_values.empty());
  5950. }
  5951. TEST(UploadProgressTest, PostContentProviderProgress) {
  5952. TestContentProviderUploadProgress(
  5953. [](Server &svr) {
  5954. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5955. res.set_content("provider received", "text/plain");
  5956. });
  5957. },
  5958. [](Client &cli, UploadProgress progress_callback) {
  5959. return cli.Post(
  5960. "/test", 10,
  5961. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5962. sink.os << "test data";
  5963. return true;
  5964. },
  5965. "text/plain", progress_callback);
  5966. });
  5967. }
  5968. // Helper function for multipart upload progress tests
  5969. template <typename SetupHandler, typename ClientCall>
  5970. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5971. ClientCall &&client_call,
  5972. const string &endpoint) {
  5973. Server svr;
  5974. setup_handler(svr);
  5975. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5976. auto se = detail::scope_exit([&] {
  5977. svr.stop();
  5978. t.join();
  5979. });
  5980. svr.wait_until_ready();
  5981. Client cli(HOST, PORT);
  5982. vector<uint64_t> progress_values;
  5983. UploadFormDataItems items = {
  5984. {"field1", "value1", "", ""},
  5985. {"field2", "longer value for progress tracking test", "", ""},
  5986. {"file1", "file content data for upload progress", "test.txt",
  5987. "text/plain"}};
  5988. auto res = client_call(cli, endpoint, items,
  5989. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5990. progress_values.push_back(current);
  5991. return true;
  5992. });
  5993. ASSERT_TRUE(res);
  5994. EXPECT_EQ(200, res->status);
  5995. EXPECT_FALSE(progress_values.empty());
  5996. }
  5997. TEST(UploadProgressTest, PostMultipartProgress) {
  5998. TestMultipartUploadProgress(
  5999. [](Server &svr) {
  6000. svr.Post("/multipart", [](const Request &req, Response &res) {
  6001. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6002. res.set_content("multipart received", "text/plain");
  6003. });
  6004. },
  6005. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6006. UploadProgress progress_callback) {
  6007. return cli.Post(endpoint, items, progress_callback);
  6008. },
  6009. "/multipart");
  6010. }
  6011. // Helper function for basic download progress tests
  6012. template <typename SetupHandler, typename ClientCall>
  6013. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6014. ClientCall &&client_call, const string &endpoint,
  6015. size_t expected_content_size) {
  6016. Server svr;
  6017. setup_handler(svr);
  6018. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6019. auto se = detail::scope_exit([&] {
  6020. svr.stop();
  6021. t.join();
  6022. });
  6023. svr.wait_until_ready();
  6024. Client cli(HOST, PORT);
  6025. vector<uint64_t> progress_values;
  6026. auto res = client_call(cli, endpoint,
  6027. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6028. progress_values.push_back(current);
  6029. return true;
  6030. });
  6031. ASSERT_TRUE(res);
  6032. EXPECT_EQ(200, res->status);
  6033. EXPECT_FALSE(progress_values.empty());
  6034. EXPECT_EQ(expected_content_size, res->body.size());
  6035. }
  6036. TEST(DownloadProgressTest, GetBasic) {
  6037. TestBasicDownloadProgress(
  6038. [](Server &svr) {
  6039. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6040. string content(1000, 'D');
  6041. res.set_content(content, "text/plain");
  6042. });
  6043. },
  6044. [](Client &cli, const string &endpoint,
  6045. DownloadProgress progress_callback) {
  6046. return cli.Get(endpoint, progress_callback);
  6047. },
  6048. "/download", 1000u);
  6049. }
  6050. // Helper function for content receiver download progress tests
  6051. template <typename SetupHandler, typename ClientCall>
  6052. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6053. ClientCall &&client_call,
  6054. const string &endpoint,
  6055. size_t expected_content_size) {
  6056. Server svr;
  6057. setup_handler(svr);
  6058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6059. auto se = detail::scope_exit([&] {
  6060. svr.stop();
  6061. t.join();
  6062. });
  6063. svr.wait_until_ready();
  6064. Client cli(HOST, PORT);
  6065. vector<uint64_t> progress_values;
  6066. string received_body;
  6067. auto res = client_call(
  6068. cli, endpoint,
  6069. [&](const char *data, size_t data_length) -> bool {
  6070. received_body.append(data, data_length);
  6071. return true;
  6072. },
  6073. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6074. progress_values.push_back(current);
  6075. return true;
  6076. });
  6077. ASSERT_TRUE(res);
  6078. EXPECT_EQ(200, res->status);
  6079. EXPECT_FALSE(progress_values.empty());
  6080. EXPECT_EQ(expected_content_size, received_body.size());
  6081. EXPECT_TRUE(res->body.empty());
  6082. }
  6083. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6084. TestContentReceiverDownloadProgress(
  6085. [](Server &svr) {
  6086. svr.Get("/download-receiver",
  6087. [](const Request & /*req*/, Response &res) {
  6088. string content(2000, 'R');
  6089. res.set_content(content, "text/plain");
  6090. });
  6091. },
  6092. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6093. DownloadProgress progress_callback) {
  6094. return cli.Get(endpoint, content_receiver, progress_callback);
  6095. },
  6096. "/download-receiver", 2000u);
  6097. }
  6098. TEST(StreamingTest, NoContentLengthStreaming) {
  6099. Server svr;
  6100. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6101. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6102. if (offset < 6) {
  6103. sink.os << (offset < 3 ? "a" : "b");
  6104. } else {
  6105. sink.done();
  6106. }
  6107. return true;
  6108. });
  6109. });
  6110. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6111. auto listen_se = detail::scope_exit([&] {
  6112. svr.stop();
  6113. listen_thread.join();
  6114. ASSERT_FALSE(svr.is_running());
  6115. });
  6116. svr.wait_until_ready();
  6117. Client client(HOST, PORT);
  6118. auto get_thread = std::thread([&client]() {
  6119. std::string s;
  6120. auto res =
  6121. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6122. s += std::string(data, len);
  6123. return true;
  6124. });
  6125. ASSERT_TRUE(res);
  6126. EXPECT_EQ(StatusCode::OK_200, res->status);
  6127. EXPECT_EQ("aaabbb", s);
  6128. });
  6129. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6130. // Give GET time to get a few messages.
  6131. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6132. }
  6133. TEST(MountTest, Unmount) {
  6134. Server svr;
  6135. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6136. auto se = detail::scope_exit([&] {
  6137. svr.stop();
  6138. listen_thread.join();
  6139. ASSERT_FALSE(svr.is_running());
  6140. });
  6141. svr.wait_until_ready();
  6142. Client cli("localhost", PORT);
  6143. svr.set_mount_point("/mount2", "./www2");
  6144. auto res = cli.Get("/");
  6145. ASSERT_TRUE(res);
  6146. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6147. res = cli.Get("/mount2/dir/test.html");
  6148. ASSERT_TRUE(res);
  6149. EXPECT_EQ(StatusCode::OK_200, res->status);
  6150. svr.set_mount_point("/", "./www");
  6151. res = cli.Get("/dir/");
  6152. ASSERT_TRUE(res);
  6153. EXPECT_EQ(StatusCode::OK_200, res->status);
  6154. svr.remove_mount_point("/");
  6155. res = cli.Get("/dir/");
  6156. ASSERT_TRUE(res);
  6157. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6158. svr.remove_mount_point("/mount2");
  6159. res = cli.Get("/mount2/dir/test.html");
  6160. ASSERT_TRUE(res);
  6161. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6162. }
  6163. TEST(MountTest, Redicect) {
  6164. Server svr;
  6165. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6166. auto se = detail::scope_exit([&] {
  6167. svr.stop();
  6168. listen_thread.join();
  6169. ASSERT_FALSE(svr.is_running());
  6170. });
  6171. svr.set_mount_point("/", "./www");
  6172. svr.wait_until_ready();
  6173. Client cli("localhost", PORT);
  6174. auto res = cli.Get("/dir/");
  6175. ASSERT_TRUE(res);
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. res = cli.Get("/dir");
  6178. ASSERT_TRUE(res);
  6179. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6180. res = cli.Get("/file");
  6181. ASSERT_TRUE(res);
  6182. EXPECT_EQ(StatusCode::OK_200, res->status);
  6183. res = cli.Get("/file/");
  6184. ASSERT_TRUE(res);
  6185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6186. cli.set_follow_location(true);
  6187. res = cli.Get("/dir");
  6188. ASSERT_TRUE(res);
  6189. EXPECT_EQ(StatusCode::OK_200, res->status);
  6190. }
  6191. TEST(MountTest, MultibytesPathName) {
  6192. Server svr;
  6193. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6194. auto se = detail::scope_exit([&] {
  6195. svr.stop();
  6196. listen_thread.join();
  6197. ASSERT_FALSE(svr.is_running());
  6198. });
  6199. svr.set_mount_point("/", "./www");
  6200. svr.wait_until_ready();
  6201. Client cli("localhost", PORT);
  6202. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6203. ASSERT_TRUE(res);
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6206. }
  6207. TEST(KeepAliveTest, ReadTimeout) {
  6208. Server svr;
  6209. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6210. std::this_thread::sleep_for(std::chrono::seconds(2));
  6211. res.set_content("a", "text/plain");
  6212. });
  6213. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6214. res.set_content("b", "text/plain");
  6215. });
  6216. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6217. auto se = detail::scope_exit([&] {
  6218. svr.stop();
  6219. listen_thread.join();
  6220. ASSERT_FALSE(svr.is_running());
  6221. });
  6222. svr.wait_until_ready();
  6223. Client cli("localhost", PORT);
  6224. cli.set_keep_alive(true);
  6225. cli.set_read_timeout(std::chrono::seconds(1));
  6226. auto resa = cli.Get("/a");
  6227. ASSERT_FALSE(resa);
  6228. EXPECT_EQ(Error::Read, resa.error());
  6229. auto resb = cli.Get("/b");
  6230. ASSERT_TRUE(resb);
  6231. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6232. EXPECT_EQ("b", resb->body);
  6233. }
  6234. TEST(KeepAliveTest, MaxCount) {
  6235. size_t keep_alive_max_count = 3;
  6236. Server svr;
  6237. svr.set_keep_alive_max_count(keep_alive_max_count);
  6238. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6239. res.set_content("Hello World!", "text/plain");
  6240. });
  6241. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6242. auto se = detail::scope_exit([&] {
  6243. svr.stop();
  6244. listen_thread.join();
  6245. ASSERT_FALSE(svr.is_running());
  6246. });
  6247. svr.wait_until_ready();
  6248. Client cli(HOST, PORT);
  6249. cli.set_keep_alive(true);
  6250. for (size_t i = 0; i < 5; i++) {
  6251. auto result = cli.Get("/hi");
  6252. ASSERT_TRUE(result);
  6253. EXPECT_EQ(StatusCode::OK_200, result->status);
  6254. if (i == keep_alive_max_count - 1) {
  6255. EXPECT_EQ("close", result->get_header_value("Connection"));
  6256. } else {
  6257. EXPECT_FALSE(result->has_header("Connection"));
  6258. }
  6259. }
  6260. }
  6261. TEST(KeepAliveTest, Issue1041) {
  6262. Server svr;
  6263. svr.set_keep_alive_timeout(3);
  6264. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6265. res.set_content("Hello World!", "text/plain");
  6266. });
  6267. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6268. auto 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 cli(HOST, PORT);
  6275. cli.set_keep_alive(true);
  6276. auto result = cli.Get("/hi");
  6277. ASSERT_TRUE(result);
  6278. EXPECT_EQ(StatusCode::OK_200, result->status);
  6279. std::this_thread::sleep_for(std::chrono::seconds(5));
  6280. result = cli.Get("/hi");
  6281. ASSERT_TRUE(result);
  6282. EXPECT_EQ(StatusCode::OK_200, result->status);
  6283. }
  6284. TEST(KeepAliveTest, Issue1959) {
  6285. Server svr;
  6286. svr.set_keep_alive_timeout(5);
  6287. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6288. res.set_content("a", "text/plain");
  6289. });
  6290. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6291. auto se = detail::scope_exit([&] {
  6292. if (!svr.is_running()) return;
  6293. svr.stop();
  6294. listen_thread.join();
  6295. ASSERT_FALSE(svr.is_running());
  6296. });
  6297. svr.wait_until_ready();
  6298. Client cli("localhost", PORT);
  6299. cli.set_keep_alive(true);
  6300. using namespace std::chrono;
  6301. auto start = steady_clock::now();
  6302. cli.Get("/a");
  6303. svr.stop();
  6304. listen_thread.join();
  6305. auto end = steady_clock::now();
  6306. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6307. EXPECT_LT(elapsed, 5000);
  6308. }
  6309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6310. TEST(KeepAliveTest, SSLClientReconnection) {
  6311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6312. ASSERT_TRUE(svr.is_valid());
  6313. svr.set_keep_alive_timeout(1);
  6314. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6315. res.set_content("Hello World!", "text/plain");
  6316. });
  6317. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6318. auto se = detail::scope_exit([&] {
  6319. svr.stop();
  6320. listen_thread.join();
  6321. ASSERT_FALSE(svr.is_running());
  6322. });
  6323. svr.wait_until_ready();
  6324. SSLClient cli(HOST, PORT);
  6325. cli.enable_server_certificate_verification(false);
  6326. cli.set_keep_alive(true);
  6327. auto result = cli.Get("/hi");
  6328. ASSERT_TRUE(result);
  6329. EXPECT_EQ(StatusCode::OK_200, result->status);
  6330. result = cli.Get("/hi");
  6331. ASSERT_TRUE(result);
  6332. EXPECT_EQ(StatusCode::OK_200, result->status);
  6333. std::this_thread::sleep_for(std::chrono::seconds(2));
  6334. // Recoonect
  6335. result = cli.Get("/hi");
  6336. ASSERT_TRUE(result);
  6337. EXPECT_EQ(StatusCode::OK_200, result->status);
  6338. result = cli.Get("/hi");
  6339. ASSERT_TRUE(result);
  6340. EXPECT_EQ(StatusCode::OK_200, result->status);
  6341. }
  6342. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6344. ASSERT_TRUE(svr.is_valid());
  6345. svr.set_keep_alive_timeout(1);
  6346. std::string content = "reconnect";
  6347. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6348. res.set_content("Hello World!", "text/plain");
  6349. });
  6350. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6351. auto se = detail::scope_exit([&] {
  6352. svr.stop();
  6353. listen_thread.join();
  6354. ASSERT_FALSE(svr.is_running());
  6355. });
  6356. svr.wait_until_ready();
  6357. SSLClient cli(HOST, PORT);
  6358. cli.enable_server_certificate_verification(false);
  6359. cli.set_keep_alive(true);
  6360. auto result = cli.Post(
  6361. "/hi", content.size(),
  6362. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6363. sink.write(content.c_str(), content.size());
  6364. return true;
  6365. },
  6366. "text/plain");
  6367. ASSERT_TRUE(result);
  6368. EXPECT_EQ(200, result->status);
  6369. std::this_thread::sleep_for(std::chrono::seconds(2));
  6370. // Recoonect
  6371. result = cli.Post(
  6372. "/hi", content.size(),
  6373. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6374. sink.write(content.c_str(), content.size());
  6375. return true;
  6376. },
  6377. "text/plain");
  6378. ASSERT_TRUE(result);
  6379. EXPECT_EQ(200, result->status);
  6380. result = cli.Post(
  6381. "/hi", content.size(),
  6382. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6383. sink.write(content.c_str(), content.size());
  6384. return true;
  6385. },
  6386. "text/plain");
  6387. ASSERT_TRUE(result);
  6388. EXPECT_EQ(200, result->status);
  6389. }
  6390. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6391. {
  6392. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6393. ASSERT_TRUE(svr.is_valid());
  6394. svr.Get("/sni", [&](const Request &req, Response &res) {
  6395. std::string expected;
  6396. if (req.ssl) {
  6397. if (const char *sni =
  6398. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6399. expected = sni;
  6400. }
  6401. }
  6402. EXPECT_EQ(expected, req.get_param_value("expected"));
  6403. res.set_content("ok", "text/plain");
  6404. });
  6405. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6406. auto se = detail::scope_exit([&] {
  6407. svr.stop();
  6408. listen_thread.join();
  6409. ASSERT_FALSE(svr.is_running());
  6410. });
  6411. svr.wait_until_ready();
  6412. {
  6413. SSLClient cli("localhost", PORT);
  6414. cli.enable_server_certificate_verification(false);
  6415. auto res = cli.Get("/sni?expected=localhost");
  6416. ASSERT_TRUE(res);
  6417. }
  6418. {
  6419. SSLClient cli("::1", PORT);
  6420. cli.enable_server_certificate_verification(false);
  6421. auto res = cli.Get("/sni?expected=");
  6422. ASSERT_TRUE(res);
  6423. }
  6424. }
  6425. }
  6426. #endif
  6427. TEST(ClientProblemDetectionTest, ContentProvider) {
  6428. Server svr;
  6429. size_t content_length = 1024 * 1024;
  6430. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6431. res.set_content_provider(
  6432. content_length, "text/plain",
  6433. [&](size_t offset, size_t length, DataSink &sink) {
  6434. auto out_len = std::min(length, static_cast<size_t>(1024));
  6435. std::string out(out_len, '@');
  6436. sink.write(out.data(), out_len);
  6437. return offset < 4096;
  6438. },
  6439. [](bool success) { ASSERT_FALSE(success); });
  6440. });
  6441. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6442. res.set_content_provider(
  6443. 0, "text/plain",
  6444. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6445. EXPECT_TRUE(false);
  6446. return true;
  6447. },
  6448. [](bool success) { ASSERT_FALSE(success); });
  6449. });
  6450. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6451. auto se = detail::scope_exit([&] {
  6452. svr.stop();
  6453. listen_thread.join();
  6454. ASSERT_FALSE(svr.is_running());
  6455. });
  6456. svr.wait_until_ready();
  6457. Client cli("localhost", PORT);
  6458. {
  6459. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6460. size_t /*data_length*/) { return false; });
  6461. ASSERT_FALSE(res);
  6462. }
  6463. {
  6464. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6465. size_t /*data_length*/) { return false; });
  6466. ASSERT_TRUE(res);
  6467. }
  6468. }
  6469. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6470. Server svr;
  6471. svr.set_error_handler([](Request const &, Response &res) -> void {
  6472. res.set_chunked_content_provider(
  6473. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6474. sink.os << "hello";
  6475. sink.os << "world";
  6476. sink.done();
  6477. return true;
  6478. });
  6479. });
  6480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6481. auto se = detail::scope_exit([&] {
  6482. svr.stop();
  6483. listen_thread.join();
  6484. ASSERT_FALSE(svr.is_running());
  6485. });
  6486. svr.wait_until_ready();
  6487. Client cli("localhost", PORT);
  6488. auto res = cli.Get("/");
  6489. ASSERT_TRUE(res);
  6490. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6491. EXPECT_EQ("helloworld", res->body);
  6492. }
  6493. TEST(LongPollingTest, ClientCloseDetection) {
  6494. Server svr;
  6495. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6496. res.set_chunked_content_provider(
  6497. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6498. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6499. sink.os << "hello";
  6500. auto count = 10;
  6501. while (count > 0 && sink.is_writable()) {
  6502. this_thread::sleep_for(chrono::milliseconds(10));
  6503. count--;
  6504. }
  6505. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6506. return true;
  6507. });
  6508. });
  6509. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6510. auto se = detail::scope_exit([&] {
  6511. svr.stop();
  6512. listen_thread.join();
  6513. ASSERT_FALSE(svr.is_running());
  6514. });
  6515. svr.wait_until_ready();
  6516. Client cli("localhost", PORT);
  6517. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6518. EXPECT_EQ("hello", string(data, data_length));
  6519. return false; // close the socket immediately.
  6520. });
  6521. ASSERT_FALSE(res);
  6522. }
  6523. TEST(GetWithParametersTest, GetWithParameters) {
  6524. Server svr;
  6525. svr.Get("/", [&](const Request &req, Response &) {
  6526. EXPECT_EQ("world", req.get_param_value("hello"));
  6527. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6528. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6529. });
  6530. svr.Get("/params", [&](const Request &req, Response &) {
  6531. EXPECT_EQ("world", req.get_param_value("hello"));
  6532. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6533. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6534. });
  6535. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6536. EXPECT_EQ("resource-id", req.matches[1]);
  6537. EXPECT_EQ("foo", req.get_param_value("param1"));
  6538. EXPECT_EQ("bar", req.get_param_value("param2"));
  6539. });
  6540. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6541. EXPECT_EQ("user-id", req.path_params.at("id"));
  6542. EXPECT_EQ("foo", req.get_param_value("param1"));
  6543. EXPECT_EQ("bar", req.get_param_value("param2"));
  6544. });
  6545. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6546. auto se = detail::scope_exit([&] {
  6547. svr.stop();
  6548. listen_thread.join();
  6549. ASSERT_FALSE(svr.is_running());
  6550. });
  6551. svr.wait_until_ready();
  6552. {
  6553. Client cli(HOST, PORT);
  6554. Params params;
  6555. params.emplace("hello", "world");
  6556. params.emplace("hello2", "world2");
  6557. params.emplace("hello3", "world3");
  6558. auto res = cli.Get("/", params, Headers{});
  6559. ASSERT_TRUE(res);
  6560. EXPECT_EQ(StatusCode::OK_200, res->status);
  6561. }
  6562. {
  6563. Client cli(HOST, PORT);
  6564. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6565. ASSERT_TRUE(res);
  6566. EXPECT_EQ(StatusCode::OK_200, res->status);
  6567. }
  6568. {
  6569. Client cli(HOST, PORT);
  6570. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6571. ASSERT_TRUE(res);
  6572. EXPECT_EQ(StatusCode::OK_200, res->status);
  6573. }
  6574. {
  6575. Client cli(HOST, PORT);
  6576. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6577. ASSERT_TRUE(res);
  6578. EXPECT_EQ(StatusCode::OK_200, res->status);
  6579. }
  6580. }
  6581. TEST(GetWithParametersTest, GetWithParameters2) {
  6582. Server svr;
  6583. svr.Get("/", [&](const Request &req, Response &res) {
  6584. auto text = req.get_param_value("hello");
  6585. res.set_content(text, "text/plain");
  6586. });
  6587. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6588. auto se = detail::scope_exit([&] {
  6589. svr.stop();
  6590. listen_thread.join();
  6591. ASSERT_FALSE(svr.is_running());
  6592. });
  6593. svr.wait_until_ready();
  6594. Client cli("localhost", PORT);
  6595. Params params;
  6596. params.emplace("hello", "world");
  6597. std::string body;
  6598. auto res = cli.Get("/", params, Headers{},
  6599. [&](const char *data, size_t data_length) {
  6600. body.append(data, data_length);
  6601. return true;
  6602. });
  6603. ASSERT_TRUE(res);
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. EXPECT_EQ("world", body);
  6606. }
  6607. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6608. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6609. auto host = "httpbin.org";
  6610. auto path = std::string{"/range/32"};
  6611. #else
  6612. auto host = "nghttp2.org";
  6613. auto path = std::string{"/httpbin/range/32"};
  6614. #endif
  6615. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6616. SSLClient cli(host);
  6617. #else
  6618. Client cli(host);
  6619. #endif
  6620. cli.set_default_headers({make_range_header({{1, 10}})});
  6621. cli.set_connection_timeout(5);
  6622. {
  6623. auto res = cli.Get(path);
  6624. ASSERT_TRUE(res);
  6625. EXPECT_EQ("bcdefghijk", res->body);
  6626. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6627. }
  6628. {
  6629. auto res = cli.Get(path);
  6630. ASSERT_TRUE(res);
  6631. EXPECT_EQ("bcdefghijk", res->body);
  6632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6633. }
  6634. }
  6635. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6636. Server svr;
  6637. svr.set_default_headers({{"Hello", "World"}});
  6638. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6639. res.set_content("ok", "text/plain");
  6640. });
  6641. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6642. auto se = detail::scope_exit([&] {
  6643. svr.stop();
  6644. listen_thread.join();
  6645. ASSERT_FALSE(svr.is_running());
  6646. });
  6647. svr.wait_until_ready();
  6648. Client cli("localhost", PORT);
  6649. auto res = cli.Get("/");
  6650. ASSERT_TRUE(res);
  6651. EXPECT_EQ(StatusCode::OK_200, res->status);
  6652. EXPECT_EQ("ok", res->body);
  6653. EXPECT_EQ("World", res->get_header_value("Hello"));
  6654. }
  6655. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6656. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6658. ASSERT_TRUE(svr.is_valid());
  6659. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6660. std::this_thread::sleep_for(std::chrono::seconds(2));
  6661. res.set_content("a", "text/plain");
  6662. });
  6663. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6664. res.set_content("b", "text/plain");
  6665. });
  6666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6667. auto se = detail::scope_exit([&] {
  6668. svr.stop();
  6669. listen_thread.join();
  6670. ASSERT_FALSE(svr.is_running());
  6671. });
  6672. svr.wait_until_ready();
  6673. SSLClient cli("localhost", PORT);
  6674. cli.enable_server_certificate_verification(false);
  6675. cli.set_keep_alive(true);
  6676. cli.set_read_timeout(std::chrono::seconds(1));
  6677. auto resa = cli.Get("/a");
  6678. ASSERT_TRUE(!resa);
  6679. EXPECT_EQ(Error::Read, resa.error());
  6680. auto resb = cli.Get("/b");
  6681. ASSERT_TRUE(resb);
  6682. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6683. EXPECT_EQ("b", resb->body);
  6684. }
  6685. #endif
  6686. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6687. protected:
  6688. ServerTestWithAI_PASSIVE()
  6689. : cli_(HOST, PORT)
  6690. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6691. ,
  6692. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6693. #endif
  6694. {
  6695. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6696. cli_.enable_server_certificate_verification(false);
  6697. #endif
  6698. }
  6699. virtual void SetUp() {
  6700. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6701. res.set_content("Hello World!", "text/plain");
  6702. });
  6703. t_ = thread(
  6704. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6705. svr_.wait_until_ready();
  6706. }
  6707. virtual void TearDown() {
  6708. svr_.stop();
  6709. t_.join();
  6710. }
  6711. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6712. SSLClient cli_;
  6713. SSLServer svr_;
  6714. #else
  6715. Client cli_;
  6716. Server svr_;
  6717. #endif
  6718. thread t_;
  6719. };
  6720. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6721. auto res = cli_.Get("/hi");
  6722. ASSERT_TRUE(res);
  6723. EXPECT_EQ(StatusCode::OK_200, res->status);
  6724. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6725. EXPECT_EQ("Hello World!", res->body);
  6726. }
  6727. class ServerUpDownTest : public ::testing::Test {
  6728. protected:
  6729. ServerUpDownTest() : cli_(HOST, PORT) {}
  6730. virtual void SetUp() {
  6731. t_ = thread([&]() {
  6732. svr_.bind_to_any_port(HOST);
  6733. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6734. ASSERT_TRUE(svr_.listen_after_bind());
  6735. });
  6736. svr_.wait_until_ready();
  6737. }
  6738. virtual void TearDown() {
  6739. svr_.stop();
  6740. t_.join();
  6741. }
  6742. Client cli_;
  6743. Server svr_;
  6744. thread t_;
  6745. };
  6746. TEST_F(ServerUpDownTest, QuickStartStop) {
  6747. // Should not crash, especially when run with
  6748. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6749. }
  6750. class PayloadMaxLengthTest : public ::testing::Test {
  6751. protected:
  6752. PayloadMaxLengthTest()
  6753. : cli_(HOST, PORT)
  6754. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6755. ,
  6756. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6757. #endif
  6758. {
  6759. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6760. cli_.enable_server_certificate_verification(false);
  6761. #endif
  6762. }
  6763. virtual void SetUp() {
  6764. svr_.set_payload_max_length(8);
  6765. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6766. res.set_content("test", "text/plain");
  6767. });
  6768. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6769. svr_.wait_until_ready();
  6770. }
  6771. virtual void TearDown() {
  6772. svr_.stop();
  6773. t_.join();
  6774. }
  6775. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6776. SSLClient cli_;
  6777. SSLServer svr_;
  6778. #else
  6779. Client cli_;
  6780. Server svr_;
  6781. #endif
  6782. thread t_;
  6783. };
  6784. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6785. auto res = cli_.Post("/test", "123456789", "text/plain");
  6786. ASSERT_TRUE(res);
  6787. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6788. res = cli_.Post("/test", "12345678", "text/plain");
  6789. ASSERT_TRUE(res);
  6790. EXPECT_EQ(StatusCode::OK_200, res->status);
  6791. }
  6792. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6793. // Test chunked encoding with payload exceeding the 8-byte limit
  6794. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6795. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6796. ASSERT_TRUE(res);
  6797. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6798. }
  6799. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6800. // Test chunked encoding with payload within the 8-byte limit
  6801. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6802. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6803. ASSERT_TRUE(res);
  6804. EXPECT_EQ(StatusCode::OK_200, res->status);
  6805. }
  6806. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6807. // Test using send_request to send chunked data exceeding payload limit
  6808. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6809. "Host: " +
  6810. std::string(HOST) + ":" + std::to_string(PORT) +
  6811. "\r\n"
  6812. "Transfer-Encoding: chunked\r\n"
  6813. "Connection: close\r\n"
  6814. "\r\n"
  6815. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6816. "0123456789\r\n"
  6817. "0\r\n" // End chunk
  6818. "\r\n";
  6819. std::string response;
  6820. bool result = send_request(1, chunked_request, &response);
  6821. if (!result) {
  6822. // If send_request fails, it might be because the server closed the
  6823. // connection due to payload limit enforcement, which is acceptable
  6824. SUCCEED()
  6825. << "Server rejected oversized chunked request (connection closed)";
  6826. } else {
  6827. // If we got a response, check if it's an error response or connection was
  6828. // closed early Short response length indicates connection was closed due to
  6829. // payload limit
  6830. if (response.length() <= 10) {
  6831. SUCCEED() << "Server closed connection for oversized chunked request";
  6832. } else {
  6833. // Check for error status codes
  6834. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6835. response.find("Payload Too Large") != std::string::npos ||
  6836. response.find("400") != std::string::npos);
  6837. }
  6838. }
  6839. }
  6840. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6841. // Test request without Content-Length header exceeding payload limit
  6842. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6843. "Host: " +
  6844. std::string(HOST) + ":" +
  6845. std::to_string(PORT) +
  6846. "\r\n"
  6847. "Connection: close\r\n"
  6848. "\r\n";
  6849. // Add payload exceeding the 8-byte limit
  6850. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6851. request_without_content_length += large_payload;
  6852. std::string response;
  6853. bool result = send_request(1, request_without_content_length, &response);
  6854. if (!result) {
  6855. // If send_request fails, server likely closed connection due to payload
  6856. // limit
  6857. SUCCEED() << "Server rejected oversized request without Content-Length "
  6858. "(connection closed)";
  6859. } else {
  6860. // Check if server responded with error or closed connection early
  6861. if (response.length() <= 10) {
  6862. SUCCEED() << "Server closed connection for oversized request without "
  6863. "Content-Length";
  6864. } else {
  6865. // Check for error status codes
  6866. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6867. response.find("Payload Too Large") != std::string::npos ||
  6868. response.find("400") != std::string::npos);
  6869. }
  6870. }
  6871. }
  6872. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6873. // Test request without Content-Length header within payload limit
  6874. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6875. "Host: " +
  6876. std::string(HOST) + ":" +
  6877. std::to_string(PORT) +
  6878. "\r\n"
  6879. "Connection: close\r\n"
  6880. "\r\n";
  6881. // Add payload within the 8-byte limit
  6882. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6883. request_without_content_length += small_payload;
  6884. std::string response;
  6885. bool result = send_request(1, request_without_content_length, &response);
  6886. // For requests without Content-Length, the server may have different behavior
  6887. // The key is that it should not reject due to payload limit for small
  6888. // payloads
  6889. if (result) {
  6890. // Check for any HTTP response (success or error, but not connection closed)
  6891. if (response.length() > 10) {
  6892. SUCCEED()
  6893. << "Server processed request without Content-Length within limit";
  6894. } else {
  6895. // Short response might indicate connection closed, which is acceptable
  6896. SUCCEED() << "Server closed connection for request without "
  6897. "Content-Length (acceptable behavior)";
  6898. }
  6899. } else {
  6900. // Connection failure might be due to protocol requirements
  6901. SUCCEED() << "Connection issue with request without Content-Length "
  6902. "(environment-specific)";
  6903. }
  6904. }
  6905. class LargePayloadMaxLengthTest : public ::testing::Test {
  6906. protected:
  6907. LargePayloadMaxLengthTest()
  6908. : cli_(HOST, PORT)
  6909. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6910. ,
  6911. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6912. #endif
  6913. {
  6914. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6915. cli_.enable_server_certificate_verification(false);
  6916. #endif
  6917. }
  6918. virtual void SetUp() {
  6919. // Set 10MB payload limit
  6920. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6921. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6922. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6923. res.set_content("Large payload test", "text/plain");
  6924. });
  6925. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6926. svr_.wait_until_ready();
  6927. }
  6928. virtual void TearDown() {
  6929. svr_.stop();
  6930. t_.join();
  6931. }
  6932. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6933. SSLClient cli_;
  6934. SSLServer svr_;
  6935. #else
  6936. Client cli_;
  6937. Server svr_;
  6938. #endif
  6939. thread t_;
  6940. };
  6941. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6942. // Test chunked encoding with payload within 10MB limit
  6943. std::string medium_payload(5 * 1024 * 1024,
  6944. 'A'); // 5MB payload, within 10MB limit
  6945. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6946. ASSERT_TRUE(res);
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. }
  6949. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6950. // Test chunked encoding with payload exceeding 10MB limit
  6951. std::string large_payload(12 * 1024 * 1024,
  6952. 'B'); // 12MB payload, exceeds 10MB limit
  6953. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6954. ASSERT_TRUE(res);
  6955. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6956. }
  6957. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6958. // Test request without Content-Length header within 10MB limit
  6959. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6960. "Host: " +
  6961. std::string(HOST) + ":" +
  6962. std::to_string(PORT) +
  6963. "\r\n"
  6964. "Connection: close\r\n"
  6965. "\r\n";
  6966. // Add 1MB payload (within 10MB limit)
  6967. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6968. request_without_content_length += medium_payload;
  6969. std::string response;
  6970. bool result = send_request(5, request_without_content_length, &response);
  6971. if (result) {
  6972. // Should get a proper HTTP response for payloads within limit
  6973. if (response.length() > 10) {
  6974. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6975. "10MB limit";
  6976. } else {
  6977. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6978. "Content-Length)";
  6979. }
  6980. } else {
  6981. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6982. }
  6983. }
  6984. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6985. // Test request without Content-Length header exceeding 10MB limit
  6986. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6987. "Host: " +
  6988. std::string(HOST) + ":" +
  6989. std::to_string(PORT) +
  6990. "\r\n"
  6991. "Connection: close\r\n"
  6992. "\r\n";
  6993. // Add 12MB payload (exceeds 10MB limit)
  6994. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6995. request_without_content_length += large_payload;
  6996. std::string response;
  6997. bool result = send_request(10, request_without_content_length, &response);
  6998. if (!result) {
  6999. // Server should close connection due to payload limit
  7000. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7001. "(connection closed)";
  7002. } else {
  7003. // Check for error response
  7004. if (response.length() <= 10) {
  7005. SUCCEED()
  7006. << "Server closed connection for 12MB request exceeding 10MB limit";
  7007. } else {
  7008. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7009. response.find("Payload Too Large") != std::string::npos ||
  7010. response.find("400") != std::string::npos);
  7011. }
  7012. }
  7013. }
  7014. TEST(HostAndPortPropertiesTest, NoSSL) {
  7015. httplib::Client cli("www.google.com", 1234);
  7016. ASSERT_EQ("www.google.com", cli.host());
  7017. ASSERT_EQ(1234, cli.port());
  7018. }
  7019. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7020. httplib::Client cli("www.google.com:1234");
  7021. ASSERT_EQ("www.google.com", cli.host());
  7022. ASSERT_EQ(1234, cli.port());
  7023. }
  7024. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7025. TEST(HostAndPortPropertiesTest, SSL) {
  7026. httplib::SSLClient cli("www.google.com");
  7027. ASSERT_EQ("www.google.com", cli.host());
  7028. ASSERT_EQ(443, cli.port());
  7029. }
  7030. #endif
  7031. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7032. TEST(SSLClientTest, UpdateCAStore) {
  7033. httplib::SSLClient httplib_client("www.google.com");
  7034. auto ca_store_1 = X509_STORE_new();
  7035. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7036. nullptr);
  7037. httplib_client.set_ca_cert_store(ca_store_1);
  7038. auto ca_store_2 = X509_STORE_new();
  7039. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7040. nullptr);
  7041. httplib_client.set_ca_cert_store(ca_store_2);
  7042. }
  7043. TEST(SSLClientTest, ServerNameIndication_Online) {
  7044. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7045. auto host = "httpbin.org";
  7046. auto path = std::string{"/get"};
  7047. #else
  7048. auto host = "nghttp2.org";
  7049. auto path = std::string{"/httpbin/get"};
  7050. #endif
  7051. SSLClient cli(host, 443);
  7052. auto res = cli.Get(path);
  7053. ASSERT_TRUE(res);
  7054. ASSERT_EQ(StatusCode::OK_200, res->status);
  7055. }
  7056. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7057. // Use a site that will cause SSL verification failure due to self-signed cert
  7058. SSLClient cli("self-signed.badssl.com", 443);
  7059. cli.enable_server_certificate_verification(true);
  7060. auto res = cli.Get("/");
  7061. ASSERT_TRUE(!res);
  7062. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7063. // For SSL server verification errors, ssl_error should be 0, only
  7064. // ssl_openssl_error should be set
  7065. EXPECT_EQ(0, res.ssl_error());
  7066. // Verify OpenSSL error is captured for SSLServerVerification
  7067. // This occurs when SSL_get_verify_result() returns a verification failure
  7068. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7069. res.ssl_openssl_error());
  7070. }
  7071. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7072. // Use a site where hostname doesn't match the certificate
  7073. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7074. SSLClient cli("wrong.host.badssl.com", 443);
  7075. cli.enable_server_certificate_verification(true);
  7076. cli.enable_server_hostname_verification(true);
  7077. auto res = cli.Get("/");
  7078. ASSERT_TRUE(!res);
  7079. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7080. // For SSL hostname verification errors, ssl_error should be 0, only
  7081. // ssl_openssl_error should be set
  7082. EXPECT_EQ(0, res.ssl_error());
  7083. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7084. // This occurs when verify_host() fails due to hostname mismatch
  7085. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7086. res.ssl_openssl_error());
  7087. }
  7088. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7089. Client cli("https://google.com");
  7090. auto res = cli.Get("/");
  7091. ASSERT_TRUE(res);
  7092. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7093. }
  7094. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7095. SSLClient cli("google.com");
  7096. cli.set_ca_cert_path(CA_CERT_FILE);
  7097. auto res = cli.Get("/");
  7098. ASSERT_TRUE(res);
  7099. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7100. }
  7101. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7102. SSLClient cli("google.com");
  7103. cli.enable_server_certificate_verification(true);
  7104. cli.set_ca_cert_path("hello");
  7105. auto res = cli.Get("/");
  7106. ASSERT_TRUE(!res);
  7107. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7108. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7109. // should be set
  7110. EXPECT_EQ(0, res.ssl_error());
  7111. // Verify OpenSSL error is captured for SSLLoadingCerts
  7112. // This error occurs when SSL_CTX_load_verify_locations() fails
  7113. // > openssl errstr 0x80000002
  7114. // error:80000002:system library::No such file or directory
  7115. // > openssl errstr 0xA000126
  7116. // error:0A000126:SSL routines::unexpected eof while reading
  7117. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7118. res.ssl_openssl_error() == 0xA000126);
  7119. }
  7120. TEST(SSLClientTest, ServerCertificateVerification4) {
  7121. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7122. ASSERT_TRUE(svr.is_valid());
  7123. svr.Get("/test", [&](const Request &, Response &res) {
  7124. res.set_content("test", "text/plain");
  7125. svr.stop();
  7126. ASSERT_TRUE(true);
  7127. });
  7128. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7129. auto se = detail::scope_exit([&] {
  7130. t.join();
  7131. ASSERT_FALSE(svr.is_running());
  7132. });
  7133. svr.wait_until_ready();
  7134. SSLClient cli("127.0.0.1", PORT);
  7135. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7136. cli.enable_server_certificate_verification(true);
  7137. cli.set_connection_timeout(30);
  7138. auto res = cli.Get("/test");
  7139. ASSERT_TRUE(res);
  7140. ASSERT_EQ(StatusCode::OK_200, res->status);
  7141. }
  7142. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7143. std::string cert;
  7144. read_file(CA_CERT_FILE, cert);
  7145. SSLClient cli("google.com");
  7146. cli.load_ca_cert_store(cert.data(), cert.size());
  7147. const auto res = cli.Get("/");
  7148. ASSERT_TRUE(res);
  7149. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7150. }
  7151. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7152. // clang-format off
  7153. static constexpr char cert[] =
  7154. "GlobalSign Root CA\n"
  7155. "==================\n"
  7156. "-----BEGIN CERTIFICATE-----\n"
  7157. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7158. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7159. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7160. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7161. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7162. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7163. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7164. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7165. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7166. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7167. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7168. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7169. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7170. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7171. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7172. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7173. "-----END CERTIFICATE-----\n";
  7174. // clang-format on
  7175. SSLClient cli("google.com");
  7176. cli.load_ca_cert_store(cert, sizeof(cert));
  7177. const auto res = cli.Get("/");
  7178. ASSERT_TRUE(res);
  7179. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7180. }
  7181. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7182. SSLClient cli("www.youtube.com");
  7183. cli.set_ca_cert_path(CA_CERT_FILE);
  7184. cli.enable_server_certificate_verification(true);
  7185. cli.set_follow_location(true);
  7186. auto res = cli.Get("/");
  7187. ASSERT_TRUE(res);
  7188. ASSERT_EQ(StatusCode::OK_200, res->status);
  7189. }
  7190. TEST(SSLClientTest, Issue2004_Online) {
  7191. Client client("https://google.com");
  7192. client.set_follow_location(true);
  7193. auto res = client.Get("/");
  7194. ASSERT_TRUE(res);
  7195. ASSERT_EQ(StatusCode::OK_200, res->status);
  7196. auto body = res->body;
  7197. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7198. }
  7199. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7200. // Create SSLClient with invalid cert/key to make is_valid() return false
  7201. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7202. "nonexistent_key.pem");
  7203. // is_valid() should be false due to cert loading failure
  7204. ASSERT_FALSE(cli.is_valid());
  7205. auto res = cli.Get("/");
  7206. ASSERT_FALSE(res);
  7207. EXPECT_EQ(Error::SSLConnection, res.error());
  7208. }
  7209. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7210. // Test for Issue #2251: SSL error not properly reported when client cert
  7211. // and key paths are swapped or mismatched
  7212. // This simulates the scenario where user accidentally swaps the cert and key
  7213. // files
  7214. // Using client cert file as private key and vice versa (completely wrong)
  7215. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7216. // Should fail validation due to cert/key mismatch
  7217. ASSERT_FALSE(cli.is_valid());
  7218. // Attempt to make a request should fail with proper error
  7219. auto res = cli.Get("/");
  7220. ASSERT_FALSE(res);
  7221. EXPECT_EQ(Error::SSLConnection, res.error());
  7222. // SSL error should be recorded in the Result object (this is the key fix for
  7223. // Issue #2251)
  7224. auto openssl_error = res.ssl_openssl_error();
  7225. EXPECT_NE(0u, openssl_error);
  7226. }
  7227. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7228. // Another variant: using valid file paths but with mismatched cert/key pair
  7229. // This tests the case where files exist but contain incompatible key material
  7230. // Using client cert with wrong key (cert2 key)
  7231. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7232. // Should fail validation
  7233. ASSERT_FALSE(cli.is_valid());
  7234. auto res = cli.Get("/");
  7235. ASSERT_FALSE(res);
  7236. // Must report error properly, not appear as success
  7237. EXPECT_EQ(Error::SSLConnection, res.error());
  7238. // OpenSSL error should be captured in Result
  7239. EXPECT_NE(0u, res.ssl_openssl_error());
  7240. }
  7241. #if 0
  7242. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7243. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7244. ASSERT_TRUE(cli != nullptr);
  7245. cli->set_address_family(AF_INET6);
  7246. cli->set_interface("en0");
  7247. auto res = cli->Get("/get");
  7248. ASSERT_TRUE(res);
  7249. ASSERT_EQ(StatusCode::OK_200, res->status);
  7250. }
  7251. #endif
  7252. void ClientCertPresent(
  7253. const std::string &client_cert_file,
  7254. const std::string &client_private_key_file,
  7255. const std::string &client_encrypted_private_key_pass = std::string()) {
  7256. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7257. CLIENT_CA_CERT_DIR);
  7258. ASSERT_TRUE(svr.is_valid());
  7259. svr.Get("/test", [&](const Request &req, Response &res) {
  7260. res.set_content("test", "text/plain");
  7261. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7262. ASSERT_TRUE(peer_cert != nullptr);
  7263. auto subject_name = X509_get_subject_name(peer_cert);
  7264. ASSERT_TRUE(subject_name != nullptr);
  7265. std::string common_name;
  7266. {
  7267. char name[BUFSIZ];
  7268. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7269. name, sizeof(name));
  7270. common_name.assign(name, static_cast<size_t>(name_len));
  7271. }
  7272. EXPECT_EQ("Common Name", common_name);
  7273. X509_free(peer_cert);
  7274. });
  7275. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7276. auto se = detail::scope_exit([&] {
  7277. svr.stop();
  7278. t.join();
  7279. ASSERT_FALSE(svr.is_running());
  7280. });
  7281. svr.wait_until_ready();
  7282. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7283. client_encrypted_private_key_pass);
  7284. cli.enable_server_certificate_verification(false);
  7285. cli.set_connection_timeout(30);
  7286. auto res = cli.Get("/test");
  7287. ASSERT_TRUE(res);
  7288. ASSERT_EQ(StatusCode::OK_200, res->status);
  7289. }
  7290. TEST(SSLClientServerTest, ClientCertPresent) {
  7291. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7292. }
  7293. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7294. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7295. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7296. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7297. }
  7298. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7299. void MemoryClientCertPresent(
  7300. const std::string &client_cert_file,
  7301. const std::string &client_private_key_file,
  7302. const std::string &client_encrypted_private_key_pass = std::string()) {
  7303. auto f = fopen(SERVER_CERT_FILE, "r+");
  7304. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7305. fclose(f);
  7306. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7307. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7308. fclose(f);
  7309. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7310. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7311. auto client_ca_cert_store = X509_STORE_new();
  7312. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7313. X509_free(client_cert);
  7314. fclose(f);
  7315. f = fopen(client_cert_file.c_str(), "r+");
  7316. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7317. fclose(f);
  7318. f = fopen(client_private_key_file.c_str(), "r+");
  7319. auto client_private_key = PEM_read_PrivateKey(
  7320. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7321. fclose(f);
  7322. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7323. ASSERT_TRUE(svr.is_valid());
  7324. svr.Get("/test", [&](const Request &req, Response &res) {
  7325. res.set_content("test", "text/plain");
  7326. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7327. ASSERT_TRUE(peer_cert != nullptr);
  7328. auto subject_name = X509_get_subject_name(peer_cert);
  7329. ASSERT_TRUE(subject_name != nullptr);
  7330. std::string common_name;
  7331. {
  7332. char name[BUFSIZ];
  7333. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7334. name, sizeof(name));
  7335. common_name.assign(name, static_cast<size_t>(name_len));
  7336. }
  7337. EXPECT_EQ("Common Name", common_name);
  7338. X509_free(peer_cert);
  7339. });
  7340. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7341. auto se = detail::scope_exit([&] {
  7342. svr.stop();
  7343. t.join();
  7344. ASSERT_FALSE(svr.is_running());
  7345. });
  7346. svr.wait_until_ready();
  7347. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7348. client_encrypted_private_key_pass);
  7349. cli.enable_server_certificate_verification(false);
  7350. cli.set_connection_timeout(30);
  7351. auto res = cli.Get("/test");
  7352. ASSERT_TRUE(res);
  7353. ASSERT_EQ(StatusCode::OK_200, res->status);
  7354. X509_free(server_cert);
  7355. EVP_PKEY_free(server_private_key);
  7356. X509_free(client_cert);
  7357. EVP_PKEY_free(client_private_key);
  7358. }
  7359. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7360. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7361. }
  7362. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7363. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7364. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7365. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7366. }
  7367. #endif
  7368. TEST(SSLClientServerTest, ClientCertMissing) {
  7369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7370. CLIENT_CA_CERT_DIR);
  7371. ASSERT_TRUE(svr.is_valid());
  7372. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7373. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7374. auto se = detail::scope_exit([&] {
  7375. svr.stop();
  7376. t.join();
  7377. ASSERT_FALSE(svr.is_running());
  7378. });
  7379. svr.wait_until_ready();
  7380. SSLClient cli(HOST, PORT);
  7381. cli.set_connection_timeout(30);
  7382. auto res = cli.Get("/test");
  7383. ASSERT_TRUE(!res);
  7384. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7385. // For SSL server verification errors, ssl_error should be 0, only
  7386. // ssl_openssl_error should be set
  7387. EXPECT_EQ(0, res.ssl_error());
  7388. // Verify OpenSSL error is captured for SSLServerVerification
  7389. // Note: This test may have different error codes depending on the exact
  7390. // verification failure
  7391. EXPECT_NE(0UL, res.ssl_openssl_error());
  7392. }
  7393. TEST(SSLClientServerTest, TrustDirOptional) {
  7394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7395. ASSERT_TRUE(svr.is_valid());
  7396. svr.Get("/test", [&](const Request &, Response &res) {
  7397. res.set_content("test", "text/plain");
  7398. });
  7399. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7400. auto se = detail::scope_exit([&] {
  7401. svr.stop();
  7402. t.join();
  7403. ASSERT_FALSE(svr.is_running());
  7404. });
  7405. svr.wait_until_ready();
  7406. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7407. cli.enable_server_certificate_verification(false);
  7408. cli.set_connection_timeout(30);
  7409. auto res = cli.Get("/test");
  7410. ASSERT_TRUE(res);
  7411. ASSERT_EQ(StatusCode::OK_200, res->status);
  7412. }
  7413. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7414. class NoListenSSLServer : public SSLServer {
  7415. public:
  7416. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7417. const char *client_ca_cert_file_path,
  7418. const char *client_ca_cert_dir_path = nullptr)
  7419. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7420. client_ca_cert_dir_path),
  7421. stop_(false) {}
  7422. std::atomic_bool stop_;
  7423. private:
  7424. bool process_and_close_socket(socket_t /*sock*/) override {
  7425. // Don't create SSL context
  7426. while (!stop_.load()) {
  7427. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7428. }
  7429. return true;
  7430. }
  7431. };
  7432. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7433. CLIENT_CA_CERT_FILE);
  7434. ASSERT_TRUE(svr.is_valid());
  7435. svr.Get("/test", [&](const Request &, Response &res) {
  7436. res.set_content("test", "text/plain");
  7437. });
  7438. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7439. auto se = detail::scope_exit([&] {
  7440. svr.stop_ = true;
  7441. svr.stop();
  7442. t.join();
  7443. ASSERT_FALSE(svr.is_running());
  7444. });
  7445. svr.wait_until_ready();
  7446. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7447. cli.enable_server_certificate_verification(false);
  7448. cli.set_connection_timeout(1);
  7449. auto res = cli.Get("/test");
  7450. ASSERT_TRUE(!res);
  7451. EXPECT_EQ(Error::SSLConnection, res.error());
  7452. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7453. }
  7454. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7455. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7456. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7457. SSL_CTX_set_options(&ssl_ctx,
  7458. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7459. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7460. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7461. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7462. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7463. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7464. "ECDHE-DSS-AES128-SHA256:"
  7465. "ECDHE-RSA-AES256-SHA256:"
  7466. "ECDHE-DSS-AES256-SHA256:";
  7467. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7468. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7469. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7470. SSL_FILETYPE_PEM) != 1) {
  7471. return false;
  7472. }
  7473. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7474. CLIENT_CA_CERT_DIR);
  7475. SSL_CTX_set_verify(
  7476. &ssl_ctx,
  7477. SSL_VERIFY_PEER |
  7478. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7479. nullptr);
  7480. return true;
  7481. };
  7482. SSLServer svr(setup_ssl_ctx_callback);
  7483. ASSERT_TRUE(svr.is_valid());
  7484. svr.Get("/test", [&](const Request &req, Response &res) {
  7485. res.set_content("test", "text/plain");
  7486. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7487. ASSERT_TRUE(peer_cert != nullptr);
  7488. auto subject_name = X509_get_subject_name(peer_cert);
  7489. ASSERT_TRUE(subject_name != nullptr);
  7490. std::string common_name;
  7491. {
  7492. char name[BUFSIZ];
  7493. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7494. name, sizeof(name));
  7495. common_name.assign(name, static_cast<size_t>(name_len));
  7496. }
  7497. EXPECT_EQ("Common Name", common_name);
  7498. X509_free(peer_cert);
  7499. });
  7500. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7501. auto se = detail::scope_exit([&] {
  7502. svr.stop();
  7503. t.join();
  7504. ASSERT_FALSE(svr.is_running());
  7505. });
  7506. svr.wait_until_ready();
  7507. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7508. cli.enable_server_certificate_verification(false);
  7509. cli.set_connection_timeout(30);
  7510. auto res = cli.Get("/test");
  7511. ASSERT_TRUE(res);
  7512. ASSERT_EQ(StatusCode::OK_200, res->status);
  7513. }
  7514. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7515. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7516. ASSERT_TRUE(svr.is_valid());
  7517. // Set up a handler to verify client certificate is present
  7518. bool client_cert_verified = false;
  7519. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7520. // Verify that client certificate was provided
  7521. client_cert_verified = true;
  7522. res.set_content("success", "text/plain");
  7523. });
  7524. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7525. auto se = detail::scope_exit([&] {
  7526. svr.stop();
  7527. t.join();
  7528. ASSERT_FALSE(svr.is_running());
  7529. });
  7530. svr.wait_until_ready();
  7531. // Client with certificate
  7532. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7533. cli.enable_server_certificate_verification(false);
  7534. cli.set_connection_timeout(30);
  7535. auto res = cli.Get("/test");
  7536. ASSERT_TRUE(res);
  7537. ASSERT_EQ(StatusCode::OK_200, res->status);
  7538. ASSERT_TRUE(client_cert_verified);
  7539. EXPECT_EQ("success", res->body);
  7540. }
  7541. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7542. // Test that when client CA cert file is provided,
  7543. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7544. // Create a server with client authentication
  7545. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7546. ASSERT_TRUE(svr.is_valid());
  7547. // We can't directly access the SSL_CTX from SSLServer to verify,
  7548. // but we can test that the server properly requests client certificates
  7549. // and accepts valid ones from the specified CA
  7550. bool handler_called = false;
  7551. svr.Get("/test", [&](const Request &req, Response &res) {
  7552. handler_called = true;
  7553. // Verify that a client certificate was provided
  7554. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7555. ASSERT_TRUE(peer_cert != nullptr);
  7556. // Get the issuer name
  7557. auto issuer_name = X509_get_issuer_name(peer_cert);
  7558. ASSERT_TRUE(issuer_name != nullptr);
  7559. char issuer_buf[256];
  7560. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7561. // The client certificate should be issued by our test CA
  7562. std::string issuer_str(issuer_buf);
  7563. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7564. X509_free(peer_cert);
  7565. res.set_content("authenticated", "text/plain");
  7566. });
  7567. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7568. auto se = detail::scope_exit([&] {
  7569. svr.stop();
  7570. t.join();
  7571. ASSERT_FALSE(svr.is_running());
  7572. });
  7573. svr.wait_until_ready();
  7574. // Connect with a client certificate issued by the CA
  7575. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7576. cli.enable_server_certificate_verification(false);
  7577. cli.set_connection_timeout(30);
  7578. auto res = cli.Get("/test");
  7579. ASSERT_TRUE(res);
  7580. ASSERT_EQ(StatusCode::OK_200, res->status);
  7581. ASSERT_TRUE(handler_called);
  7582. EXPECT_EQ("authenticated", res->body);
  7583. }
  7584. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7585. // Test 1: Valid CA file - no error should be recorded
  7586. {
  7587. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7588. CLIENT_CA_CERT_FILE);
  7589. ASSERT_TRUE(svr.is_valid());
  7590. // With valid setup, last_ssl_error should be 0
  7591. EXPECT_EQ(0, svr.ssl_last_error());
  7592. }
  7593. // Test 2: Invalid CA file content
  7594. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7595. {
  7596. // Create a temporary file with completely invalid content
  7597. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7598. {
  7599. std::ofstream ofs(temp_invalid_ca);
  7600. ofs << "This is not a certificate file at all\n";
  7601. ofs << "Just plain text content\n";
  7602. }
  7603. // Create server with invalid CA file
  7604. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7605. // Clean up temporary file
  7606. std::remove(temp_invalid_ca);
  7607. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7608. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7609. // Note: SSL_CTX_load_verify_locations typically fails first,
  7610. // but our error handling code path is still exercised
  7611. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7612. }
  7613. }
  7614. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7615. // Test SSL server using X509_STORE constructor with client CA certificates
  7616. // This test verifies that Phase 2 implementation correctly extracts CA names
  7617. // from an X509_STORE and sets them in the SSL context
  7618. // Load the CA certificate into memory
  7619. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7620. ASSERT_NE(nullptr, bio);
  7621. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7622. BIO_free(bio);
  7623. ASSERT_NE(nullptr, ca_cert);
  7624. // Create an X509_STORE and add the CA certificate
  7625. auto store = X509_STORE_new();
  7626. ASSERT_NE(nullptr, store);
  7627. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7628. // Load server certificate and private key
  7629. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7630. ASSERT_NE(nullptr, cert_bio);
  7631. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7632. BIO_free(cert_bio);
  7633. ASSERT_NE(nullptr, server_cert);
  7634. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7635. ASSERT_NE(nullptr, key_bio);
  7636. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7637. BIO_free(key_bio);
  7638. ASSERT_NE(nullptr, server_key);
  7639. // Create SSLServer with X509_STORE constructor
  7640. // Note: X509_STORE ownership is transferred to SSL_CTX
  7641. SSLServer svr(server_cert, server_key, store);
  7642. ASSERT_TRUE(svr.is_valid());
  7643. // No SSL error should be recorded for valid setup
  7644. EXPECT_EQ(0, svr.ssl_last_error());
  7645. // Set up server endpoints
  7646. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7647. res.set_content("ok", "text/plain");
  7648. });
  7649. // Start server in a thread
  7650. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7651. svr.wait_until_ready();
  7652. // Connect with client certificate (using constructor with paths)
  7653. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7654. cli.enable_server_certificate_verification(false);
  7655. auto res = cli.Get("/test-x509store");
  7656. ASSERT_TRUE(res);
  7657. EXPECT_EQ(200, res->status);
  7658. EXPECT_EQ("ok", res->body);
  7659. // Clean up
  7660. X509_free(server_cert);
  7661. EVP_PKEY_free(server_key);
  7662. X509_free(ca_cert);
  7663. svr.stop();
  7664. server_thread.join();
  7665. }
  7666. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7667. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7668. // prepare large data
  7669. std::random_device seed_gen;
  7670. std::mt19937 random(seed_gen());
  7671. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7672. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7673. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7674. // server
  7675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7676. ASSERT_TRUE(svr.is_valid());
  7677. svr.Post("/binary", [&](const Request &req, Response &res) {
  7678. EXPECT_EQ(large_size_byte, req.body.size());
  7679. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7680. res.set_content(req.body, "application/octet-stream");
  7681. });
  7682. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7683. auto se = detail::scope_exit([&] {
  7684. svr.stop();
  7685. listen_thread.join();
  7686. ASSERT_FALSE(svr.is_running());
  7687. });
  7688. svr.wait_until_ready();
  7689. // client POST
  7690. SSLClient cli("localhost", PORT);
  7691. cli.enable_server_certificate_verification(false);
  7692. cli.set_read_timeout(std::chrono::seconds(100));
  7693. cli.set_write_timeout(std::chrono::seconds(100));
  7694. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7695. large_size_byte, "application/octet-stream");
  7696. // compare
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ(large_size_byte, res->body.size());
  7699. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7700. }
  7701. #endif
  7702. #ifdef _WIN32
  7703. TEST(CleanupTest, WSACleanup) {
  7704. int ret = WSACleanup();
  7705. ASSERT_EQ(0, ret);
  7706. }
  7707. #endif
  7708. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7709. TEST(NoSSLSupport, SimpleInterface) {
  7710. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7711. }
  7712. #endif
  7713. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7714. TEST(InvalidScheme, SimpleInterface) {
  7715. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7716. }
  7717. #endif
  7718. TEST(NoScheme, SimpleInterface) {
  7719. Client cli("yahoo.com:80");
  7720. ASSERT_TRUE(cli.is_valid());
  7721. }
  7722. TEST(SendAPI, SimpleInterface_Online) {
  7723. Client cli("http://yahoo.com");
  7724. Request req;
  7725. req.method = "GET";
  7726. req.path = "/";
  7727. auto res = cli.send(req);
  7728. ASSERT_TRUE(res);
  7729. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7730. }
  7731. TEST(SendAPI, WithParamsInRequest) {
  7732. Server svr;
  7733. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7734. EXPECT_TRUE(req.has_param("test"));
  7735. EXPECT_EQ("test_value", req.get_param_value("test"));
  7736. });
  7737. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7738. auto se = detail::scope_exit([&] {
  7739. svr.stop();
  7740. t.join();
  7741. ASSERT_FALSE(svr.is_running());
  7742. });
  7743. svr.wait_until_ready();
  7744. Client cli(HOST, PORT);
  7745. {
  7746. Request req;
  7747. req.method = "GET";
  7748. req.path = "/";
  7749. req.params.emplace("test", "test_value");
  7750. auto res = cli.send(req);
  7751. ASSERT_TRUE(res);
  7752. }
  7753. {
  7754. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7755. ASSERT_TRUE(res);
  7756. }
  7757. }
  7758. TEST(ClientImplMethods, GetSocketTest) {
  7759. httplib::Server svr;
  7760. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7761. res.status = StatusCode::OK_200;
  7762. });
  7763. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7764. auto se = detail::scope_exit([&] {
  7765. svr.stop();
  7766. thread.join();
  7767. ASSERT_FALSE(svr.is_running());
  7768. });
  7769. svr.wait_until_ready();
  7770. {
  7771. httplib::Client cli("http://127.0.0.1:3333");
  7772. cli.set_keep_alive(true);
  7773. // Use the behavior of cpp-httplib of opening the connection
  7774. // only when the first request happens. If that changes,
  7775. // this test would be obsolete.
  7776. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7777. // This also implicitly tests the server. But other tests would fail much
  7778. // earlier than this one to be considered.
  7779. auto res = cli.Get("/");
  7780. ASSERT_TRUE(res);
  7781. EXPECT_EQ(StatusCode::OK_200, res->status);
  7782. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7783. }
  7784. }
  7785. // Disabled due to out-of-memory problem on GitHub Actions
  7786. #ifdef _WIN64
  7787. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7788. // allocate content size larger than 2GB in memory
  7789. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7790. char *content = (char *)malloc(content_size);
  7791. ASSERT_TRUE(content);
  7792. Server svr;
  7793. svr.Get("/foo",
  7794. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7795. res.set_content(content, content_size, "application/octet-stream");
  7796. });
  7797. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7798. auto se = detail::scope_exit([&] {
  7799. svr.stop();
  7800. listen_thread.join();
  7801. if (content) free(content);
  7802. ASSERT_FALSE(svr.is_running());
  7803. });
  7804. svr.wait_until_ready();
  7805. Client cli(HOST, PORT);
  7806. auto res = cli.Get("/foo");
  7807. ASSERT_TRUE(res);
  7808. EXPECT_EQ(StatusCode::OK_200, res->status);
  7809. EXPECT_EQ(content_size, res->body.length());
  7810. }
  7811. #endif
  7812. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7813. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7814. Client cli("http://yahoo.com");
  7815. auto res = cli.Get("/");
  7816. ASSERT_TRUE(res);
  7817. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7818. cli.set_follow_location(true);
  7819. res = cli.Get("/");
  7820. ASSERT_TRUE(res);
  7821. EXPECT_EQ(StatusCode::OK_200, res->status);
  7822. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7823. }
  7824. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7825. Client cli("https://yahoo.com");
  7826. auto res = cli.Get("/");
  7827. ASSERT_TRUE(res);
  7828. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7829. cli.set_follow_location(true);
  7830. res = cli.Get("/");
  7831. ASSERT_TRUE(res);
  7832. EXPECT_EQ(StatusCode::OK_200, res->status);
  7833. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7834. }
  7835. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7836. Client cli("https://yahoo.com");
  7837. auto res = cli.Get("/");
  7838. ASSERT_TRUE(res);
  7839. ASSERT_FALSE(!res);
  7840. ASSERT_TRUE(res);
  7841. ASSERT_FALSE(res == nullptr);
  7842. ASSERT_TRUE(res != nullptr);
  7843. EXPECT_EQ(Error::Success, res.error());
  7844. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7845. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7846. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7847. cli.set_follow_location(true);
  7848. res = cli.Get("/");
  7849. ASSERT_TRUE(res);
  7850. EXPECT_EQ(Error::Success, res.error());
  7851. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7852. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7853. EXPECT_EQ(StatusCode::OK_200, res->status);
  7854. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7855. }
  7856. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7857. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7858. Client cli("https://cdnjs.cloudflare.com");
  7859. auto res =
  7860. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7861. ASSERT_TRUE(res);
  7862. EXPECT_EQ(StatusCode::OK_200, res->status);
  7863. EXPECT_EQ(287630U, res->body.size());
  7864. EXPECT_EQ("application/javascript; charset=utf-8",
  7865. res->get_header_value("Content-Type"));
  7866. }
  7867. #endif
  7868. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7869. #undef REDIR_HOST // Silence compiler warning
  7870. #define REDIR_HOST "https://httpbingo.org"
  7871. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7872. Client cli(REDIR_HOST);
  7873. cli.set_follow_location(true);
  7874. auto res =
  7875. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7876. ASSERT_TRUE(res);
  7877. EXPECT_EQ(StatusCode::OK_200, res->status);
  7878. }
  7879. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7880. Client cli(REDIR_HOST);
  7881. cli.set_follow_location(true);
  7882. Params params;
  7883. params.emplace("url", "http://example.com");
  7884. params.emplace("status_code", "302");
  7885. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7886. ASSERT_TRUE(res);
  7887. EXPECT_EQ(StatusCode::OK_200, res->status);
  7888. }
  7889. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7890. Client cli(REDIR_HOST);
  7891. cli.set_follow_location(true);
  7892. Params params;
  7893. params.emplace("url", "http://example.com");
  7894. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7895. ASSERT_TRUE(res);
  7896. EXPECT_EQ(StatusCode::OK_200, res->status);
  7897. }
  7898. TEST(HttpToHttpsRedirectTest, CertFile) {
  7899. Server svr;
  7900. ASSERT_TRUE(svr.is_valid());
  7901. svr.Get("/index", [&](const Request &, Response &res) {
  7902. res.set_redirect("https://127.0.0.1:1235/index");
  7903. svr.stop();
  7904. });
  7905. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7906. ASSERT_TRUE(ssl_svr.is_valid());
  7907. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7908. res.set_content("test", "text/plain");
  7909. ssl_svr.stop();
  7910. });
  7911. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7912. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7913. auto se = detail::scope_exit([&] {
  7914. t2.join();
  7915. t.join();
  7916. ASSERT_FALSE(svr.is_running());
  7917. });
  7918. svr.wait_until_ready();
  7919. ssl_svr.wait_until_ready();
  7920. Client cli("127.0.0.1", PORT);
  7921. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7922. cli.enable_server_certificate_verification(true);
  7923. cli.set_follow_location(true);
  7924. cli.set_connection_timeout(30);
  7925. auto res = cli.Get("/index");
  7926. ASSERT_TRUE(res);
  7927. ASSERT_EQ(StatusCode::OK_200, res->status);
  7928. }
  7929. TEST(SSLClientRedirectTest, CertFile) {
  7930. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7931. ASSERT_TRUE(ssl_svr1.is_valid());
  7932. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7933. res.set_redirect("https://127.0.0.1:1235/index");
  7934. ssl_svr1.stop();
  7935. });
  7936. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7937. ASSERT_TRUE(ssl_svr2.is_valid());
  7938. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7939. res.set_content("test", "text/plain");
  7940. ssl_svr2.stop();
  7941. });
  7942. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7943. thread t2 =
  7944. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7945. auto se = detail::scope_exit([&] {
  7946. t2.join();
  7947. t.join();
  7948. ASSERT_FALSE(ssl_svr1.is_running());
  7949. });
  7950. ssl_svr1.wait_until_ready();
  7951. ssl_svr2.wait_until_ready();
  7952. SSLClient cli("127.0.0.1", PORT);
  7953. std::string cert;
  7954. read_file(SERVER_CERT2_FILE, cert);
  7955. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7956. cli.enable_server_certificate_verification(true);
  7957. cli.set_follow_location(true);
  7958. cli.set_connection_timeout(30);
  7959. auto res = cli.Get("/index");
  7960. ASSERT_TRUE(res);
  7961. ASSERT_EQ(StatusCode::OK_200, res->status);
  7962. }
  7963. TEST(MultipartFormDataTest, LargeData) {
  7964. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7965. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7966. const ContentReader &content_reader) {
  7967. if (req.is_multipart_form_data()) {
  7968. std::vector<FormData> items;
  7969. content_reader(
  7970. [&](const FormData &file) {
  7971. items.push_back(file);
  7972. return true;
  7973. },
  7974. [&](const char *data, size_t data_length) {
  7975. items.back().content.append(data, data_length);
  7976. return true;
  7977. });
  7978. EXPECT_TRUE(std::string(items[0].name) == "document");
  7979. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7980. EXPECT_TRUE(items[0].filename == "2MB_data");
  7981. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7982. EXPECT_TRUE(items[1].name == "hello");
  7983. EXPECT_TRUE(items[1].content == "world");
  7984. EXPECT_TRUE(items[1].filename == "");
  7985. EXPECT_TRUE(items[1].content_type == "");
  7986. } else {
  7987. std::string body;
  7988. content_reader([&](const char *data, size_t data_length) {
  7989. body.append(data, data_length);
  7990. return true;
  7991. });
  7992. }
  7993. });
  7994. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7995. auto se = detail::scope_exit([&] {
  7996. svr.stop();
  7997. t.join();
  7998. ASSERT_FALSE(svr.is_running());
  7999. });
  8000. svr.wait_until_ready();
  8001. {
  8002. std::string data(1024 * 1024 * 2, '.');
  8003. std::stringstream buffer;
  8004. buffer << data;
  8005. Client cli("https://localhost:8080");
  8006. cli.enable_server_certificate_verification(false);
  8007. UploadFormDataItems items{
  8008. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8009. {"hello", "world", "", ""},
  8010. };
  8011. auto res = cli.Post("/post", items);
  8012. ASSERT_TRUE(res);
  8013. ASSERT_EQ(StatusCode::OK_200, res->status);
  8014. }
  8015. }
  8016. TEST(MultipartFormDataTest, DataProviderItems) {
  8017. std::random_device seed_gen;
  8018. std::mt19937 random(seed_gen());
  8019. std::string rand1;
  8020. rand1.resize(1000);
  8021. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8022. std::string rand2;
  8023. rand2.resize(3000);
  8024. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8026. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8027. const ContentReader &content_reader) {
  8028. ASSERT_FALSE(req.is_multipart_form_data());
  8029. std::string body;
  8030. content_reader([&](const char *data, size_t data_length) {
  8031. body.append(data, data_length);
  8032. return true;
  8033. });
  8034. EXPECT_EQ(body, "");
  8035. });
  8036. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8037. const ContentReader &content_reader) {
  8038. ASSERT_TRUE(req.is_multipart_form_data());
  8039. std::vector<FormData> items;
  8040. content_reader(
  8041. [&](const FormData &file) {
  8042. items.push_back(file);
  8043. return true;
  8044. },
  8045. [&](const char *data, size_t data_length) {
  8046. items.back().content.append(data, data_length);
  8047. return true;
  8048. });
  8049. ASSERT_TRUE(items.size() == 2);
  8050. EXPECT_EQ(std::string(items[0].name), "name1");
  8051. EXPECT_EQ(items[0].content, "Testing123");
  8052. EXPECT_EQ(items[0].filename, "filename1");
  8053. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8054. EXPECT_EQ(items[1].name, "name2");
  8055. EXPECT_EQ(items[1].content, "Testing456");
  8056. EXPECT_EQ(items[1].filename, "");
  8057. EXPECT_EQ(items[1].content_type, "");
  8058. });
  8059. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8060. const ContentReader &content_reader) {
  8061. ASSERT_TRUE(req.is_multipart_form_data());
  8062. std::vector<FormData> items;
  8063. content_reader(
  8064. [&](const FormData &file) {
  8065. items.push_back(file);
  8066. return true;
  8067. },
  8068. [&](const char *data, size_t data_length) {
  8069. items.back().content.append(data, data_length);
  8070. return true;
  8071. });
  8072. ASSERT_TRUE(items.size() == 2);
  8073. EXPECT_EQ(items[0].name, "name3");
  8074. EXPECT_EQ(items[0].content, rand1);
  8075. EXPECT_EQ(items[0].filename, "filename3");
  8076. EXPECT_EQ(items[0].content_type, "");
  8077. EXPECT_EQ(items[1].name, "name4");
  8078. EXPECT_EQ(items[1].content, rand2);
  8079. EXPECT_EQ(items[1].filename, "filename4");
  8080. EXPECT_EQ(items[1].content_type, "");
  8081. });
  8082. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8083. const ContentReader &content_reader) {
  8084. ASSERT_TRUE(req.is_multipart_form_data());
  8085. std::vector<FormData> items;
  8086. content_reader(
  8087. [&](const FormData &file) {
  8088. items.push_back(file);
  8089. return true;
  8090. },
  8091. [&](const char *data, size_t data_length) {
  8092. items.back().content.append(data, data_length);
  8093. return true;
  8094. });
  8095. ASSERT_TRUE(items.size() == 4);
  8096. EXPECT_EQ(std::string(items[0].name), "name1");
  8097. EXPECT_EQ(items[0].content, "Testing123");
  8098. EXPECT_EQ(items[0].filename, "filename1");
  8099. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8100. EXPECT_EQ(items[1].name, "name2");
  8101. EXPECT_EQ(items[1].content, "Testing456");
  8102. EXPECT_EQ(items[1].filename, "");
  8103. EXPECT_EQ(items[1].content_type, "");
  8104. EXPECT_EQ(items[2].name, "name3");
  8105. EXPECT_EQ(items[2].content, rand1);
  8106. EXPECT_EQ(items[2].filename, "filename3");
  8107. EXPECT_EQ(items[2].content_type, "");
  8108. EXPECT_EQ(items[3].name, "name4");
  8109. EXPECT_EQ(items[3].content, rand2);
  8110. EXPECT_EQ(items[3].filename, "filename4");
  8111. EXPECT_EQ(items[3].content_type, "");
  8112. });
  8113. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8114. auto se = detail::scope_exit([&] {
  8115. svr.stop();
  8116. t.join();
  8117. ASSERT_FALSE(svr.is_running());
  8118. });
  8119. svr.wait_until_ready();
  8120. {
  8121. Client cli("https://localhost:8080");
  8122. cli.enable_server_certificate_verification(false);
  8123. UploadFormDataItems items{
  8124. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8125. {"name2", "Testing456", "", ""}, // not a file
  8126. };
  8127. {
  8128. auto res = cli.Post("/post-none", {}, {}, {});
  8129. ASSERT_TRUE(res);
  8130. ASSERT_EQ(StatusCode::OK_200, res->status);
  8131. }
  8132. FormDataProviderItems providers;
  8133. {
  8134. auto res =
  8135. cli.Post("/post-items", {}, items, providers); // empty providers
  8136. ASSERT_TRUE(res);
  8137. ASSERT_EQ(StatusCode::OK_200, res->status);
  8138. }
  8139. providers.push_back({"name3",
  8140. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8141. // test the offset is given correctly at each step
  8142. if (!offset)
  8143. sink.os.write(rand1.data(), 30);
  8144. else if (offset == 30)
  8145. sink.os.write(rand1.data() + 30, 300);
  8146. else if (offset == 330)
  8147. sink.os.write(rand1.data() + 330, 670);
  8148. else if (offset == rand1.size())
  8149. sink.done();
  8150. return true;
  8151. },
  8152. "filename3",
  8153. {}});
  8154. providers.push_back({"name4",
  8155. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8156. // test the offset is given correctly at each step
  8157. if (!offset)
  8158. sink.os.write(rand2.data(), 2000);
  8159. else if (offset == 2000)
  8160. sink.os.write(rand2.data() + 2000, 1);
  8161. else if (offset == 2001)
  8162. sink.os.write(rand2.data() + 2001, 999);
  8163. else if (offset == rand2.size())
  8164. sink.done();
  8165. return true;
  8166. },
  8167. "filename4",
  8168. {}});
  8169. {
  8170. auto res = cli.Post("/post-providers", {}, {}, providers);
  8171. ASSERT_TRUE(res);
  8172. ASSERT_EQ(StatusCode::OK_200, res->status);
  8173. }
  8174. {
  8175. auto res = cli.Post("/post-both", {}, items, providers);
  8176. ASSERT_TRUE(res);
  8177. ASSERT_EQ(StatusCode::OK_200, res->status);
  8178. }
  8179. }
  8180. }
  8181. TEST(MultipartFormDataTest, BadHeader) {
  8182. Server svr;
  8183. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8184. res.set_content("ok", "text/plain");
  8185. });
  8186. thread t = thread([&] { svr.listen(HOST, PORT); });
  8187. auto se = detail::scope_exit([&] {
  8188. svr.stop();
  8189. t.join();
  8190. ASSERT_FALSE(svr.is_running());
  8191. });
  8192. svr.wait_until_ready();
  8193. const std::string body =
  8194. "This is the preamble. It is to be ignored, though it\r\n"
  8195. "is a handy place for composition agents to include an\r\n"
  8196. "explanatory note to non-MIME conformant readers.\r\n"
  8197. "\r\n"
  8198. "\r\n"
  8199. "--simple boundary\r\n"
  8200. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8201. ": BAD...\r\n"
  8202. "\r\n"
  8203. "value1\r\n"
  8204. "--simple boundary\r\n"
  8205. "Content-Disposition: form-data; name=\"field2\"; "
  8206. "filename=\"example.txt\"\r\n"
  8207. "\r\n"
  8208. "value2\r\n"
  8209. "--simple boundary--\r\n"
  8210. "This is the epilogue. It is also to be ignored.\r\n";
  8211. std::string content_type =
  8212. R"(multipart/form-data; boundary="simple boundary")";
  8213. Client cli(HOST, PORT);
  8214. auto res = cli.Post("/post", body, content_type.c_str());
  8215. ASSERT_TRUE(res);
  8216. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8217. }
  8218. TEST(MultipartFormDataTest, WithPreamble) {
  8219. Server svr;
  8220. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8221. res.set_content("ok", "text/plain");
  8222. });
  8223. thread t = thread([&] { svr.listen(HOST, PORT); });
  8224. auto se = detail::scope_exit([&] {
  8225. svr.stop();
  8226. t.join();
  8227. ASSERT_FALSE(svr.is_running());
  8228. });
  8229. svr.wait_until_ready();
  8230. const std::string body =
  8231. "This is the preamble. It is to be ignored, though it\r\n"
  8232. "is a handy place for composition agents to include an\r\n"
  8233. "explanatory note to non-MIME conformant readers.\r\n"
  8234. "\r\n"
  8235. "\r\n"
  8236. "--simple boundary\r\n"
  8237. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8238. "\r\n"
  8239. "value1\r\n"
  8240. "--simple boundary\r\n"
  8241. "Content-Disposition: form-data; name=\"field2\"; "
  8242. "filename=\"example.txt\"\r\n"
  8243. "\r\n"
  8244. "value2\r\n"
  8245. "--simple boundary--\r\n"
  8246. "This is the epilogue. It is also to be ignored.\r\n";
  8247. std::string content_type =
  8248. R"(multipart/form-data; boundary="simple boundary")";
  8249. Client cli(HOST, PORT);
  8250. auto res = cli.Post("/post", body, content_type.c_str());
  8251. ASSERT_TRUE(res);
  8252. EXPECT_EQ(StatusCode::OK_200, res->status);
  8253. }
  8254. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8255. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8256. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8257. const ContentReader &content_reader) {
  8258. if (req.is_multipart_form_data()) {
  8259. std::vector<FormData> items;
  8260. content_reader(
  8261. [&](const FormData &file) {
  8262. items.push_back(file);
  8263. return true;
  8264. },
  8265. [&](const char *data, size_t data_length) {
  8266. items.back().content.append(data, data_length);
  8267. return true;
  8268. });
  8269. EXPECT_TRUE(std::string(items[0].name) == "document");
  8270. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8271. EXPECT_TRUE(items[0].filename == "2MB_data");
  8272. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8273. EXPECT_TRUE(items[1].name == "hello");
  8274. EXPECT_TRUE(items[1].content == "world");
  8275. EXPECT_TRUE(items[1].filename == "");
  8276. EXPECT_TRUE(items[1].content_type == "");
  8277. } else {
  8278. std::string body;
  8279. content_reader([&](const char *data, size_t data_length) {
  8280. body.append(data, data_length);
  8281. return true;
  8282. });
  8283. }
  8284. });
  8285. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8286. auto se = detail::scope_exit([&] {
  8287. svr.stop();
  8288. t.join();
  8289. ASSERT_FALSE(svr.is_running());
  8290. });
  8291. svr.wait_until_ready();
  8292. {
  8293. std::string data(1024 * 1024 * 2, '.');
  8294. std::stringstream buffer;
  8295. buffer << data;
  8296. Client cli("https://localhost:8080");
  8297. cli.enable_server_certificate_verification(false);
  8298. UploadFormDataItems items{
  8299. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8300. {"hello", "world", "", ""},
  8301. };
  8302. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8303. ASSERT_TRUE(res);
  8304. ASSERT_EQ(StatusCode::OK_200, res->status);
  8305. }
  8306. }
  8307. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8308. std::string data(1024 * 1024 * 2, '&');
  8309. std::stringstream buffer;
  8310. buffer << data;
  8311. Client cli("https://localhost:8080");
  8312. UploadFormDataItems items{
  8313. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8314. {"hello", "world", "", ""},
  8315. };
  8316. for (const char &c : " \t\r\n") {
  8317. auto res =
  8318. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8319. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8320. ASSERT_FALSE(res);
  8321. }
  8322. }
  8323. TEST(MultipartFormDataTest, PutFormData) {
  8324. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8325. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8326. const ContentReader &content_reader) {
  8327. if (req.is_multipart_form_data()) {
  8328. std::vector<FormData> items;
  8329. content_reader(
  8330. [&](const FormData &file) {
  8331. items.push_back(file);
  8332. return true;
  8333. },
  8334. [&](const char *data, size_t data_length) {
  8335. items.back().content.append(data, data_length);
  8336. return true;
  8337. });
  8338. EXPECT_TRUE(std::string(items[0].name) == "document");
  8339. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8340. EXPECT_TRUE(items[0].filename == "2MB_data");
  8341. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8342. EXPECT_TRUE(items[1].name == "hello");
  8343. EXPECT_TRUE(items[1].content == "world");
  8344. EXPECT_TRUE(items[1].filename == "");
  8345. EXPECT_TRUE(items[1].content_type == "");
  8346. } else {
  8347. std::string body;
  8348. content_reader([&](const char *data, size_t data_length) {
  8349. body.append(data, data_length);
  8350. return true;
  8351. });
  8352. }
  8353. });
  8354. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8355. auto se = detail::scope_exit([&] {
  8356. svr.stop();
  8357. t.join();
  8358. ASSERT_FALSE(svr.is_running());
  8359. });
  8360. svr.wait_until_ready();
  8361. {
  8362. std::string data(1024 * 1024 * 2, '&');
  8363. std::stringstream buffer;
  8364. buffer << data;
  8365. Client cli("https://localhost:8080");
  8366. cli.enable_server_certificate_verification(false);
  8367. UploadFormDataItems items{
  8368. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8369. {"hello", "world", "", ""},
  8370. };
  8371. auto res = cli.Put("/put", items);
  8372. ASSERT_TRUE(res);
  8373. ASSERT_EQ(StatusCode::OK_200, res->status);
  8374. }
  8375. }
  8376. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8378. svr.Put("/put_customboundary",
  8379. [&](const Request &req, const Response & /*res*/,
  8380. const ContentReader &content_reader) {
  8381. if (req.is_multipart_form_data()) {
  8382. std::vector<FormData> items;
  8383. content_reader(
  8384. [&](const FormData &file) {
  8385. items.push_back(file);
  8386. return true;
  8387. },
  8388. [&](const char *data, size_t data_length) {
  8389. items.back().content.append(data, data_length);
  8390. return true;
  8391. });
  8392. EXPECT_TRUE(std::string(items[0].name) == "document");
  8393. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8394. EXPECT_TRUE(items[0].filename == "2MB_data");
  8395. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8396. EXPECT_TRUE(items[1].name == "hello");
  8397. EXPECT_TRUE(items[1].content == "world");
  8398. EXPECT_TRUE(items[1].filename == "");
  8399. EXPECT_TRUE(items[1].content_type == "");
  8400. } else {
  8401. std::string body;
  8402. content_reader([&](const char *data, size_t data_length) {
  8403. body.append(data, data_length);
  8404. return true;
  8405. });
  8406. }
  8407. });
  8408. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8409. auto se = detail::scope_exit([&] {
  8410. svr.stop();
  8411. t.join();
  8412. ASSERT_FALSE(svr.is_running());
  8413. });
  8414. svr.wait_until_ready();
  8415. {
  8416. std::string data(1024 * 1024 * 2, '&');
  8417. std::stringstream buffer;
  8418. buffer << data;
  8419. Client cli("https://localhost:8080");
  8420. cli.enable_server_certificate_verification(false);
  8421. UploadFormDataItems items{
  8422. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8423. {"hello", "world", "", ""},
  8424. };
  8425. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8426. ASSERT_TRUE(res);
  8427. ASSERT_EQ(StatusCode::OK_200, res->status);
  8428. }
  8429. }
  8430. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8431. std::string data(1024 * 1024 * 2, '&');
  8432. std::stringstream buffer;
  8433. buffer << data;
  8434. Client cli("https://localhost:8080");
  8435. cli.enable_server_certificate_verification(false);
  8436. UploadFormDataItems items{
  8437. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8438. {"hello", "world", "", ""},
  8439. };
  8440. for (const char &c : " \t\r\n") {
  8441. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8442. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8443. ASSERT_FALSE(res);
  8444. }
  8445. }
  8446. TEST(MultipartFormDataTest, AlternateFilename) {
  8447. auto handled = false;
  8448. Server svr;
  8449. svr.Post("/test", [&](const Request &req, Response &res) {
  8450. ASSERT_EQ(2u, req.form.files.size());
  8451. ASSERT_EQ(1u, req.form.fields.size());
  8452. // Test files
  8453. const auto &file1 = req.form.get_file("file1");
  8454. ASSERT_EQ("file1", file1.name);
  8455. ASSERT_EQ("A.txt", file1.filename);
  8456. ASSERT_EQ("text/plain", file1.content_type);
  8457. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8458. const auto &file2 = req.form.get_file("file2");
  8459. ASSERT_EQ("file2", file2.name);
  8460. ASSERT_EQ("a.html", file2.filename);
  8461. ASSERT_EQ("text/html", file2.content_type);
  8462. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8463. file2.content);
  8464. // Test text field
  8465. const auto &text = req.form.get_field("text");
  8466. ASSERT_EQ("text default", text);
  8467. res.set_content("ok", "text/plain");
  8468. handled = true;
  8469. });
  8470. thread t = thread([&] { svr.listen(HOST, PORT); });
  8471. auto se = detail::scope_exit([&] {
  8472. svr.stop();
  8473. t.join();
  8474. ASSERT_FALSE(svr.is_running());
  8475. ASSERT_TRUE(handled);
  8476. });
  8477. svr.wait_until_ready();
  8478. auto req = "POST /test HTTP/1.1\r\n"
  8479. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8480. "Content-Length: 399\r\n"
  8481. "\r\n"
  8482. "----------\r\n"
  8483. "Content-Disposition: form-data; name=\"text\"\r\n"
  8484. "\r\n"
  8485. "text default\r\n"
  8486. "----------\r\n"
  8487. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8488. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8489. "Content-Type: text/plain\r\n"
  8490. "\r\n"
  8491. "Content of a.txt.\r\n"
  8492. "\r\n"
  8493. "----------\r\n"
  8494. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8495. "\"a.html\"\r\n"
  8496. "Content-Type: text/html\r\n"
  8497. "\r\n"
  8498. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8499. "\r\n"
  8500. "------------\r\n";
  8501. ASSERT_TRUE(send_request(1, req));
  8502. }
  8503. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8504. auto handled = false;
  8505. Server svr;
  8506. svr.Post("/test", [&](const Request &req, Response &) {
  8507. ASSERT_EQ(2u, req.form.fields.size());
  8508. const auto &text1 = req.form.get_field("text1");
  8509. ASSERT_EQ("text1", text1);
  8510. const auto &text2 = req.form.get_field("text2");
  8511. ASSERT_EQ("text2", text2);
  8512. handled = true;
  8513. });
  8514. thread t = thread([&] { svr.listen(HOST, PORT); });
  8515. auto se = detail::scope_exit([&] {
  8516. svr.stop();
  8517. t.join();
  8518. ASSERT_FALSE(svr.is_running());
  8519. ASSERT_TRUE(handled);
  8520. });
  8521. svr.wait_until_ready();
  8522. auto req = "POST /test HTTP/1.1\r\n"
  8523. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8524. "Content-Length: 146\r\n"
  8525. "\r\n----------\r\n"
  8526. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8527. "\r\n"
  8528. "text1"
  8529. "\r\n----------\r\n"
  8530. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8531. "\r\n"
  8532. "text2"
  8533. "\r\n------------";
  8534. std::string response;
  8535. ASSERT_TRUE(send_request(1, req, &response));
  8536. ASSERT_EQ("200", response.substr(9, 3));
  8537. }
  8538. TEST(MultipartFormDataTest, ContentLength) {
  8539. auto handled = false;
  8540. Server svr;
  8541. svr.Post("/test", [&](const Request &req, Response &) {
  8542. ASSERT_EQ(2u, req.form.fields.size());
  8543. const auto &text1 = req.form.get_field("text1");
  8544. ASSERT_EQ("text1", text1);
  8545. const auto &text2 = req.form.get_field("text2");
  8546. ASSERT_EQ("text2", text2);
  8547. handled = true;
  8548. });
  8549. thread t = thread([&] { svr.listen(HOST, PORT); });
  8550. auto se = detail::scope_exit([&] {
  8551. svr.stop();
  8552. t.join();
  8553. ASSERT_FALSE(svr.is_running());
  8554. ASSERT_TRUE(handled);
  8555. });
  8556. svr.wait_until_ready();
  8557. auto req = "POST /test HTTP/1.1\r\n"
  8558. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8559. "Content-Length: 167\r\n"
  8560. "\r\n----------\r\n"
  8561. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8562. "Content-Length: 5\r\n"
  8563. "\r\n"
  8564. "text1"
  8565. "\r\n----------\r\n"
  8566. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8567. "\r\n"
  8568. "text2"
  8569. "\r\n------------\r\n";
  8570. std::string response;
  8571. ASSERT_TRUE(send_request(1, req, &response));
  8572. ASSERT_EQ("200", response.substr(9, 3));
  8573. }
  8574. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8575. auto handled = false;
  8576. Server svr;
  8577. svr.Post("/test", [&](const Request &req, Response &) {
  8578. ASSERT_EQ(2u, req.form.fields.size());
  8579. const auto &text1 = req.form.get_field("text1");
  8580. ASSERT_EQ("text1", text1);
  8581. // TODO: Add header access for text fields if needed
  8582. const auto &text2 = req.form.get_field("text2");
  8583. ASSERT_EQ("text2", text2);
  8584. // TODO: Header access for text fields needs to be implemented
  8585. // auto &headers = it->second.headers;
  8586. // ASSERT_EQ(3U, headers.size());
  8587. // auto custom_header = headers.find("x-whatever");
  8588. // ASSERT_TRUE(custom_header != headers.end());
  8589. // ASSERT_NE("customvalue", custom_header->second);
  8590. // ASSERT_EQ("CustomValue", custom_header->second);
  8591. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8592. handled = true;
  8593. });
  8594. thread t = thread([&] { svr.listen(HOST, PORT); });
  8595. auto se = detail::scope_exit([&] {
  8596. svr.stop();
  8597. t.join();
  8598. ASSERT_FALSE(svr.is_running());
  8599. ASSERT_TRUE(handled);
  8600. });
  8601. svr.wait_until_ready();
  8602. auto req = "POST /test HTTP/1.1\r\n"
  8603. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8604. "Content-Length: 232\r\n"
  8605. "\r\n----------\r\n"
  8606. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8607. "Content-Length: 5\r\n"
  8608. "X-Test: 1\r\n"
  8609. "\r\n"
  8610. "text1"
  8611. "\r\n----------\r\n"
  8612. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8613. "Content-Type: text/plain\r\n"
  8614. "X-Whatever: CustomValue\r\n"
  8615. "\r\n"
  8616. "text2"
  8617. "\r\n------------\r\n"
  8618. "That should be disregarded. Not even read";
  8619. std::string response;
  8620. ASSERT_TRUE(send_request(1, req, &response));
  8621. ASSERT_EQ("200", response.substr(9, 3));
  8622. }
  8623. #endif
  8624. TEST(MultipartFormDataTest, LargeHeader) {
  8625. auto handled = false;
  8626. Server svr;
  8627. svr.Post("/test", [&](const Request &req, Response &) {
  8628. ASSERT_EQ(1u, req.form.fields.size());
  8629. const auto &text = req.form.get_field("name1");
  8630. ASSERT_EQ("text1", text);
  8631. handled = true;
  8632. });
  8633. thread t = thread([&] { svr.listen(HOST, PORT); });
  8634. auto se = detail::scope_exit([&] {
  8635. svr.stop();
  8636. t.join();
  8637. ASSERT_FALSE(svr.is_running());
  8638. ASSERT_TRUE(handled);
  8639. });
  8640. svr.wait_until_ready();
  8641. auto boundary = std::string("cpp-httplib-multipart-data");
  8642. std::string content = "--" + boundary +
  8643. "\r\n"
  8644. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8645. "\r\n"
  8646. "text1\r\n"
  8647. "--" +
  8648. boundary + "--\r\n";
  8649. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8650. "Content-Type: multipart/form-data;boundary=" +
  8651. boundary +
  8652. "\r\n"
  8653. "Content-Length: " +
  8654. std::to_string(content.size()) +
  8655. "\r\n"
  8656. "Dummy-Header: ";
  8657. std::string header_suffix = "\r\n"
  8658. "\r\n";
  8659. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8660. size_t header_dummy_size =
  8661. read_buff_size -
  8662. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8663. auto header_dummy = std::string(header_dummy_size, '@');
  8664. auto req = header_prefix + header_dummy + header_suffix + content;
  8665. std::string response;
  8666. ASSERT_TRUE(send_request(1, req, &response));
  8667. ASSERT_EQ("200", response.substr(9, 3));
  8668. }
  8669. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8670. static constexpr unsigned int number_of_tasks{1000000};
  8671. std::atomic_uint count{0};
  8672. std::unique_ptr<TaskQueue> task_queue{
  8673. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8674. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8675. auto queued = task_queue->enqueue(
  8676. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8677. EXPECT_TRUE(queued);
  8678. }
  8679. EXPECT_NO_THROW(task_queue->shutdown());
  8680. EXPECT_EQ(number_of_tasks, count.load());
  8681. }
  8682. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8683. static constexpr unsigned int number_of_tasks{1000000};
  8684. static constexpr unsigned int qlimit{2};
  8685. unsigned int queued_count{0};
  8686. std::atomic_uint count{0};
  8687. std::unique_ptr<TaskQueue> task_queue{
  8688. new ThreadPool{/*num_threads=*/1, qlimit}};
  8689. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8690. if (task_queue->enqueue(
  8691. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8692. queued_count++;
  8693. }
  8694. }
  8695. EXPECT_NO_THROW(task_queue->shutdown());
  8696. EXPECT_EQ(queued_count, count.load());
  8697. EXPECT_TRUE(queued_count <= number_of_tasks);
  8698. EXPECT_TRUE(queued_count >= qlimit);
  8699. }
  8700. TEST(TaskQueueTest, MaxQueuedRequests) {
  8701. static constexpr unsigned int qlimit{3};
  8702. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8703. std::condition_variable sem_cv;
  8704. std::mutex sem_mtx;
  8705. int credits = 0;
  8706. bool queued;
  8707. /* Fill up the queue with tasks that will block until we give them credits to
  8708. * complete. */
  8709. for (unsigned int n = 0; n <= qlimit;) {
  8710. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8711. std::unique_lock<std::mutex> lock(sem_mtx);
  8712. while (credits <= 0) {
  8713. sem_cv.wait(lock);
  8714. }
  8715. /* Consume the credit and signal the test code if they are all gone. */
  8716. if (--credits == 0) { sem_cv.notify_one(); }
  8717. });
  8718. if (n < qlimit) {
  8719. /* The first qlimit enqueues must succeed. */
  8720. EXPECT_TRUE(queued);
  8721. } else {
  8722. /* The last one will succeed only when the worker thread
  8723. * starts and dequeues the first blocking task. Although
  8724. * not necessary for the correctness of this test, we sleep for
  8725. * a short while to avoid busy waiting. */
  8726. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8727. }
  8728. if (queued) { n++; }
  8729. }
  8730. /* Further enqueues must fail since the queue is full. */
  8731. for (auto i = 0; i < 4; i++) {
  8732. queued = task_queue->enqueue([] {});
  8733. EXPECT_FALSE(queued);
  8734. }
  8735. /* Give the credits to allow the previous tasks to complete. */
  8736. {
  8737. std::unique_lock<std::mutex> lock(sem_mtx);
  8738. credits += qlimit + 1;
  8739. }
  8740. sem_cv.notify_all();
  8741. /* Wait for all the credits to be consumed. */
  8742. {
  8743. std::unique_lock<std::mutex> lock(sem_mtx);
  8744. while (credits > 0) {
  8745. sem_cv.wait(lock);
  8746. }
  8747. }
  8748. /* Check that we are able again to enqueue at least qlimit tasks. */
  8749. for (unsigned int i = 0; i < qlimit; i++) {
  8750. queued = task_queue->enqueue([] {});
  8751. EXPECT_TRUE(queued);
  8752. }
  8753. EXPECT_NO_THROW(task_queue->shutdown());
  8754. }
  8755. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8756. Server svr;
  8757. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8758. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8759. });
  8760. svr.Get("/hello", [](const Request &req, Response &res) {
  8761. res.set_content(req.get_param_value("key"), "text/plain");
  8762. });
  8763. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8764. auto se = detail::scope_exit([&] {
  8765. svr.stop();
  8766. thread.join();
  8767. ASSERT_FALSE(svr.is_running());
  8768. });
  8769. svr.wait_until_ready();
  8770. {
  8771. Client cli(HOST, PORT);
  8772. cli.set_follow_location(true);
  8773. auto res = cli.Get("/");
  8774. ASSERT_TRUE(res);
  8775. EXPECT_EQ(StatusCode::OK_200, res->status);
  8776. EXPECT_EQ("val&key2=val2", res->body);
  8777. }
  8778. }
  8779. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8780. Server svr;
  8781. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8782. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8783. });
  8784. svr.Get("/hello", [](const Request &req, Response &res) {
  8785. res.set_content(req.get_param_value("key"), "text/plain");
  8786. });
  8787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8788. auto se = detail::scope_exit([&] {
  8789. svr.stop();
  8790. thread.join();
  8791. ASSERT_FALSE(svr.is_running());
  8792. });
  8793. svr.wait_until_ready();
  8794. {
  8795. Client cli(HOST, PORT);
  8796. cli.set_follow_location(true);
  8797. auto res = cli.Get("/");
  8798. ASSERT_TRUE(res);
  8799. EXPECT_EQ(StatusCode::OK_200, res->status);
  8800. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8801. }
  8802. }
  8803. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8804. TEST(RedirectTest, Issue2185_Online) {
  8805. SSLClient client("github.com");
  8806. client.set_follow_location(true);
  8807. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8808. "Coollab-Windows.zip");
  8809. ASSERT_TRUE(res);
  8810. EXPECT_EQ(StatusCode::OK_200, res->status);
  8811. EXPECT_EQ(9920427U, res->body.size());
  8812. }
  8813. #endif
  8814. TEST(VulnerabilityTest, CRLFInjection) {
  8815. Server svr;
  8816. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8817. res.set_content("Hello 1", "text/plain");
  8818. });
  8819. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8820. res.set_content("Hello 2", "text/plain");
  8821. });
  8822. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8823. res.set_content("Hello 3", "text/plain");
  8824. });
  8825. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8826. res.set_content("Hello 4", "text/plain");
  8827. });
  8828. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8829. for (const auto &x : req.headers) {
  8830. auto key = x.first;
  8831. EXPECT_STRNE("evil", key.c_str());
  8832. }
  8833. });
  8834. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8835. auto se = detail::scope_exit([&] {
  8836. svr.stop();
  8837. thread.join();
  8838. ASSERT_FALSE(svr.is_running());
  8839. });
  8840. svr.wait_until_ready();
  8841. {
  8842. Client cli(HOST, PORT);
  8843. cli.Post("/test1", "A=B",
  8844. "application/x-www-form-urlencoded\r\nevil: hello1");
  8845. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8846. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8847. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8848. }
  8849. }
  8850. TEST(PathParamsTest, StaticMatch) {
  8851. const auto pattern = "/users/all";
  8852. detail::PathParamsMatcher matcher(pattern);
  8853. Request request;
  8854. request.path = "/users/all";
  8855. ASSERT_TRUE(matcher.match(request));
  8856. std::unordered_map<std::string, std::string> expected_params = {};
  8857. EXPECT_EQ(request.path_params, expected_params);
  8858. }
  8859. TEST(PathParamsTest, StaticMismatch) {
  8860. const auto pattern = "/users/all";
  8861. detail::PathParamsMatcher matcher(pattern);
  8862. Request request;
  8863. request.path = "/users/1";
  8864. ASSERT_FALSE(matcher.match(request));
  8865. }
  8866. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8867. const auto pattern = "/users/:id/subscriptions";
  8868. detail::PathParamsMatcher matcher(pattern);
  8869. Request request;
  8870. request.path = "/users/42/subscriptions";
  8871. ASSERT_TRUE(matcher.match(request));
  8872. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8873. EXPECT_EQ(request.path_params, expected_params);
  8874. }
  8875. TEST(PathParamsTest, SingleParamInTheEnd) {
  8876. const auto pattern = "/users/:id";
  8877. detail::PathParamsMatcher matcher(pattern);
  8878. Request request;
  8879. request.path = "/users/24";
  8880. ASSERT_TRUE(matcher.match(request));
  8881. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8882. EXPECT_EQ(request.path_params, expected_params);
  8883. }
  8884. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8885. const auto pattern = "/users/:id/";
  8886. detail::PathParamsMatcher matcher(pattern);
  8887. Request request;
  8888. request.path = "/users/42/";
  8889. ASSERT_TRUE(matcher.match(request));
  8890. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8891. EXPECT_EQ(request.path_params, expected_params);
  8892. }
  8893. TEST(PathParamsTest, EmptyParam) {
  8894. const auto pattern = "/users/:id/";
  8895. detail::PathParamsMatcher matcher(pattern);
  8896. Request request;
  8897. request.path = "/users//";
  8898. ASSERT_TRUE(matcher.match(request));
  8899. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8900. EXPECT_EQ(request.path_params, expected_params);
  8901. }
  8902. TEST(PathParamsTest, FragmentMismatch) {
  8903. const auto pattern = "/users/:id/";
  8904. detail::PathParamsMatcher matcher(pattern);
  8905. Request request;
  8906. request.path = "/admins/24/";
  8907. ASSERT_FALSE(matcher.match(request));
  8908. }
  8909. TEST(PathParamsTest, ExtraFragments) {
  8910. const auto pattern = "/users/:id";
  8911. detail::PathParamsMatcher matcher(pattern);
  8912. Request request;
  8913. request.path = "/users/42/subscriptions";
  8914. ASSERT_FALSE(matcher.match(request));
  8915. }
  8916. TEST(PathParamsTest, MissingTrailingParam) {
  8917. const auto pattern = "/users/:id";
  8918. detail::PathParamsMatcher matcher(pattern);
  8919. Request request;
  8920. request.path = "/users";
  8921. ASSERT_FALSE(matcher.match(request));
  8922. }
  8923. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8924. const auto pattern = "/users/:id/subscriptions";
  8925. detail::PathParamsMatcher matcher(pattern);
  8926. Request request;
  8927. request.path = "/users/subscriptions";
  8928. ASSERT_FALSE(matcher.match(request));
  8929. }
  8930. TEST(PathParamsTest, MultipleParams) {
  8931. const auto pattern = "/users/:userid/subscriptions/:subid";
  8932. detail::PathParamsMatcher matcher(pattern);
  8933. Request request;
  8934. request.path = "/users/42/subscriptions/2";
  8935. ASSERT_TRUE(matcher.match(request));
  8936. std::unordered_map<std::string, std::string> expected_params = {
  8937. {"userid", "42"}, {"subid", "2"}};
  8938. EXPECT_EQ(request.path_params, expected_params);
  8939. }
  8940. TEST(PathParamsTest, SequenceOfParams) {
  8941. const auto pattern = "/values/:x/:y/:z";
  8942. detail::PathParamsMatcher matcher(pattern);
  8943. Request request;
  8944. request.path = "/values/1/2/3";
  8945. ASSERT_TRUE(matcher.match(request));
  8946. std::unordered_map<std::string, std::string> expected_params = {
  8947. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8948. EXPECT_EQ(request.path_params, expected_params);
  8949. }
  8950. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8951. const auto pattern = "/prefix:suffix";
  8952. detail::PathParamsMatcher matcher(pattern);
  8953. Request request;
  8954. request.path = "/prefix:suffix";
  8955. ASSERT_TRUE(matcher.match(request));
  8956. const std::unordered_map<std::string, std::string> expected_params = {};
  8957. EXPECT_EQ(request.path_params, expected_params);
  8958. }
  8959. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8960. // If ipv6 regex working, regex match codepath is taken.
  8961. // else port will default to 80 in Client impl
  8962. int clientImplMagicPort = 80;
  8963. int port = 4321;
  8964. // above ports must be different to avoid false negative
  8965. EXPECT_NE(clientImplMagicPort, port);
  8966. std::string ipV6TestURL = "http://[ff06::c3]";
  8967. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8968. CLIENT_PRIVATE_KEY_FILE);
  8969. EXPECT_EQ(cli.port(), port);
  8970. }
  8971. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8972. auto file_path = "./www/dir/index.html";
  8973. auto dir_path = "./www/dir";
  8974. detail::FileStat stat_file(file_path);
  8975. EXPECT_TRUE(stat_file.is_file());
  8976. EXPECT_FALSE(stat_file.is_dir());
  8977. detail::FileStat stat_dir(dir_path);
  8978. EXPECT_FALSE(stat_dir.is_file());
  8979. EXPECT_TRUE(stat_dir.is_dir());
  8980. }
  8981. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  8982. // IPv4 with default HTTP port (80)
  8983. EXPECT_EQ("example.com",
  8984. detail::make_host_and_port_string("example.com", 80, false));
  8985. // IPv4 with default HTTPS port (443)
  8986. EXPECT_EQ("example.com",
  8987. detail::make_host_and_port_string("example.com", 443, true));
  8988. // IPv4 with non-default HTTP port
  8989. EXPECT_EQ("example.com:8080",
  8990. detail::make_host_and_port_string("example.com", 8080, false));
  8991. // IPv4 with non-default HTTPS port
  8992. EXPECT_EQ("example.com:8443",
  8993. detail::make_host_and_port_string("example.com", 8443, true));
  8994. // IPv6 with default HTTP port (80)
  8995. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  8996. // IPv6 with default HTTPS port (443)
  8997. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  8998. // IPv6 with non-default HTTP port
  8999. EXPECT_EQ("[::1]:8080",
  9000. detail::make_host_and_port_string("::1", 8080, false));
  9001. // IPv6 with non-default HTTPS port
  9002. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9003. // IPv6 full address with default port
  9004. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9005. detail::make_host_and_port_string(
  9006. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9007. // IPv6 full address with non-default port
  9008. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9009. detail::make_host_and_port_string(
  9010. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9011. // IPv6 localhost with non-default port
  9012. EXPECT_EQ("[::1]:3000",
  9013. detail::make_host_and_port_string("::1", 3000, false));
  9014. // IPv6 with zone ID (link-local address) with default port
  9015. EXPECT_EQ("[fe80::1%eth0]",
  9016. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9017. // IPv6 with zone ID (link-local address) with non-default port
  9018. EXPECT_EQ("[fe80::1%eth0]:8080",
  9019. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9020. // Edge case: Port 443 with is_ssl=false (should add port)
  9021. EXPECT_EQ("example.com:443",
  9022. detail::make_host_and_port_string("example.com", 443, false));
  9023. // Edge case: Port 80 with is_ssl=true (should add port)
  9024. EXPECT_EQ("example.com:80",
  9025. detail::make_host_and_port_string("example.com", 80, true));
  9026. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9027. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9028. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9029. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9030. // Security fix: Already bracketed IPv6 should not get double brackets
  9031. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9032. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9033. EXPECT_EQ("[::1]:8080",
  9034. detail::make_host_and_port_string("[::1]", 8080, false));
  9035. EXPECT_EQ("[2001:db8::1]:8080",
  9036. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9037. EXPECT_EQ("[fe80::1%eth0]",
  9038. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9039. EXPECT_EQ("[fe80::1%eth0]:8080",
  9040. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9041. // Edge case: Empty host (should return as-is)
  9042. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9043. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9044. // This is a known limitation but shouldn't crash
  9045. EXPECT_EQ("[host:name]",
  9046. detail::make_host_and_port_string("host:name", 80, false));
  9047. // Port number edge cases (no validation, but should not crash)
  9048. EXPECT_EQ("example.com:0",
  9049. detail::make_host_and_port_string("example.com", 0, false));
  9050. EXPECT_EQ("example.com:-1",
  9051. detail::make_host_and_port_string("example.com", -1, false));
  9052. EXPECT_EQ("example.com:65535",
  9053. detail::make_host_and_port_string("example.com", 65535, false));
  9054. EXPECT_EQ("example.com:65536",
  9055. detail::make_host_and_port_string("example.com", 65536, false));
  9056. }
  9057. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9058. Server svr;
  9059. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9060. EXPECT_EQ(res.status, 400);
  9061. });
  9062. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9063. auto se = detail::scope_exit([&] {
  9064. svr.stop();
  9065. thread.join();
  9066. ASSERT_FALSE(svr.is_running());
  9067. });
  9068. svr.wait_until_ready();
  9069. Client cli(HOST, PORT);
  9070. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9071. }
  9072. TEST(InvalidHeaderCharsTest, is_field_name) {
  9073. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9074. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9075. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9076. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9077. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9078. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9079. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9080. EXPECT_FALSE(detail::fields::is_field_name(""));
  9081. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9082. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9083. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9084. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9085. }
  9086. TEST(InvalidHeaderCharsTest, is_field_value) {
  9087. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9088. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9089. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9090. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9091. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9092. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9093. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9094. EXPECT_TRUE(detail::fields::is_field_value(""));
  9095. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9096. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9097. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9098. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9099. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9100. }
  9101. TEST(InvalidHeaderCharsTest, OnServer) {
  9102. Server svr;
  9103. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9104. std::string header = "Not Set";
  9105. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9106. res.set_header(header, "value");
  9107. res.set_content("Page Content Page Content", "text/plain");
  9108. });
  9109. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9110. std::string header = "Not Set";
  9111. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9112. res.set_header("X-Test", header);
  9113. res.set_content("Page Content Page Content", "text/plain");
  9114. });
  9115. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9116. auto se = detail::scope_exit([&] {
  9117. svr.stop();
  9118. thread.join();
  9119. ASSERT_FALSE(svr.is_running());
  9120. });
  9121. svr.wait_until_ready();
  9122. Client cli(HOST, PORT);
  9123. {
  9124. auto res = cli.Get(
  9125. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9126. ASSERT_TRUE(res);
  9127. EXPECT_EQ("Page Content Page Content", res->body);
  9128. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9129. }
  9130. {
  9131. auto res = cli.Get(
  9132. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9133. ASSERT_TRUE(res);
  9134. EXPECT_EQ("Page Content Page Content", res->body);
  9135. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9136. }
  9137. }
  9138. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9139. auto handled = false;
  9140. Server svr;
  9141. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9142. thread t = thread([&] { svr.listen(HOST, PORT); });
  9143. auto se = detail::scope_exit([&] {
  9144. svr.stop();
  9145. t.join();
  9146. ASSERT_FALSE(svr.is_running());
  9147. ASSERT_FALSE(handled);
  9148. });
  9149. svr.wait_until_ready();
  9150. auto req = "POST /test HTTP/1.1\r\n"
  9151. "Content-Length: x\r\n"
  9152. "\r\n";
  9153. std::string response;
  9154. ASSERT_TRUE(send_request(1, req, &response));
  9155. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9156. response.substr(0, response.find("\r\n")));
  9157. }
  9158. #ifndef _WIN32
  9159. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9160. static constexpr char reject[] = "Unauthorized";
  9161. static constexpr char accept[] = "Upload accepted";
  9162. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9163. Server svr;
  9164. svr.set_expect_100_continue_handler(
  9165. [](const Request & /*req*/, Response &res) {
  9166. res.status = StatusCode::Unauthorized_401;
  9167. res.set_content(reject, "text/plain");
  9168. return res.status;
  9169. });
  9170. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9171. res.set_content(accept, "text/plain");
  9172. });
  9173. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9174. auto se = detail::scope_exit([&] {
  9175. svr.stop();
  9176. thread.join();
  9177. ASSERT_FALSE(svr.is_running());
  9178. });
  9179. svr.wait_until_ready();
  9180. {
  9181. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9182. curl_easy_init(), &curl_easy_cleanup};
  9183. ASSERT_NE(curl, nullptr);
  9184. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9185. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9186. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9187. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9188. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9189. &curl_slist_free_all};
  9190. ASSERT_NE(list, nullptr);
  9191. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9192. struct read_data {
  9193. size_t read_size;
  9194. size_t total_size;
  9195. } data = {0, total_size};
  9196. using read_callback_t =
  9197. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9198. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9199. void *userdata) -> size_t {
  9200. read_data *data = (read_data *)userdata;
  9201. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9202. std::fill_n(ptr, size * nmemb, 'A');
  9203. data->read_size += size * nmemb;
  9204. return size * nmemb;
  9205. };
  9206. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9207. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9208. std::vector<char> buffer;
  9209. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9210. using write_callback_t =
  9211. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9212. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9213. void *userdata) -> size_t {
  9214. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9215. buffer->reserve(buffer->size() + size * nmemb + 1);
  9216. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9217. return size * nmemb;
  9218. };
  9219. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9220. {
  9221. const auto res = curl_easy_perform(curl.get());
  9222. ASSERT_EQ(res, CURLE_OK);
  9223. }
  9224. {
  9225. auto response_code = long{};
  9226. const auto res =
  9227. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9228. ASSERT_EQ(res, CURLE_OK);
  9229. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9230. }
  9231. {
  9232. auto dl = curl_off_t{};
  9233. const auto res =
  9234. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9235. ASSERT_EQ(res, CURLE_OK);
  9236. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9237. }
  9238. {
  9239. buffer.push_back('\0');
  9240. ASSERT_STRCASEEQ(buffer.data(), reject);
  9241. }
  9242. }
  9243. }
  9244. #endif
  9245. template <typename S, typename C>
  9246. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9247. svr.Get("/stream", [&](const Request &, Response &res) {
  9248. auto data = new std::string("01234567890123456789");
  9249. res.set_content_provider(
  9250. data->size(), "text/plain",
  9251. [&, data](size_t offset, size_t length, DataSink &sink) {
  9252. const size_t DATA_CHUNK_SIZE = 4;
  9253. const auto &d = *data;
  9254. std::this_thread::sleep_for(std::chrono::seconds(1));
  9255. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9256. return true;
  9257. },
  9258. [data](bool success) {
  9259. EXPECT_FALSE(success);
  9260. delete data;
  9261. });
  9262. });
  9263. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9264. auto i = new size_t(0);
  9265. res.set_content_provider(
  9266. "text/plain",
  9267. [i](size_t, DataSink &sink) {
  9268. if (*i < 5) {
  9269. std::this_thread::sleep_for(std::chrono::seconds(1));
  9270. sink.write("abcd", 4);
  9271. (*i)++;
  9272. } else {
  9273. sink.done();
  9274. }
  9275. return true;
  9276. },
  9277. [i](bool success) {
  9278. EXPECT_FALSE(success);
  9279. delete i;
  9280. });
  9281. });
  9282. svr.Get("/chunked", [&](const Request &, Response &res) {
  9283. auto i = new size_t(0);
  9284. res.set_chunked_content_provider(
  9285. "text/plain",
  9286. [i](size_t, DataSink &sink) {
  9287. if (*i < 5) {
  9288. std::this_thread::sleep_for(std::chrono::seconds(1));
  9289. sink.os << "abcd";
  9290. (*i)++;
  9291. } else {
  9292. sink.done();
  9293. }
  9294. return true;
  9295. },
  9296. [i](bool success) {
  9297. EXPECT_FALSE(success);
  9298. delete i;
  9299. });
  9300. });
  9301. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9302. auto se = detail::scope_exit([&] {
  9303. svr.stop();
  9304. listen_thread.join();
  9305. ASSERT_FALSE(svr.is_running());
  9306. });
  9307. svr.wait_until_ready();
  9308. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9309. {
  9310. auto start = std::chrono::steady_clock::now();
  9311. auto res = cli.Get("/stream");
  9312. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9313. std::chrono::steady_clock::now() - start)
  9314. .count();
  9315. ASSERT_FALSE(res);
  9316. EXPECT_EQ(Error::Read, res.error());
  9317. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9318. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9319. }
  9320. {
  9321. auto start = std::chrono::steady_clock::now();
  9322. auto res = cli.Get("/stream_without_length");
  9323. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9324. std::chrono::steady_clock::now() - start)
  9325. .count();
  9326. ASSERT_FALSE(res);
  9327. EXPECT_EQ(Error::Read, res.error());
  9328. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9329. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9330. }
  9331. {
  9332. auto start = std::chrono::steady_clock::now();
  9333. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9334. EXPECT_EQ("abcd", string(data, data_length));
  9335. return true;
  9336. });
  9337. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9338. std::chrono::steady_clock::now() - start)
  9339. .count();
  9340. ASSERT_FALSE(res);
  9341. EXPECT_EQ(Error::Read, res.error());
  9342. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9343. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9344. }
  9345. }
  9346. TEST(MaxTimeoutTest, ContentStream) {
  9347. time_t timeout = 2000;
  9348. time_t threshold = 200;
  9349. Server svr;
  9350. Client cli("localhost", PORT);
  9351. max_timeout_test(svr, cli, timeout, threshold);
  9352. }
  9353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9354. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9355. time_t timeout = 2000;
  9356. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9357. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9358. SSLClient cli("localhost", PORT);
  9359. cli.enable_server_certificate_verification(false);
  9360. max_timeout_test(svr, cli, timeout, threshold);
  9361. }
  9362. #endif
  9363. class EventDispatcher {
  9364. public:
  9365. EventDispatcher() {}
  9366. bool wait_event(DataSink *sink) {
  9367. unique_lock<mutex> lk(m_);
  9368. int id = id_;
  9369. // Wait with timeout to prevent hanging if client disconnects
  9370. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9371. [&] { return cid_ == id; })) {
  9372. return false; // Timeout occurred
  9373. }
  9374. sink->write(message_.data(), message_.size());
  9375. return true;
  9376. }
  9377. void send_event(const string &message) {
  9378. lock_guard<mutex> lk(m_);
  9379. cid_ = id_++;
  9380. message_ = message;
  9381. cv_.notify_all();
  9382. }
  9383. private:
  9384. mutex m_;
  9385. condition_variable cv_;
  9386. atomic_int id_{0};
  9387. atomic_int cid_{-1};
  9388. string message_;
  9389. };
  9390. TEST(ClientInThreadTest, Issue2068) {
  9391. EventDispatcher ed;
  9392. Server svr;
  9393. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9394. res.set_chunked_content_provider("text/event-stream",
  9395. [&](size_t /*offset*/, DataSink &sink) {
  9396. return ed.wait_event(&sink);
  9397. });
  9398. });
  9399. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9400. svr.wait_until_ready();
  9401. thread event_thread([&] {
  9402. int id = 0;
  9403. while (svr.is_running()) {
  9404. this_thread::sleep_for(chrono::milliseconds(500));
  9405. std::stringstream ss;
  9406. ss << "data: " << id << "\n\n";
  9407. ed.send_event(ss.str());
  9408. id++;
  9409. }
  9410. });
  9411. auto se = detail::scope_exit([&] {
  9412. svr.stop();
  9413. listen_thread.join();
  9414. event_thread.join();
  9415. ASSERT_FALSE(svr.is_running());
  9416. });
  9417. {
  9418. auto client = detail::make_unique<Client>(HOST, PORT);
  9419. client->set_read_timeout(std::chrono::minutes(10));
  9420. std::atomic<bool> stop{false};
  9421. std::thread t([&] {
  9422. client->Get("/event1",
  9423. [&](const char *, size_t) -> bool { return !stop; });
  9424. });
  9425. std::this_thread::sleep_for(std::chrono::seconds(2));
  9426. stop = true;
  9427. client->stop();
  9428. t.join();
  9429. // Reset client after thread has finished
  9430. client.reset();
  9431. }
  9432. }
  9433. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9434. Server svr;
  9435. svr.Get("/", [](const Request &req, Response &res) {
  9436. EXPECT_EQ(2U, req.trailers.size());
  9437. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9438. // Denied
  9439. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9440. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9441. // Accepted
  9442. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9443. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9444. EXPECT_TRUE(req.has_trailer("X-World"));
  9445. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9446. res.set_content("ok", "text/plain");
  9447. });
  9448. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9449. auto se = detail::scope_exit([&] {
  9450. svr.stop();
  9451. t.join();
  9452. ASSERT_FALSE(svr.is_running());
  9453. });
  9454. svr.wait_until_ready();
  9455. const std::string req = "GET / HTTP/1.1\r\n"
  9456. "Transfer-Encoding: chunked\r\n"
  9457. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9458. "\r\n"
  9459. "0\r\n"
  9460. "Content-Length: 10\r\n"
  9461. "Host: internal.local\r\n"
  9462. "Content-Type: malicious/content\r\n"
  9463. "Cookie: any\r\n"
  9464. "Set-Cookie: any\r\n"
  9465. "X-Forwarded-For: attacker.com\r\n"
  9466. "X-Real-Ip: 1.1.1.1\r\n"
  9467. "X-Hello: hello\r\n"
  9468. "X-World: world\r\n"
  9469. "\r\n";
  9470. std::string res;
  9471. ASSERT_TRUE(send_request(1, req, &res));
  9472. }
  9473. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9474. Server svr;
  9475. std::string observed_remote_addr;
  9476. std::string observed_xff;
  9477. svr.Get("/ip", [&](const Request &req, Response &res) {
  9478. observed_remote_addr = req.remote_addr;
  9479. observed_xff = req.get_header_value("X-Forwarded-For");
  9480. res.set_content("ok", "text/plain");
  9481. });
  9482. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9483. auto se = detail::scope_exit([&] {
  9484. svr.stop();
  9485. t.join();
  9486. ASSERT_FALSE(svr.is_running());
  9487. });
  9488. svr.wait_until_ready();
  9489. Client cli(HOST, PORT);
  9490. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9491. ASSERT_TRUE(res);
  9492. EXPECT_EQ(StatusCode::OK_200, res->status);
  9493. EXPECT_EQ(observed_xff, "203.0.113.66");
  9494. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9495. observed_remote_addr == "127.0.0.1");
  9496. }
  9497. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9498. Server svr;
  9499. svr.set_trusted_proxies({"203.0.113.66"});
  9500. std::string observed_remote_addr;
  9501. std::string observed_xff;
  9502. svr.Get("/ip", [&](const Request &req, Response &res) {
  9503. observed_remote_addr = req.remote_addr;
  9504. observed_xff = req.get_header_value("X-Forwarded-For");
  9505. res.set_content("ok", "text/plain");
  9506. });
  9507. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9508. auto se = detail::scope_exit([&] {
  9509. svr.stop();
  9510. t.join();
  9511. ASSERT_FALSE(svr.is_running());
  9512. });
  9513. svr.wait_until_ready();
  9514. Client cli(HOST, PORT);
  9515. auto res = cli.Get("/ip");
  9516. ASSERT_TRUE(res);
  9517. EXPECT_EQ(StatusCode::OK_200, res->status);
  9518. EXPECT_EQ(observed_xff, "");
  9519. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9520. observed_remote_addr == "127.0.0.1");
  9521. }
  9522. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9523. Server svr;
  9524. svr.set_trusted_proxies({"203.0.113.66"});
  9525. std::string observed_remote_addr;
  9526. std::string observed_xff;
  9527. svr.Get("/ip", [&](const Request &req, Response &res) {
  9528. observed_remote_addr = req.remote_addr;
  9529. observed_xff = req.get_header_value("X-Forwarded-For");
  9530. res.set_content("ok", "text/plain");
  9531. });
  9532. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9533. auto se = detail::scope_exit([&] {
  9534. svr.stop();
  9535. t.join();
  9536. ASSERT_FALSE(svr.is_running());
  9537. });
  9538. svr.wait_until_ready();
  9539. Client cli(HOST, PORT);
  9540. auto res =
  9541. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9542. ASSERT_TRUE(res);
  9543. EXPECT_EQ(StatusCode::OK_200, res->status);
  9544. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9545. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9546. }
  9547. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9548. Server svr;
  9549. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9550. std::string observed_remote_addr;
  9551. std::string observed_xff;
  9552. svr.Get("/ip", [&](const Request &req, Response &res) {
  9553. observed_remote_addr = req.remote_addr;
  9554. observed_xff = req.get_header_value("X-Forwarded-For");
  9555. res.set_content("ok", "text/plain");
  9556. });
  9557. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9558. auto se = detail::scope_exit([&] {
  9559. svr.stop();
  9560. t.join();
  9561. ASSERT_FALSE(svr.is_running());
  9562. });
  9563. svr.wait_until_ready();
  9564. Client cli(HOST, PORT);
  9565. auto res = cli.Get(
  9566. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9567. ASSERT_TRUE(res);
  9568. EXPECT_EQ(StatusCode::OK_200, res->status);
  9569. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9570. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9571. }
  9572. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9573. Server svr;
  9574. svr.set_trusted_proxies({"192.0.2.45"});
  9575. std::string observed_remote_addr;
  9576. std::string observed_xff;
  9577. svr.Get("/ip", [&](const Request &req, Response &res) {
  9578. observed_remote_addr = req.remote_addr;
  9579. observed_xff = req.get_header_value("X-Forwarded-For");
  9580. res.set_content("ok", "text/plain");
  9581. });
  9582. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9583. auto se = detail::scope_exit([&] {
  9584. svr.stop();
  9585. t.join();
  9586. ASSERT_FALSE(svr.is_running());
  9587. });
  9588. svr.wait_until_ready();
  9589. Client cli(HOST, PORT);
  9590. auto res =
  9591. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9592. ASSERT_TRUE(res);
  9593. EXPECT_EQ(StatusCode::OK_200, res->status);
  9594. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9595. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9596. }
  9597. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9598. Server svr;
  9599. svr.set_trusted_proxies({"192.0.2.45"});
  9600. std::string observed_remote_addr;
  9601. std::string observed_xff;
  9602. svr.Get("/ip", [&](const Request &req, Response &res) {
  9603. observed_remote_addr = req.remote_addr;
  9604. observed_xff = req.get_header_value("X-Forwarded-For");
  9605. res.set_content("ok", "text/plain");
  9606. });
  9607. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9608. auto se = detail::scope_exit([&] {
  9609. svr.stop();
  9610. t.join();
  9611. ASSERT_FALSE(svr.is_running());
  9612. });
  9613. svr.wait_until_ready();
  9614. Client cli(HOST, PORT);
  9615. auto res = cli.Get(
  9616. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9617. ASSERT_TRUE(res);
  9618. EXPECT_EQ(StatusCode::OK_200, res->status);
  9619. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9620. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9621. }
  9622. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9623. Server svr;
  9624. svr.set_trusted_proxies({"192.0.2.45"});
  9625. std::string observed_remote_addr;
  9626. std::string observed_xff;
  9627. svr.Get("/ip", [&](const Request &req, Response &res) {
  9628. observed_remote_addr = req.remote_addr;
  9629. observed_xff = req.get_header_value("X-Forwarded-For");
  9630. res.set_content("ok", "text/plain");
  9631. });
  9632. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9633. auto se = detail::scope_exit([&] {
  9634. svr.stop();
  9635. t.join();
  9636. ASSERT_FALSE(svr.is_running());
  9637. });
  9638. svr.wait_until_ready();
  9639. Client cli(HOST, PORT);
  9640. auto res = cli.Get("/ip", {{"X-Forwarded-For",
  9641. " 198.51.100.23 , 203.0.113.66 , 192.0.2.45 "}});
  9642. ASSERT_TRUE(res);
  9643. EXPECT_EQ(StatusCode::OK_200, res->status);
  9644. // Header parser trims surrounding whitespace of the header value
  9645. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9646. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9647. }