1
0

test.cc 351 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446
  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 = req.get_header_value("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. .Put("/empty-no-content-type",
  2846. [&](const Request &req, Response &res) {
  2847. EXPECT_EQ(req.body, "");
  2848. EXPECT_FALSE(req.has_header("Content-Type"));
  2849. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2850. res.set_content("empty-no-content-type", "text/plain");
  2851. })
  2852. .Put("/put",
  2853. [&](const Request &req, Response &res) {
  2854. EXPECT_EQ(req.body, "PUT");
  2855. res.set_content(req.body, "text/plain");
  2856. })
  2857. .Put("/put-large",
  2858. [&](const Request &req, Response &res) {
  2859. EXPECT_EQ(req.body, LARGE_DATA);
  2860. res.set_content(req.body, "text/plain");
  2861. })
  2862. .Patch("/patch",
  2863. [&](const Request &req, Response &res) {
  2864. EXPECT_EQ(req.body, "PATCH");
  2865. res.set_content(req.body, "text/plain");
  2866. })
  2867. .Delete("/delete",
  2868. [&](const Request & /*req*/, Response &res) {
  2869. res.set_content("DELETE", "text/plain");
  2870. })
  2871. .Delete("/delete-body",
  2872. [&](const Request &req, Response &res) {
  2873. EXPECT_EQ(req.body, "content");
  2874. res.set_content(req.body, "text/plain");
  2875. })
  2876. .Options(R"(\*)",
  2877. [&](const Request & /*req*/, Response &res) {
  2878. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2879. })
  2880. .Get("/request-target",
  2881. [&](const Request &req, Response & /*res*/) {
  2882. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2883. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2884. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2885. })
  2886. .Get("/long-query-value",
  2887. [&](const Request &req, Response & /*res*/) {
  2888. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2889. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2890. })
  2891. .Get("/too-long-query-value",
  2892. [&](const Request &req, Response & /*res*/) {
  2893. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2894. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2895. })
  2896. .Get("/array-param",
  2897. [&](const Request &req, Response & /*res*/) {
  2898. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2899. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2900. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2901. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2902. })
  2903. .Post("/validate-no-multiple-headers",
  2904. [&](const Request &req, Response & /*res*/) {
  2905. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2906. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2907. })
  2908. .Post("/content_receiver",
  2909. [&](const Request &req, Response &res,
  2910. const ContentReader &content_reader) {
  2911. if (req.is_multipart_form_data()) {
  2912. std::vector<FormData> items;
  2913. content_reader(
  2914. [&](const FormData &file) {
  2915. items.push_back(file);
  2916. return true;
  2917. },
  2918. [&](const char *data, size_t data_length) {
  2919. items.back().content.append(data, data_length);
  2920. return true;
  2921. });
  2922. EXPECT_EQ(5u, items.size());
  2923. {
  2924. const auto &file = get_file_value(items, "text1");
  2925. EXPECT_TRUE(file.filename.empty());
  2926. EXPECT_EQ("text default", file.content);
  2927. }
  2928. {
  2929. const auto &file = get_file_value(items, "text2");
  2930. EXPECT_TRUE(file.filename.empty());
  2931. EXPECT_EQ("aωb", file.content);
  2932. }
  2933. {
  2934. const auto &file = get_file_value(items, "file1");
  2935. EXPECT_EQ("hello.txt", file.filename);
  2936. EXPECT_EQ("text/plain", file.content_type);
  2937. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2938. }
  2939. {
  2940. const auto &file = get_file_value(items, "file2");
  2941. EXPECT_EQ("world.json", file.filename);
  2942. EXPECT_EQ("application/json", file.content_type);
  2943. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2944. }
  2945. {
  2946. const auto &file = get_file_value(items, "file3");
  2947. EXPECT_TRUE(file.filename.empty());
  2948. EXPECT_EQ("application/octet-stream", file.content_type);
  2949. EXPECT_EQ(0u, file.content.size());
  2950. }
  2951. } else {
  2952. std::string body;
  2953. content_reader([&](const char *data, size_t data_length) {
  2954. EXPECT_EQ(7U, data_length);
  2955. body.append(data, data_length);
  2956. return true;
  2957. });
  2958. EXPECT_EQ(body, "content");
  2959. res.set_content(body, "text/plain");
  2960. }
  2961. })
  2962. .Put("/content_receiver",
  2963. [&](const Request & /*req*/, Response &res,
  2964. const ContentReader &content_reader) {
  2965. std::string body;
  2966. content_reader([&](const char *data, size_t data_length) {
  2967. body.append(data, data_length);
  2968. return true;
  2969. });
  2970. EXPECT_EQ(body, "content");
  2971. res.set_content(body, "text/plain");
  2972. })
  2973. .Patch("/content_receiver",
  2974. [&](const Request & /*req*/, Response &res,
  2975. const ContentReader &content_reader) {
  2976. std::string body;
  2977. content_reader([&](const char *data, size_t data_length) {
  2978. body.append(data, data_length);
  2979. return true;
  2980. });
  2981. EXPECT_EQ(body, "content");
  2982. res.set_content(body, "text/plain");
  2983. })
  2984. .Post("/query-string-and-body",
  2985. [&](const Request &req, Response & /*res*/) {
  2986. ASSERT_TRUE(req.has_param("key"));
  2987. EXPECT_EQ(req.get_param_value("key"), "value");
  2988. EXPECT_EQ(req.body, "content");
  2989. })
  2990. .Get("/last-request",
  2991. [&](const Request &req, Response & /*res*/) {
  2992. EXPECT_EQ("close", req.get_header_value("Connection"));
  2993. })
  2994. .Get(R"(/redirect/(\d+))",
  2995. [&](const Request &req, Response &res) {
  2996. auto num = std::stoi(req.matches[1]) + 1;
  2997. std::string url = "/redirect/" + std::to_string(num);
  2998. res.set_redirect(url);
  2999. })
  3000. .Post("/binary",
  3001. [&](const Request &req, Response &res) {
  3002. EXPECT_EQ(4U, req.body.size());
  3003. EXPECT_EQ("application/octet-stream",
  3004. req.get_header_value("Content-Type"));
  3005. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3006. res.set_content(req.body, "application/octet-stream");
  3007. })
  3008. .Put("/binary",
  3009. [&](const Request &req, Response &res) {
  3010. EXPECT_EQ(4U, req.body.size());
  3011. EXPECT_EQ("application/octet-stream",
  3012. req.get_header_value("Content-Type"));
  3013. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3014. res.set_content(req.body, "application/octet-stream");
  3015. })
  3016. .Patch("/binary",
  3017. [&](const Request &req, Response &res) {
  3018. EXPECT_EQ(4U, req.body.size());
  3019. EXPECT_EQ("application/octet-stream",
  3020. req.get_header_value("Content-Type"));
  3021. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3022. res.set_content(req.body, "application/octet-stream");
  3023. })
  3024. .Delete("/binary",
  3025. [&](const Request &req, Response &res) {
  3026. EXPECT_EQ(4U, req.body.size());
  3027. EXPECT_EQ("application/octet-stream",
  3028. req.get_header_value("Content-Type"));
  3029. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3030. res.set_content(req.body, "application/octet-stream");
  3031. })
  3032. .Get("/issue1772",
  3033. [&](const Request & /*req*/, Response &res) {
  3034. res.status = 401;
  3035. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3036. })
  3037. .Delete("/issue609",
  3038. [](const httplib::Request &, httplib::Response &res,
  3039. const httplib::ContentReader &) {
  3040. res.set_content("ok", "text/plain");
  3041. })
  3042. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3043. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3044. .Get("/compress",
  3045. [&](const Request & /*req*/, Response &res) {
  3046. res.set_content(
  3047. "12345678901234567890123456789012345678901234567890123456789"
  3048. "01234567890123456789012345678901234567890",
  3049. "text/plain");
  3050. })
  3051. .Get("/nocompress",
  3052. [&](const Request & /*req*/, Response &res) {
  3053. res.set_content(
  3054. "12345678901234567890123456789012345678901234567890123456789"
  3055. "01234567890123456789012345678901234567890",
  3056. "application/octet-stream");
  3057. })
  3058. .Post("/compress-multipart",
  3059. [&](const Request &req, Response & /*res*/) {
  3060. EXPECT_EQ(2u, req.form.fields.size());
  3061. ASSERT_TRUE(!req.form.has_field("???"));
  3062. {
  3063. const auto &text = req.form.get_field("key1");
  3064. EXPECT_EQ("test", text);
  3065. }
  3066. {
  3067. const auto &text = req.form.get_field("key2");
  3068. EXPECT_EQ("--abcdefg123", text);
  3069. }
  3070. })
  3071. #endif
  3072. ;
  3073. persons_["john"] = "programmer";
  3074. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3075. svr_.wait_until_ready();
  3076. }
  3077. virtual void TearDown() {
  3078. svr_.stop();
  3079. if (!request_threads_.empty()) {
  3080. std::this_thread::sleep_for(std::chrono::seconds(1));
  3081. for (auto &t : request_threads_) {
  3082. t.join();
  3083. }
  3084. }
  3085. t_.join();
  3086. }
  3087. map<string, string> persons_;
  3088. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3089. SSLClient cli_;
  3090. SSLServer svr_;
  3091. #else
  3092. Client cli_;
  3093. Server svr_;
  3094. #endif
  3095. thread t_;
  3096. std::vector<thread> request_threads_;
  3097. };
  3098. TEST_F(ServerTest, GetMethod200) {
  3099. auto res = cli_.Get("/hi");
  3100. ASSERT_TRUE(res);
  3101. EXPECT_EQ("HTTP/1.1", res->version);
  3102. EXPECT_EQ(StatusCode::OK_200, res->status);
  3103. EXPECT_EQ("OK", res->reason);
  3104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3105. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3106. EXPECT_EQ("Hello World!", res->body);
  3107. }
  3108. TEST_F(ServerTest, GetEmptyFile) {
  3109. auto res = cli_.Get("/empty_file");
  3110. ASSERT_TRUE(res);
  3111. EXPECT_EQ(StatusCode::OK_200, res->status);
  3112. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3113. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3114. EXPECT_EQ("", res->body);
  3115. }
  3116. TEST_F(ServerTest, GetFileContent) {
  3117. auto res = cli_.Get("/file_content");
  3118. ASSERT_TRUE(res);
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3121. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3122. EXPECT_EQ("test.html", res->body);
  3123. }
  3124. TEST_F(ServerTest, GetFileContentWithRange) {
  3125. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3126. ASSERT_TRUE(res);
  3127. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3128. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3129. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3130. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3131. EXPECT_EQ("est", res->body);
  3132. }
  3133. TEST_F(ServerTest, GetFileContentWithContentType) {
  3134. auto res = cli_.Get("/file_content_with_content_type");
  3135. ASSERT_TRUE(res);
  3136. EXPECT_EQ(StatusCode::OK_200, res->status);
  3137. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3138. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3139. EXPECT_EQ("file\n", res->body);
  3140. }
  3141. TEST_F(ServerTest, GetInvalidFileContent) {
  3142. auto res = cli_.Get("/invalid_file_content");
  3143. ASSERT_TRUE(res);
  3144. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3145. }
  3146. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3147. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3148. ASSERT_TRUE(res);
  3149. EXPECT_EQ("HTTP/1.1", res->version);
  3150. EXPECT_EQ(StatusCode::OK_200, res->status);
  3151. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3152. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3153. EXPECT_EQ("Hello World!", res->body);
  3154. }
  3155. TEST_F(ServerTest, GetMethod302) {
  3156. auto res = cli_.Get("/");
  3157. ASSERT_TRUE(res);
  3158. EXPECT_EQ(StatusCode::Found_302, res->status);
  3159. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3160. }
  3161. TEST_F(ServerTest, GetMethod302Redirect) {
  3162. cli_.set_follow_location(true);
  3163. auto res = cli_.Get("/");
  3164. ASSERT_TRUE(res);
  3165. EXPECT_EQ(StatusCode::OK_200, res->status);
  3166. EXPECT_EQ("Hello World!", res->body);
  3167. EXPECT_EQ("/hi", res->location);
  3168. }
  3169. TEST_F(ServerTest, GetMethod404) {
  3170. auto res = cli_.Get("/invalid");
  3171. ASSERT_TRUE(res);
  3172. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3173. }
  3174. TEST_F(ServerTest, HeadMethod200) {
  3175. auto res = cli_.Head("/hi");
  3176. ASSERT_TRUE(res);
  3177. EXPECT_EQ(StatusCode::OK_200, res->status);
  3178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3179. EXPECT_TRUE(res->body.empty());
  3180. }
  3181. TEST_F(ServerTest, HeadMethod200Static) {
  3182. auto res = cli_.Head("/mount/dir/index.html");
  3183. ASSERT_TRUE(res);
  3184. EXPECT_EQ(StatusCode::OK_200, res->status);
  3185. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3186. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3187. EXPECT_TRUE(res->body.empty());
  3188. }
  3189. TEST_F(ServerTest, HeadMethod404) {
  3190. auto res = cli_.Head("/invalid");
  3191. ASSERT_TRUE(res);
  3192. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3193. EXPECT_TRUE(res->body.empty());
  3194. }
  3195. TEST_F(ServerTest, GetMethodPersonJohn) {
  3196. auto res = cli_.Get("/person/john");
  3197. ASSERT_TRUE(res);
  3198. EXPECT_EQ(StatusCode::OK_200, res->status);
  3199. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3200. EXPECT_EQ("programmer", res->body);
  3201. }
  3202. TEST_F(ServerTest, PostMethod1) {
  3203. auto res = cli_.Get("/person/john1");
  3204. ASSERT_TRUE(res);
  3205. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3206. res = cli_.Post("/person", "name=john1&note=coder",
  3207. "application/x-www-form-urlencoded");
  3208. ASSERT_TRUE(res);
  3209. ASSERT_EQ(StatusCode::OK_200, res->status);
  3210. res = cli_.Get("/person/john1");
  3211. ASSERT_TRUE(res);
  3212. ASSERT_EQ(StatusCode::OK_200, res->status);
  3213. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3214. ASSERT_EQ("coder", res->body);
  3215. }
  3216. TEST_F(ServerTest, PostMethod2) {
  3217. auto res = cli_.Get("/person/john2");
  3218. ASSERT_TRUE(res);
  3219. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3220. Params params;
  3221. params.emplace("name", "john2");
  3222. params.emplace("note", "coder");
  3223. res = cli_.Post("/person", params);
  3224. ASSERT_TRUE(res);
  3225. ASSERT_EQ(StatusCode::OK_200, res->status);
  3226. res = cli_.Get("/person/john2");
  3227. ASSERT_TRUE(res);
  3228. ASSERT_EQ(StatusCode::OK_200, res->status);
  3229. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3230. ASSERT_EQ("coder", res->body);
  3231. }
  3232. TEST_F(ServerTest, PutMethod3) {
  3233. auto res = cli_.Get("/person/john3");
  3234. ASSERT_TRUE(res);
  3235. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3236. Params params;
  3237. params.emplace("name", "john3");
  3238. params.emplace("note", "coder");
  3239. res = cli_.Put("/person", params);
  3240. ASSERT_TRUE(res);
  3241. ASSERT_EQ(StatusCode::OK_200, res->status);
  3242. res = cli_.Get("/person/john3");
  3243. ASSERT_TRUE(res);
  3244. ASSERT_EQ(StatusCode::OK_200, res->status);
  3245. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3246. ASSERT_EQ("coder", res->body);
  3247. }
  3248. TEST_F(ServerTest, DeleteMethod1) {
  3249. auto res = cli_.Get("/person/john4");
  3250. ASSERT_TRUE(res);
  3251. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3252. Params params;
  3253. params.emplace("name", "john4");
  3254. params.emplace("note", "coder");
  3255. res = cli_.Post("/person", params);
  3256. ASSERT_TRUE(res);
  3257. ASSERT_EQ(StatusCode::OK_200, res->status);
  3258. res = cli_.Get("/person/john4");
  3259. ASSERT_TRUE(res);
  3260. ASSERT_EQ(StatusCode::OK_200, res->status);
  3261. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3262. ASSERT_EQ("coder", res->body);
  3263. Params delete_params;
  3264. delete_params.emplace("name", "john4");
  3265. res = cli_.Delete("/person", delete_params);
  3266. ASSERT_TRUE(res);
  3267. ASSERT_EQ(StatusCode::OK_200, res->status);
  3268. ASSERT_EQ("DELETED", res->body);
  3269. res = cli_.Get("/person/john4");
  3270. ASSERT_TRUE(res);
  3271. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3272. }
  3273. TEST_F(ServerTest, DeleteMethod2) {
  3274. auto res = cli_.Get("/person/john5");
  3275. ASSERT_TRUE(res);
  3276. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3277. Params params;
  3278. params.emplace("name", "john5");
  3279. params.emplace("note", "developer");
  3280. res = cli_.Post("/person", params);
  3281. ASSERT_TRUE(res);
  3282. ASSERT_EQ(StatusCode::OK_200, res->status);
  3283. res = cli_.Get("/person/john5");
  3284. ASSERT_TRUE(res);
  3285. ASSERT_EQ(StatusCode::OK_200, res->status);
  3286. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3287. ASSERT_EQ("developer", res->body);
  3288. Params delete_params;
  3289. delete_params.emplace("name", "john5");
  3290. Headers headers;
  3291. headers.emplace("Custom-Header", "test-value");
  3292. res = cli_.Delete("/person", headers, delete_params);
  3293. ASSERT_TRUE(res);
  3294. ASSERT_EQ(StatusCode::OK_200, res->status);
  3295. ASSERT_EQ("DELETED", res->body);
  3296. res = cli_.Get("/person/john5");
  3297. ASSERT_TRUE(res);
  3298. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3299. }
  3300. TEST_F(ServerTest, DeleteMethod3) {
  3301. auto res = cli_.Get("/person/john6");
  3302. ASSERT_TRUE(res);
  3303. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3304. Params params;
  3305. params.emplace("name", "john6");
  3306. params.emplace("note", "tester");
  3307. res = cli_.Post("/person", params);
  3308. ASSERT_TRUE(res);
  3309. ASSERT_EQ(StatusCode::OK_200, res->status);
  3310. res = cli_.Get("/person/john6");
  3311. ASSERT_TRUE(res);
  3312. ASSERT_EQ(StatusCode::OK_200, res->status);
  3313. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3314. ASSERT_EQ("tester", res->body);
  3315. Params delete_params;
  3316. delete_params.emplace("name", "john6");
  3317. Headers headers;
  3318. headers.emplace("Custom-Header", "test-value");
  3319. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3320. ASSERT_TRUE(res);
  3321. ASSERT_EQ(StatusCode::OK_200, res->status);
  3322. ASSERT_EQ("DELETED", res->body);
  3323. res = cli_.Get("/person/john6");
  3324. ASSERT_TRUE(res);
  3325. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3326. }
  3327. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3328. Params params;
  3329. params.emplace("json", JSON_DATA);
  3330. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3331. ASSERT_TRUE(res);
  3332. ASSERT_EQ(StatusCode::OK_200, res->status);
  3333. ASSERT_EQ(JSON_DATA, res->body);
  3334. }
  3335. TEST_F(ServerTest, PostEmptyContent) {
  3336. auto res = cli_.Post("/empty", "", "text/plain");
  3337. ASSERT_TRUE(res);
  3338. ASSERT_EQ(StatusCode::OK_200, res->status);
  3339. ASSERT_EQ("empty", res->body);
  3340. }
  3341. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3342. auto res = cli_.Post("/empty-no-content-type");
  3343. ASSERT_TRUE(res);
  3344. ASSERT_EQ(StatusCode::OK_200, res->status);
  3345. ASSERT_EQ("empty-no-content-type", res->body);
  3346. }
  3347. TEST_F(ServerTest, PostPathOnly) {
  3348. auto res = cli_.Post("/path-only");
  3349. ASSERT_TRUE(res);
  3350. ASSERT_EQ(StatusCode::OK_200, res->status);
  3351. ASSERT_EQ("path-only", res->body);
  3352. }
  3353. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3354. auto res = cli_.Post("/path-headers-only",
  3355. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3356. ASSERT_TRUE(res);
  3357. ASSERT_EQ(StatusCode::OK_200, res->status);
  3358. ASSERT_EQ("path-headers-only", res->body);
  3359. }
  3360. TEST_F(ServerTest, PostLarge) {
  3361. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3362. ASSERT_TRUE(res);
  3363. ASSERT_EQ(StatusCode::OK_200, res->status);
  3364. EXPECT_EQ(LARGE_DATA, res->body);
  3365. }
  3366. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3367. auto res = cli_.Put("/empty-no-content-type");
  3368. ASSERT_TRUE(res);
  3369. ASSERT_EQ(StatusCode::OK_200, res->status);
  3370. ASSERT_EQ("empty-no-content-type", res->body);
  3371. }
  3372. TEST_F(ServerTest, GetMethodDir) {
  3373. auto res = cli_.Get("/dir/");
  3374. ASSERT_TRUE(res);
  3375. EXPECT_EQ(StatusCode::OK_200, res->status);
  3376. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3377. auto body = R"(<html>
  3378. <head>
  3379. </head>
  3380. <body>
  3381. <a href="/dir/test.html">Test</a>
  3382. <a href="/hi">hi</a>
  3383. </body>
  3384. </html>
  3385. )";
  3386. EXPECT_EQ(body, res->body);
  3387. }
  3388. TEST_F(ServerTest, GetMethodDirTest) {
  3389. auto res = cli_.Get("/dir/test.html");
  3390. ASSERT_TRUE(res);
  3391. EXPECT_EQ(StatusCode::OK_200, res->status);
  3392. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3393. EXPECT_EQ("test.html", res->body);
  3394. }
  3395. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3396. auto res = cli_.Get("/dir/../dir/test.html");
  3397. ASSERT_TRUE(res);
  3398. EXPECT_EQ(StatusCode::OK_200, res->status);
  3399. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3400. EXPECT_EQ("test.html", res->body);
  3401. }
  3402. TEST_F(ServerTest, GetMethodInvalidPath) {
  3403. auto res = cli_.Get("/dir/../test.html");
  3404. ASSERT_TRUE(res);
  3405. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3406. }
  3407. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3408. auto res = cli_.Get("/../www/dir/test.html");
  3409. ASSERT_TRUE(res);
  3410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3411. }
  3412. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3413. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3414. ASSERT_TRUE(res);
  3415. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3416. }
  3417. TEST_F(ServerTest, GetMethodDirMountTest) {
  3418. auto res = cli_.Get("/mount/dir/test.html");
  3419. ASSERT_TRUE(res);
  3420. EXPECT_EQ(StatusCode::OK_200, res->status);
  3421. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3422. EXPECT_EQ("test.html", res->body);
  3423. }
  3424. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3425. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3426. ASSERT_TRUE(res);
  3427. EXPECT_EQ(StatusCode::OK_200, res->status);
  3428. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3429. EXPECT_EQ("test.html", res->body);
  3430. }
  3431. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3432. auto res = cli_.Get("/mount/dir/../test.html");
  3433. ASSERT_TRUE(res);
  3434. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3435. }
  3436. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3437. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3438. ASSERT_TRUE(res);
  3439. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3440. }
  3441. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3442. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3443. ASSERT_TRUE(res);
  3444. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3445. }
  3446. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3447. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3450. }
  3451. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3452. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3453. ASSERT_TRUE(res);
  3454. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3455. }
  3456. TEST_F(ServerTest, PostMethod303) {
  3457. auto res = cli_.Post("/1", "body", "text/plain");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3460. EXPECT_EQ("/2", res->get_header_value("Location"));
  3461. }
  3462. TEST_F(ServerTest, PostMethod303Redirect) {
  3463. cli_.set_follow_location(true);
  3464. auto res = cli_.Post("/1", "body", "text/plain");
  3465. ASSERT_TRUE(res);
  3466. EXPECT_EQ(StatusCode::OK_200, res->status);
  3467. EXPECT_EQ("redirected.", res->body);
  3468. EXPECT_EQ("/2", res->location);
  3469. }
  3470. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3471. auto res = cli_.Get("/dir/test.abcde");
  3472. ASSERT_TRUE(res);
  3473. EXPECT_EQ(StatusCode::OK_200, res->status);
  3474. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3475. EXPECT_EQ("abcde", res->body);
  3476. }
  3477. TEST_F(ServerTest, StaticFileRange) {
  3478. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3479. ASSERT_TRUE(res);
  3480. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3481. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3482. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3483. EXPECT_EQ(true, res->has_header("Content-Range"));
  3484. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3485. EXPECT_EQ(std::string("cd"), res->body);
  3486. }
  3487. TEST_F(ServerTest, StaticFileRanges) {
  3488. auto res =
  3489. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3490. ASSERT_TRUE(res);
  3491. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3492. EXPECT_TRUE(
  3493. res->get_header_value("Content-Type")
  3494. .find(
  3495. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3496. 0);
  3497. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3498. }
  3499. TEST_F(ServerTest, StaticFileRangeHead) {
  3500. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3501. ASSERT_TRUE(res);
  3502. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3503. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3504. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3505. EXPECT_EQ(true, res->has_header("Content-Range"));
  3506. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3507. }
  3508. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3509. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3510. ASSERT_TRUE(res);
  3511. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3513. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3514. EXPECT_EQ(true, res->has_header("Content-Range"));
  3515. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3516. res->get_header_value("Content-Range"));
  3517. EXPECT_EQ("LAST\n", res->body);
  3518. }
  3519. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3520. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3521. ASSERT_TRUE(res);
  3522. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3523. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3524. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3525. EXPECT_EQ(true, res->has_header("Content-Range"));
  3526. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3527. }
  3528. TEST_F(ServerTest, StaticFileBigFile) {
  3529. auto res = cli_.Get("/dir/1MB.txt");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::OK_200, res->status);
  3532. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3533. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3534. }
  3535. TEST_F(ServerTest, InvalidBaseDirMount) {
  3536. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3537. }
  3538. TEST_F(ServerTest, Binary) {
  3539. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3540. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3541. "application/octet-stream");
  3542. ASSERT_TRUE(res);
  3543. ASSERT_EQ(StatusCode::OK_200, res->status);
  3544. ASSERT_EQ(4U, res->body.size());
  3545. res = cli_.Put("/binary", binary.data(), binary.size(),
  3546. "application/octet-stream");
  3547. ASSERT_TRUE(res);
  3548. ASSERT_EQ(StatusCode::OK_200, res->status);
  3549. ASSERT_EQ(4U, res->body.size());
  3550. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3551. "application/octet-stream");
  3552. ASSERT_TRUE(res);
  3553. ASSERT_EQ(StatusCode::OK_200, res->status);
  3554. ASSERT_EQ(4U, res->body.size());
  3555. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3556. "application/octet-stream");
  3557. ASSERT_TRUE(res);
  3558. ASSERT_EQ(StatusCode::OK_200, res->status);
  3559. ASSERT_EQ(4U, res->body.size());
  3560. }
  3561. TEST_F(ServerTest, BinaryString) {
  3562. auto binary = std::string("\x00\x01\x02\x03", 4);
  3563. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3564. ASSERT_TRUE(res);
  3565. ASSERT_EQ(StatusCode::OK_200, res->status);
  3566. ASSERT_EQ(4U, res->body.size());
  3567. res = cli_.Put("/binary", binary, "application/octet-stream");
  3568. ASSERT_TRUE(res);
  3569. ASSERT_EQ(StatusCode::OK_200, res->status);
  3570. ASSERT_EQ(4U, res->body.size());
  3571. res = cli_.Patch("/binary", binary, "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_.Delete("/binary", binary, "application/octet-stream");
  3576. ASSERT_TRUE(res);
  3577. ASSERT_EQ(StatusCode::OK_200, res->status);
  3578. ASSERT_EQ(4U, res->body.size());
  3579. }
  3580. TEST_F(ServerTest, EmptyRequest) {
  3581. auto res = cli_.Get("");
  3582. ASSERT_TRUE(!res);
  3583. EXPECT_EQ(Error::Connection, res.error());
  3584. }
  3585. TEST_F(ServerTest, LongRequest) {
  3586. std::string request;
  3587. for (size_t i = 0; i < 545; i++) {
  3588. request += "/TooLongRequest";
  3589. }
  3590. request += "OK";
  3591. auto res = cli_.Get(request.c_str());
  3592. ASSERT_TRUE(res);
  3593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3594. }
  3595. TEST_F(ServerTest, TooLongRequest) {
  3596. std::string request;
  3597. for (size_t i = 0; i < 546; i++) {
  3598. request += "/TooLongRequest";
  3599. }
  3600. request += "_NG";
  3601. auto res = cli_.Get(request.c_str());
  3602. ASSERT_TRUE(res);
  3603. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3604. }
  3605. TEST_F(ServerTest, AlmostTooLongRequest) {
  3606. // test for #2046 - URI length check shouldn't include other content on req
  3607. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3608. // leading /, space, HTTP/1.1)
  3609. std::string request =
  3610. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3611. auto res = cli_.Get(request.c_str());
  3612. ASSERT_TRUE(res);
  3613. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3614. }
  3615. TEST_F(ServerTest, LongHeader) {
  3616. Request req;
  3617. req.method = "GET";
  3618. req.path = "/hi";
  3619. std::string host_and_port;
  3620. host_and_port += HOST;
  3621. host_and_port += ":";
  3622. host_and_port += std::to_string(PORT);
  3623. req.headers.emplace("Host", host_and_port.c_str());
  3624. req.headers.emplace("Accept", "*/*");
  3625. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3626. req.headers.emplace(
  3627. "Header-Name",
  3628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3656. "@@@@@@@@@@@@@@@@");
  3657. auto res = std::make_shared<Response>();
  3658. auto error = Error::Success;
  3659. auto ret = cli_.send(req, *res, error);
  3660. ASSERT_TRUE(ret);
  3661. EXPECT_EQ(StatusCode::OK_200, res->status);
  3662. }
  3663. TEST_F(ServerTest, LongQueryValue) {
  3664. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3665. ASSERT_TRUE(res);
  3666. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3667. }
  3668. TEST_F(ServerTest, TooLongQueryValue) {
  3669. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3670. ASSERT_FALSE(res);
  3671. EXPECT_EQ(Error::Read, res.error());
  3672. }
  3673. TEST_F(ServerTest, TooLongHeader) {
  3674. Request req;
  3675. req.method = "GET";
  3676. req.path = "/hi";
  3677. std::string host_and_port;
  3678. host_and_port += HOST;
  3679. host_and_port += ":";
  3680. host_and_port += std::to_string(PORT);
  3681. req.headers.emplace("Host", host_and_port.c_str());
  3682. req.headers.emplace("Accept", "*/*");
  3683. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3684. req.headers.emplace(
  3685. "Header-Name",
  3686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3714. "@@@@@@@@@@@@@@@@@");
  3715. auto res = std::make_shared<Response>();
  3716. auto error = Error::Success;
  3717. auto ret = cli_.send(req, *res, error);
  3718. ASSERT_TRUE(ret);
  3719. EXPECT_EQ(StatusCode::OK_200, res->status);
  3720. }
  3721. TEST_F(ServerTest, HeaderCountAtLimit) {
  3722. // Test with headers just under the 100 limit
  3723. httplib::Headers headers;
  3724. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3725. // This should keep us just under the 100 header limit
  3726. for (int i = 0; i < 95; i++) {
  3727. std::string name = "X-Test-Header-" + std::to_string(i);
  3728. std::string value = "value" + std::to_string(i);
  3729. headers.emplace(name, value);
  3730. }
  3731. // This should work fine as we're under the limit
  3732. auto res = cli_.Get("/hi", headers);
  3733. EXPECT_TRUE(res);
  3734. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3735. }
  3736. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3737. // Test with many headers to exceed the 100 limit
  3738. httplib::Headers headers;
  3739. // Add 150 headers to definitely exceed the 100 limit
  3740. for (int i = 0; i < 150; i++) {
  3741. std::string name = "X-Test-Header-" + std::to_string(i);
  3742. std::string value = "value" + std::to_string(i);
  3743. headers.emplace(name, value);
  3744. }
  3745. // This should fail due to exceeding header count limit
  3746. auto res = cli_.Get("/hi", headers);
  3747. // The request should either fail or return 400 Bad Request
  3748. if (res) {
  3749. // If we get a response, it should be 400 Bad Request
  3750. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3751. } else {
  3752. // Or the request should fail entirely
  3753. EXPECT_FALSE(res);
  3754. }
  3755. }
  3756. TEST_F(ServerTest, PercentEncoding) {
  3757. auto res = cli_.Get("/e%6edwith%");
  3758. ASSERT_TRUE(res);
  3759. EXPECT_EQ(StatusCode::OK_200, res->status);
  3760. }
  3761. TEST_F(ServerTest, PercentEncodingUnicode) {
  3762. auto res = cli_.Get("/e%u006edwith%");
  3763. ASSERT_TRUE(res);
  3764. EXPECT_EQ(StatusCode::OK_200, res->status);
  3765. }
  3766. TEST_F(ServerTest, InvalidPercentEncoding) {
  3767. auto res = cli_.Get("/%endwith%");
  3768. ASSERT_TRUE(res);
  3769. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3770. }
  3771. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3772. auto res = cli_.Get("/%uendwith%");
  3773. ASSERT_TRUE(res);
  3774. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3775. }
  3776. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3777. auto res = cli_.Get("/hello?aaa=bbb%");
  3778. ASSERT_TRUE(res);
  3779. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3780. }
  3781. TEST_F(ServerTest, PlusSignEncoding) {
  3782. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3783. ASSERT_TRUE(res);
  3784. EXPECT_EQ(StatusCode::OK_200, res->status);
  3785. EXPECT_EQ("a +b", res->body);
  3786. }
  3787. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3788. // This test simulates a potential DoS attack using many headers
  3789. // to verify our security fix prevents memory exhaustion
  3790. httplib::Headers attack_headers;
  3791. // Attempt to add many headers like an attacker would (200 headers to far
  3792. // exceed limit)
  3793. for (int i = 0; i < 200; i++) {
  3794. std::string name = "X-Attack-Header-" + std::to_string(i);
  3795. std::string value = "attack_payload_" + std::to_string(i);
  3796. attack_headers.emplace(name, value);
  3797. }
  3798. // Try to POST with excessive headers
  3799. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3800. // Should either fail or return 400 Bad Request due to security limit
  3801. if (res) {
  3802. // If we get a response, it should be 400 Bad Request
  3803. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3804. } else {
  3805. // Request failed, which is the expected behavior for DoS protection
  3806. EXPECT_FALSE(res);
  3807. }
  3808. }
  3809. TEST_F(ServerTest, MultipartFormData) {
  3810. UploadFormDataItems items = {
  3811. {"text1", "text default", "", ""},
  3812. {"text2", "aωb", "", ""},
  3813. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3814. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3815. {"file3", "", "", "application/octet-stream"},
  3816. {"file4", "", "", " application/json tmp-string "}};
  3817. auto res = cli_.Post("/multipart", items);
  3818. ASSERT_TRUE(res);
  3819. EXPECT_EQ(StatusCode::OK_200, res->status);
  3820. }
  3821. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3822. UploadFormDataItems items = {
  3823. {"text", "default text", "", ""},
  3824. {"multi_text1", "aaaaa", "", ""},
  3825. {"multi_text1", "bbbbb", "", ""},
  3826. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3827. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3828. "application/json"},
  3829. };
  3830. auto res = cli_.Post("/multipart/multi_file_values", items);
  3831. ASSERT_TRUE(res);
  3832. EXPECT_EQ(StatusCode::OK_200, res->status);
  3833. }
  3834. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3835. auto res = cli_.Get("/hi");
  3836. ASSERT_TRUE(res);
  3837. EXPECT_EQ(StatusCode::OK_200, res->status);
  3838. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3839. EXPECT_EQ("Hello World!", res->body);
  3840. }
  3841. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3842. Request req;
  3843. req.method = "POST";
  3844. req.path = "/chunked";
  3845. std::string host_and_port;
  3846. host_and_port += HOST;
  3847. host_and_port += ":";
  3848. host_and_port += std::to_string(PORT);
  3849. req.headers.emplace("Host", host_and_port.c_str());
  3850. req.headers.emplace("Accept", "*/*");
  3851. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3852. req.headers.emplace("Content-Type", "text/plain");
  3853. req.headers.emplace("Content-Length", "0");
  3854. req.headers.emplace(
  3855. "Transfer-Encoding",
  3856. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3857. // Client does not chunk, so make a chunked body manually.
  3858. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3859. auto res = std::make_shared<Response>();
  3860. auto error = Error::Success;
  3861. auto ret = cli_.send(req, *res, error);
  3862. ASSERT_TRUE(ret);
  3863. EXPECT_EQ(StatusCode::OK_200, res->status);
  3864. }
  3865. TEST_F(ServerTest, GetStreamed2) {
  3866. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3867. ASSERT_TRUE(res);
  3868. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3869. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3870. EXPECT_EQ(true, res->has_header("Content-Range"));
  3871. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3872. EXPECT_EQ(std::string("ab"), res->body);
  3873. }
  3874. TEST_F(ServerTest, GetStreamed) {
  3875. auto res = cli_.Get("/streamed");
  3876. ASSERT_TRUE(res);
  3877. EXPECT_EQ(StatusCode::OK_200, res->status);
  3878. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3879. EXPECT_EQ(std::string("aaabbb"), res->body);
  3880. }
  3881. TEST_F(ServerTest, GetStreamedWithRange1) {
  3882. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3883. ASSERT_TRUE(res);
  3884. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3885. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3886. EXPECT_EQ(true, res->has_header("Content-Range"));
  3887. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3888. EXPECT_EQ(std::string("def"), res->body);
  3889. }
  3890. TEST_F(ServerTest, GetStreamedWithRange2) {
  3891. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3892. ASSERT_TRUE(res);
  3893. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3894. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3895. EXPECT_EQ(true, res->has_header("Content-Range"));
  3896. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3897. EXPECT_EQ(std::string("bcdefg"), res->body);
  3898. }
  3899. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3900. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3901. ASSERT_TRUE(res);
  3902. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3903. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3904. EXPECT_EQ(true, res->has_header("Content-Range"));
  3905. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3906. EXPECT_EQ(std::string("efg"), res->body);
  3907. }
  3908. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3909. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3910. ASSERT_TRUE(res);
  3911. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3912. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3913. EXPECT_EQ(false, res->has_header("Content-Range"));
  3914. EXPECT_EQ(0U, res->body.size());
  3915. }
  3916. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3917. auto res = cli_.Get("/streamed-with-range",
  3918. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3919. "92233720368547758079223372036854775807"}});
  3920. ASSERT_TRUE(res);
  3921. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3922. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3923. EXPECT_EQ(false, res->has_header("Content-Range"));
  3924. EXPECT_EQ(0U, res->body.size());
  3925. }
  3926. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3927. auto res = cli_.Get(
  3928. "/with-range",
  3929. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3930. {"Accept-Encoding", ""}});
  3931. ASSERT_TRUE(res);
  3932. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3933. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3934. EXPECT_EQ(true, res->has_header("Content-Range"));
  3935. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3936. EXPECT_EQ(std::string("abcdefg"), res->body);
  3937. }
  3938. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3939. auto res = cli_.Get("/with-range", {
  3940. {"Range", "bytes=0-"},
  3941. {"Accept-Encoding", ""},
  3942. });
  3943. ASSERT_TRUE(res);
  3944. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3945. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3946. EXPECT_EQ(true, res->has_header("Content-Range"));
  3947. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3948. EXPECT_EQ(std::string("abcdefg"), res->body);
  3949. }
  3950. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3951. auto res =
  3952. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3953. ASSERT_TRUE(res);
  3954. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3955. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3956. EXPECT_EQ(false, res->has_header("Content-Range"));
  3957. EXPECT_EQ(267U, res->body.size());
  3958. // Check that both range contents are present
  3959. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3960. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3961. // Check that Content-Range headers are present for both ranges
  3962. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3963. std::string::npos);
  3964. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3965. std::string::npos);
  3966. }
  3967. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3968. Ranges ranges;
  3969. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3970. ranges.emplace_back(0, -1);
  3971. }
  3972. auto res =
  3973. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  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, GetStreamedWithOverwrapping) {
  3981. auto res =
  3982. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3983. ASSERT_TRUE(res);
  3984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3985. EXPECT_EQ(5U, res->body.size());
  3986. // Check that overlapping ranges are coalesced into a single range
  3987. EXPECT_EQ("bcdef", res->body);
  3988. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3989. // Should be single range, not multipart
  3990. EXPECT_TRUE(res->has_header("Content-Range"));
  3991. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3992. }
  3993. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3994. auto res =
  3995. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3996. ASSERT_TRUE(res);
  3997. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3998. EXPECT_EQ(268U, res->body.size());
  3999. // Check that both range contents are present
  4000. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4001. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4002. // Check that Content-Range headers are present for both ranges
  4003. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4004. std::string::npos);
  4005. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4006. std::string::npos);
  4007. }
  4008. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4009. auto res =
  4010. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4013. EXPECT_EQ(269U, res->body.size());
  4014. // Check that both duplicate range contents are present
  4015. size_t first_abc = res->body.find("abc\r\n");
  4016. EXPECT_TRUE(first_abc != std::string::npos);
  4017. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4018. EXPECT_TRUE(second_abc != std::string::npos);
  4019. // Check that Content-Range headers are present for both ranges
  4020. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4021. EXPECT_TRUE(first_range != std::string::npos);
  4022. size_t second_range =
  4023. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4024. EXPECT_TRUE(second_range != std::string::npos);
  4025. }
  4026. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4027. auto res = cli_.Get("/streamed-with-range?error",
  4028. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4029. ASSERT_TRUE(res);
  4030. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4031. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4032. EXPECT_EQ(false, res->has_header("Content-Range"));
  4033. EXPECT_EQ(0U, res->body.size());
  4034. }
  4035. TEST_F(ServerTest, GetStreamedEndless) {
  4036. uint64_t offset = 0;
  4037. auto res = cli_.Get("/streamed-cancel",
  4038. [&](const char * /*data*/, uint64_t data_length) {
  4039. if (offset < 100) {
  4040. offset += data_length;
  4041. return true;
  4042. }
  4043. return false;
  4044. });
  4045. ASSERT_TRUE(!res);
  4046. EXPECT_EQ(Error::Canceled, res.error());
  4047. }
  4048. TEST_F(ServerTest, ClientStop) {
  4049. std::atomic_size_t count{4};
  4050. std::vector<std::thread> threads;
  4051. for (auto i = count.load(); i != 0; --i) {
  4052. threads.emplace_back([&]() {
  4053. auto res = cli_.Get("/streamed-cancel",
  4054. [&](const char *, uint64_t) { return true; });
  4055. --count;
  4056. ASSERT_TRUE(!res);
  4057. EXPECT_TRUE(res.error() == Error::Canceled ||
  4058. res.error() == Error::Read || res.error() == Error::Write);
  4059. });
  4060. }
  4061. std::this_thread::sleep_for(std::chrono::seconds(2));
  4062. while (count != 0) {
  4063. cli_.stop();
  4064. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4065. }
  4066. for (auto &t : threads) {
  4067. t.join();
  4068. }
  4069. }
  4070. TEST_F(ServerTest, GetWithRange1) {
  4071. auto res = cli_.Get("/with-range", {
  4072. make_range_header({{3, 5}}),
  4073. {"Accept-Encoding", ""},
  4074. });
  4075. ASSERT_TRUE(res);
  4076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4077. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4078. EXPECT_EQ(true, res->has_header("Content-Range"));
  4079. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4080. EXPECT_EQ(std::string("def"), res->body);
  4081. }
  4082. TEST_F(ServerTest, GetWithRange2) {
  4083. auto res = cli_.Get("/with-range", {
  4084. make_range_header({{1, -1}}),
  4085. {"Accept-Encoding", ""},
  4086. });
  4087. ASSERT_TRUE(res);
  4088. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4089. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4090. EXPECT_EQ(true, res->has_header("Content-Range"));
  4091. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4092. EXPECT_EQ(std::string("bcdefg"), res->body);
  4093. }
  4094. TEST_F(ServerTest, GetWithRange3) {
  4095. auto res = cli_.Get("/with-range", {
  4096. make_range_header({{0, 0}}),
  4097. {"Accept-Encoding", ""},
  4098. });
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4101. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ(true, res->has_header("Content-Range"));
  4103. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4104. EXPECT_EQ(std::string("a"), res->body);
  4105. }
  4106. TEST_F(ServerTest, GetWithRange4) {
  4107. auto res = cli_.Get("/with-range", {
  4108. make_range_header({{-1, 2}}),
  4109. {"Accept-Encoding", ""},
  4110. });
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4113. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4114. EXPECT_EQ(true, res->has_header("Content-Range"));
  4115. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4116. EXPECT_EQ(std::string("fg"), res->body);
  4117. }
  4118. TEST_F(ServerTest, GetWithRange5) {
  4119. auto res = cli_.Get("/with-range", {
  4120. make_range_header({{0, 5}}),
  4121. {"Accept-Encoding", ""},
  4122. });
  4123. ASSERT_TRUE(res);
  4124. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4125. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4126. EXPECT_EQ(true, res->has_header("Content-Range"));
  4127. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4128. EXPECT_EQ(std::string("abcdef"), res->body);
  4129. }
  4130. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4131. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4132. ASSERT_TRUE(res);
  4133. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4134. }
  4135. TEST_F(ServerTest, GetWithRangeMultipart) {
  4136. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4139. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4140. EXPECT_EQ(false, res->has_header("Content-Range"));
  4141. EXPECT_EQ(267U, res->body.size());
  4142. }
  4143. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4144. auto res =
  4145. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4146. ASSERT_TRUE(res);
  4147. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4148. }
  4149. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4150. auto res = cli_.Get("/with-range-customized-response",
  4151. {{make_range_header({{1, 2}})}});
  4152. ASSERT_TRUE(res);
  4153. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4154. EXPECT_EQ(true, res->has_header("Content-Length"));
  4155. EXPECT_EQ(false, res->has_header("Content-Range"));
  4156. EXPECT_EQ(JSON_DATA, res->body);
  4157. }
  4158. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4159. auto res = cli_.Get("/with-range-customized-response",
  4160. {{make_range_header({{1, 2}, {4, 5}})}});
  4161. ASSERT_TRUE(res);
  4162. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4163. EXPECT_EQ(true, res->has_header("Content-Length"));
  4164. EXPECT_EQ(false, res->has_header("Content-Range"));
  4165. EXPECT_EQ(JSON_DATA, res->body);
  4166. }
  4167. TEST_F(ServerTest, Issue1772) {
  4168. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4169. ASSERT_TRUE(res);
  4170. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4171. }
  4172. TEST_F(ServerTest, Issue609) {
  4173. auto res = cli_.Delete("/issue609");
  4174. ASSERT_TRUE(res);
  4175. EXPECT_EQ(StatusCode::OK_200, res->status);
  4176. EXPECT_EQ(std::string("ok"), res->body);
  4177. }
  4178. TEST_F(ServerTest, GetStreamedChunked) {
  4179. auto res = cli_.Get("/streamed-chunked");
  4180. ASSERT_TRUE(res);
  4181. EXPECT_EQ(StatusCode::OK_200, res->status);
  4182. EXPECT_EQ(std::string("123456789"), res->body);
  4183. }
  4184. TEST_F(ServerTest, GetStreamedChunked2) {
  4185. auto res = cli_.Get("/streamed-chunked2");
  4186. ASSERT_TRUE(res);
  4187. EXPECT_EQ(StatusCode::OK_200, res->status);
  4188. EXPECT_EQ(std::string("123456789"), res->body);
  4189. }
  4190. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4191. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4192. ASSERT_TRUE(res);
  4193. EXPECT_EQ(StatusCode::OK_200, res->status);
  4194. EXPECT_EQ(std::string("123456789"), res->body);
  4195. EXPECT_TRUE(res->has_header("Trailer"));
  4196. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4197. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4198. // Trailers are now stored separately from headers (security fix)
  4199. EXPECT_EQ(2U, res->trailers.size());
  4200. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4201. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4202. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4203. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4204. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4205. // Verify trailers are NOT in headers (security verification)
  4206. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4207. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4208. }
  4209. TEST_F(ServerTest, LargeChunkedPost) {
  4210. Request req;
  4211. req.method = "POST";
  4212. req.path = "/large-chunked";
  4213. std::string host_and_port;
  4214. host_and_port += HOST;
  4215. host_and_port += ":";
  4216. host_and_port += std::to_string(PORT);
  4217. req.headers.emplace("Host", host_and_port.c_str());
  4218. req.headers.emplace("Accept", "*/*");
  4219. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4220. req.headers.emplace("Content-Type", "text/plain");
  4221. req.headers.emplace("Content-Length", "0");
  4222. req.headers.emplace("Transfer-Encoding", "chunked");
  4223. std::string long_string(30 * 1024u, 'a');
  4224. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4225. // Attempt to make a large enough post to exceed OS buffers, to test that
  4226. // the server handles short reads if the full chunk data isn't available.
  4227. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4228. auto res = std::make_shared<Response>();
  4229. auto error = Error::Success;
  4230. auto ret = cli_.send(req, *res, error);
  4231. ASSERT_TRUE(ret);
  4232. EXPECT_EQ(StatusCode::OK_200, res->status);
  4233. }
  4234. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4235. auto res = cli_.Get("/remote_addr");
  4236. ASSERT_TRUE(res);
  4237. EXPECT_EQ(StatusCode::OK_200, res->status);
  4238. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4239. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4240. }
  4241. TEST_F(ServerTest, GetMethodLocalAddr) {
  4242. auto res = cli_.Get("/local_addr");
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ(StatusCode::OK_200, res->status);
  4245. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4246. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4247. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4248. }
  4249. TEST_F(ServerTest, HTTPResponseSplitting) {
  4250. auto res = cli_.Get("/http_response_splitting");
  4251. ASSERT_TRUE(res);
  4252. EXPECT_EQ(StatusCode::OK_200, res->status);
  4253. }
  4254. TEST_F(ServerTest, SlowRequest) {
  4255. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4256. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4257. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4258. }
  4259. #if 0
  4260. TEST_F(ServerTest, SlowPost) {
  4261. char buffer[64 * 1024];
  4262. memset(buffer, 0x42, sizeof(buffer));
  4263. auto res = cli_.Post(
  4264. "/slowpost", 64 * 1024 * 1024,
  4265. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4266. auto ret = sink.write(buffer, sizeof(buffer));
  4267. EXPECT_TRUE(ret);
  4268. return true;
  4269. },
  4270. "text/plain");
  4271. ASSERT_TRUE(res);
  4272. EXPECT_EQ(StatusCode::OK_200, res->status);
  4273. }
  4274. TEST_F(ServerTest, SlowPostFail) {
  4275. char buffer[64 * 1024];
  4276. memset(buffer, 0x42, sizeof(buffer));
  4277. cli_.set_write_timeout(std::chrono::seconds(0));
  4278. auto res = cli_.Post(
  4279. "/slowpost", 64 * 1024 * 1024,
  4280. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4281. sink.write(buffer, sizeof(buffer));
  4282. return true;
  4283. },
  4284. "text/plain");
  4285. ASSERT_TRUE(!res);
  4286. EXPECT_EQ(Error::Write, res.error());
  4287. }
  4288. #endif
  4289. TEST_F(ServerTest, Put) {
  4290. auto res = cli_.Put("/put", "PUT", "text/plain");
  4291. ASSERT_TRUE(res);
  4292. EXPECT_EQ(StatusCode::OK_200, res->status);
  4293. EXPECT_EQ("PUT", res->body);
  4294. }
  4295. TEST_F(ServerTest, PutWithContentProvider) {
  4296. auto res = cli_.Put(
  4297. "/put", 3,
  4298. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4299. sink.os << "PUT";
  4300. return true;
  4301. },
  4302. "text/plain");
  4303. ASSERT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::OK_200, res->status);
  4305. EXPECT_EQ("PUT", res->body);
  4306. }
  4307. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4308. auto res = cli_.Post(
  4309. "/post", 42,
  4310. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4311. return false;
  4312. },
  4313. "text/plain");
  4314. ASSERT_TRUE(!res);
  4315. EXPECT_EQ(Error::Canceled, res.error());
  4316. }
  4317. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4318. auto res = cli_.Put(
  4319. "/put",
  4320. [](size_t /*offset*/, DataSink &sink) {
  4321. sink.os << "PUT";
  4322. sink.done();
  4323. return true;
  4324. },
  4325. "text/plain");
  4326. ASSERT_TRUE(res);
  4327. EXPECT_EQ(StatusCode::OK_200, res->status);
  4328. EXPECT_EQ("PUT", res->body);
  4329. }
  4330. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4331. auto res = cli_.Post(
  4332. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4333. "text/plain");
  4334. ASSERT_TRUE(!res);
  4335. EXPECT_EQ(Error::Canceled, res.error());
  4336. }
  4337. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4338. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4339. cli_.set_compress(true);
  4340. auto res = cli_.Put(
  4341. "/put", 3,
  4342. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4343. sink.os << "PUT";
  4344. return true;
  4345. },
  4346. "text/plain");
  4347. ASSERT_TRUE(res);
  4348. EXPECT_EQ(StatusCode::OK_200, res->status);
  4349. EXPECT_EQ("PUT", res->body);
  4350. }
  4351. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4352. cli_.set_compress(true);
  4353. auto res = cli_.Post(
  4354. "/post", 42,
  4355. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4356. return false;
  4357. },
  4358. "text/plain");
  4359. ASSERT_TRUE(!res);
  4360. EXPECT_EQ(Error::Canceled, res.error());
  4361. }
  4362. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4363. cli_.set_compress(true);
  4364. auto res = cli_.Put(
  4365. "/put",
  4366. [](size_t /*offset*/, DataSink &sink) {
  4367. sink.os << "PUT";
  4368. sink.done();
  4369. return true;
  4370. },
  4371. "text/plain");
  4372. ASSERT_TRUE(res);
  4373. EXPECT_EQ(StatusCode::OK_200, res->status);
  4374. EXPECT_EQ("PUT", res->body);
  4375. }
  4376. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4377. cli_.set_compress(true);
  4378. auto res = cli_.Post(
  4379. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4380. "text/plain");
  4381. ASSERT_TRUE(!res);
  4382. EXPECT_EQ(Error::Canceled, res.error());
  4383. }
  4384. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4385. cli_.set_compress(true);
  4386. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4387. ASSERT_TRUE(res);
  4388. EXPECT_EQ(StatusCode::OK_200, res->status);
  4389. EXPECT_EQ(LARGE_DATA, res->body);
  4390. }
  4391. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4392. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4393. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4394. Client cli(s.c_str());
  4395. cli.enable_server_certificate_verification(false);
  4396. #else
  4397. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4398. Client cli(s.c_str());
  4399. #endif
  4400. cli.set_compress(true);
  4401. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4402. ASSERT_TRUE(res);
  4403. EXPECT_EQ(StatusCode::OK_200, res->status);
  4404. EXPECT_EQ(LARGE_DATA, res->body);
  4405. // The compressed size should be less than a 10th of the original. May vary
  4406. // depending on the zlib library.
  4407. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4408. static_cast<uint64_t>(10 * 1024 * 1024));
  4409. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4410. }
  4411. TEST_F(ServerTest, PutContentWithDeflate) {
  4412. cli_.set_compress(false);
  4413. Headers headers;
  4414. headers.emplace("Content-Encoding", "deflate");
  4415. // PUT in deflate format:
  4416. auto res = cli_.Put("/put", headers,
  4417. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4418. ASSERT_TRUE(res);
  4419. EXPECT_EQ(StatusCode::OK_200, res->status);
  4420. EXPECT_EQ("PUT", res->body);
  4421. }
  4422. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4423. Headers headers;
  4424. headers.emplace("Accept-Encoding", "gzip, deflate");
  4425. auto res = cli_.Get("/streamed-chunked", headers);
  4426. ASSERT_TRUE(res);
  4427. EXPECT_EQ(StatusCode::OK_200, res->status);
  4428. EXPECT_EQ(std::string("123456789"), res->body);
  4429. }
  4430. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4431. Headers headers;
  4432. headers.emplace("Accept-Encoding", "gzip, deflate");
  4433. auto res = cli_.Get("/streamed-chunked2", headers);
  4434. ASSERT_TRUE(res);
  4435. EXPECT_EQ(StatusCode::OK_200, res->status);
  4436. EXPECT_EQ(std::string("123456789"), res->body);
  4437. }
  4438. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4439. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4440. ASSERT_TRUE(res);
  4441. EXPECT_EQ(StatusCode::OK_200, res->status);
  4442. }
  4443. TEST(GzipDecompressor, ChunkedDecompression) {
  4444. std::string data;
  4445. for (size_t i = 0; i < 32 * 1024; ++i) {
  4446. data.push_back(static_cast<char>('a' + i % 26));
  4447. }
  4448. std::string compressed_data;
  4449. {
  4450. httplib::detail::gzip_compressor compressor;
  4451. bool result = compressor.compress(
  4452. data.data(), data.size(),
  4453. /*last=*/true,
  4454. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4455. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4456. compressed_data_size);
  4457. return true;
  4458. });
  4459. ASSERT_TRUE(result);
  4460. }
  4461. std::string decompressed_data;
  4462. {
  4463. httplib::detail::gzip_decompressor decompressor;
  4464. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4465. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4466. size_t chunk_size = 130;
  4467. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4468. chunk_begin += chunk_size) {
  4469. size_t current_chunk_size =
  4470. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4471. bool result = decompressor.decompress(
  4472. compressed_data.data() + chunk_begin, current_chunk_size,
  4473. [&](const char *decompressed_data_chunk,
  4474. size_t decompressed_data_chunk_size) {
  4475. decompressed_data.insert(decompressed_data.size(),
  4476. decompressed_data_chunk,
  4477. decompressed_data_chunk_size);
  4478. return true;
  4479. });
  4480. ASSERT_TRUE(result);
  4481. }
  4482. }
  4483. ASSERT_EQ(data, decompressed_data);
  4484. }
  4485. TEST(GzipDecompressor, DeflateDecompression) {
  4486. std::string original_text = "Raw deflate without gzip";
  4487. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4488. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4489. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4490. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4491. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4492. std::string decompressed_data;
  4493. {
  4494. httplib::detail::gzip_decompressor decompressor;
  4495. bool result = decompressor.decompress(
  4496. compressed_data.data(), compressed_data.size(),
  4497. [&](const char *decompressed_data_chunk,
  4498. size_t decompressed_data_chunk_size) {
  4499. decompressed_data.insert(decompressed_data.size(),
  4500. decompressed_data_chunk,
  4501. decompressed_data_chunk_size);
  4502. return true;
  4503. });
  4504. ASSERT_TRUE(result);
  4505. }
  4506. ASSERT_EQ(original_text, decompressed_data);
  4507. }
  4508. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4509. std::string original_text = "Raw deflate without gzip";
  4510. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4511. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4512. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4513. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4514. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4515. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4516. std::string decompressed_data;
  4517. {
  4518. httplib::detail::gzip_decompressor decompressor;
  4519. bool result = decompressor.decompress(
  4520. compressed_data.data(), compressed_data.size(),
  4521. [&](const char *decompressed_data_chunk,
  4522. size_t decompressed_data_chunk_size) {
  4523. decompressed_data.insert(decompressed_data.size(),
  4524. decompressed_data_chunk,
  4525. decompressed_data_chunk_size);
  4526. return true;
  4527. });
  4528. ASSERT_TRUE(result);
  4529. }
  4530. ASSERT_EQ(original_text, decompressed_data);
  4531. }
  4532. #ifdef _WIN32
  4533. TEST(GzipDecompressor, LargeRandomData) {
  4534. // prepare large random data that is difficult to be compressed and is
  4535. // expected to have large size even when compressed
  4536. std::random_device seed_gen;
  4537. std::mt19937 random(seed_gen());
  4538. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4539. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4540. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4541. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4542. // compress data over 4GiB
  4543. std::string compressed_data;
  4544. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4545. httplib::detail::gzip_compressor compressor;
  4546. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4547. data.size() * sizeof(std::uint32_t), true,
  4548. [&](const char *data, size_t size) {
  4549. compressed_data.insert(
  4550. compressed_data.size(), data, size);
  4551. return true;
  4552. });
  4553. ASSERT_TRUE(result);
  4554. // FIXME: compressed data size is expected to be greater than 4GiB,
  4555. // but there is no guarantee
  4556. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4557. // decompress data over 4GiB
  4558. std::string decompressed_data;
  4559. decompressed_data.reserve(data_size);
  4560. httplib::detail::gzip_decompressor decompressor;
  4561. result = decompressor.decompress(
  4562. compressed_data.data(), compressed_data.size(),
  4563. [&](const char *data, size_t size) {
  4564. decompressed_data.insert(decompressed_data.size(), data, size);
  4565. return true;
  4566. });
  4567. ASSERT_TRUE(result);
  4568. // compare
  4569. ASSERT_EQ(data_size, decompressed_data.size());
  4570. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4571. 0);
  4572. }
  4573. #endif
  4574. #endif
  4575. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4576. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4577. Headers headers;
  4578. headers.emplace("Accept-Encoding", "br");
  4579. auto res = cli_.Get("/streamed-chunked", headers);
  4580. ASSERT_TRUE(res);
  4581. EXPECT_EQ(StatusCode::OK_200, res->status);
  4582. EXPECT_EQ(std::string("123456789"), res->body);
  4583. }
  4584. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4585. Headers headers;
  4586. headers.emplace("Accept-Encoding", "br");
  4587. auto res = cli_.Get("/streamed-chunked2", headers);
  4588. ASSERT_TRUE(res);
  4589. EXPECT_EQ(StatusCode::OK_200, res->status);
  4590. EXPECT_EQ(std::string("123456789"), res->body);
  4591. }
  4592. #endif
  4593. TEST_F(ServerTest, Patch) {
  4594. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4595. ASSERT_TRUE(res);
  4596. EXPECT_EQ(StatusCode::OK_200, res->status);
  4597. EXPECT_EQ("PATCH", res->body);
  4598. }
  4599. TEST_F(ServerTest, Delete) {
  4600. auto res = cli_.Delete("/delete");
  4601. ASSERT_TRUE(res);
  4602. EXPECT_EQ(StatusCode::OK_200, res->status);
  4603. EXPECT_EQ("DELETE", res->body);
  4604. }
  4605. TEST_F(ServerTest, DeleteContentReceiver) {
  4606. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4607. ASSERT_TRUE(res);
  4608. EXPECT_EQ(StatusCode::OK_200, res->status);
  4609. EXPECT_EQ("content", res->body);
  4610. }
  4611. TEST_F(ServerTest, Options) {
  4612. auto res = cli_.Options("*");
  4613. ASSERT_TRUE(res);
  4614. EXPECT_EQ(StatusCode::OK_200, res->status);
  4615. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4616. EXPECT_TRUE(res->body.empty());
  4617. }
  4618. TEST_F(ServerTest, URL) {
  4619. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4620. ASSERT_TRUE(res);
  4621. EXPECT_EQ(StatusCode::OK_200, res->status);
  4622. }
  4623. TEST_F(ServerTest, ArrayParam) {
  4624. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4625. ASSERT_TRUE(res);
  4626. EXPECT_EQ(StatusCode::OK_200, res->status);
  4627. }
  4628. TEST_F(ServerTest, NoMultipleHeaders) {
  4629. Headers headers = {{"Content-Length", "5"}};
  4630. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4631. "text/plain");
  4632. ASSERT_TRUE(res);
  4633. EXPECT_EQ(StatusCode::OK_200, res->status);
  4634. }
  4635. TEST_F(ServerTest, PostContentReceiver) {
  4636. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4637. ASSERT_TRUE(res);
  4638. ASSERT_EQ(StatusCode::OK_200, res->status);
  4639. ASSERT_EQ("content", res->body);
  4640. }
  4641. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4642. UploadFormDataItems items = {
  4643. {"text1", "text default", "", ""},
  4644. {"text2", "aωb", "", ""},
  4645. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4646. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4647. {"file3", "", "", "application/octet-stream"},
  4648. };
  4649. auto res = cli_.Post("/content_receiver", items);
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(StatusCode::OK_200, res->status);
  4652. }
  4653. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4654. UploadFormDataItems items = {
  4655. {"text1", "text default", "", ""},
  4656. {"text2", "aωb", "", ""},
  4657. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4658. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4659. {"file3", "", "", "application/octet-stream"},
  4660. };
  4661. auto boundary = std::string("+++++");
  4662. std::string body;
  4663. for (const auto &item : items) {
  4664. body += "--" + boundary + "\r\n";
  4665. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4666. if (!item.filename.empty()) {
  4667. body += "; filename=\"" + item.filename + "\"";
  4668. }
  4669. body += "\r\n";
  4670. if (!item.content_type.empty()) {
  4671. body += "Content-Type: " + item.content_type + "\r\n";
  4672. }
  4673. body += "\r\n";
  4674. body += item.content + "\r\n";
  4675. }
  4676. body += "--" + boundary + "--\r\n";
  4677. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4678. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4679. ASSERT_TRUE(res);
  4680. EXPECT_EQ(StatusCode::OK_200, res->status);
  4681. }
  4682. TEST_F(ServerTest, PostContentReceiverGzip) {
  4683. cli_.set_compress(true);
  4684. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4685. ASSERT_TRUE(res);
  4686. ASSERT_EQ(StatusCode::OK_200, res->status);
  4687. ASSERT_EQ("content", res->body);
  4688. }
  4689. TEST_F(ServerTest, PutContentReceiver) {
  4690. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4691. ASSERT_TRUE(res);
  4692. ASSERT_EQ(StatusCode::OK_200, res->status);
  4693. ASSERT_EQ("content", res->body);
  4694. }
  4695. TEST_F(ServerTest, PatchContentReceiver) {
  4696. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4697. ASSERT_TRUE(res);
  4698. ASSERT_EQ(StatusCode::OK_200, res->status);
  4699. ASSERT_EQ("content", res->body);
  4700. }
  4701. template <typename ClientType>
  4702. void TestWithHeadersAndContentReceiver(
  4703. ClientType &cli,
  4704. std::function<Result(ClientType &, const std::string &, const Headers &,
  4705. const std::string &, const std::string &,
  4706. ContentReceiver, DownloadProgress)>
  4707. request_func) {
  4708. Headers headers;
  4709. headers.emplace("X-Custom-Header", "test-value");
  4710. std::string received_body;
  4711. auto res = request_func(
  4712. cli, "/content_receiver", headers, "content", "application/json",
  4713. [&](const char *data, size_t data_length) {
  4714. received_body.append(data, data_length);
  4715. return true;
  4716. },
  4717. nullptr);
  4718. ASSERT_TRUE(res);
  4719. EXPECT_EQ(StatusCode::OK_200, res->status);
  4720. EXPECT_EQ("content", received_body);
  4721. }
  4722. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4723. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4724. using ClientT = SSLClient;
  4725. #else
  4726. using ClientT = Client;
  4727. #endif
  4728. TestWithHeadersAndContentReceiver<ClientT>(
  4729. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4730. const std::string &body, const std::string &content_type,
  4731. ContentReceiver receiver, DownloadProgress progress) {
  4732. return cli.Post(path, headers, body, content_type, receiver, progress);
  4733. });
  4734. }
  4735. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4736. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4737. using ClientT = SSLClient;
  4738. #else
  4739. using ClientT = Client;
  4740. #endif
  4741. TestWithHeadersAndContentReceiver<ClientT>(
  4742. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4743. const std::string &body, const std::string &content_type,
  4744. ContentReceiver receiver, DownloadProgress progress) {
  4745. return cli.Put(path, headers, body, content_type, receiver, progress);
  4746. });
  4747. }
  4748. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4749. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4750. using ClientT = SSLClient;
  4751. #else
  4752. using ClientT = Client;
  4753. #endif
  4754. TestWithHeadersAndContentReceiver<ClientT>(
  4755. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4756. const std::string &body, const std::string &content_type,
  4757. ContentReceiver receiver, DownloadProgress progress) {
  4758. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4759. });
  4760. }
  4761. template <typename ClientType>
  4762. void TestWithHeadersAndContentReceiverWithProgress(
  4763. ClientType &cli,
  4764. std::function<Result(ClientType &, const std::string &, const Headers &,
  4765. const std::string &, const std::string &,
  4766. ContentReceiver, DownloadProgress)>
  4767. request_func) {
  4768. Headers headers;
  4769. headers.emplace("X-Test-Header", "progress-test");
  4770. std::string received_body;
  4771. auto progress_called = false;
  4772. auto res = request_func(
  4773. cli, "/content_receiver", headers, "content", "text/plain",
  4774. [&](const char *data, size_t data_length) {
  4775. received_body.append(data, data_length);
  4776. return true;
  4777. },
  4778. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4779. progress_called = true;
  4780. return true;
  4781. });
  4782. ASSERT_TRUE(res);
  4783. EXPECT_EQ(StatusCode::OK_200, res->status);
  4784. EXPECT_EQ("content", received_body);
  4785. EXPECT_TRUE(progress_called);
  4786. }
  4787. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4788. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4789. using ClientT = SSLClient;
  4790. #else
  4791. using ClientT = Client;
  4792. #endif
  4793. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4794. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4795. const std::string &body, const std::string &content_type,
  4796. ContentReceiver receiver, DownloadProgress progress) {
  4797. return cli.Post(path, headers, body, content_type, receiver, progress);
  4798. });
  4799. }
  4800. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4801. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4802. using ClientT = SSLClient;
  4803. #else
  4804. using ClientT = Client;
  4805. #endif
  4806. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4807. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4808. const std::string &body, const std::string &content_type,
  4809. ContentReceiver receiver, DownloadProgress progress) {
  4810. return cli.Put(path, headers, body, content_type, receiver, progress);
  4811. });
  4812. }
  4813. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4814. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4815. using ClientT = SSLClient;
  4816. #else
  4817. using ClientT = Client;
  4818. #endif
  4819. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4820. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4821. const std::string &body, const std::string &content_type,
  4822. ContentReceiver receiver, DownloadProgress progress) {
  4823. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4824. });
  4825. }
  4826. template <typename ClientType>
  4827. void TestWithHeadersAndContentReceiverError(
  4828. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4829. const Headers &, const std::string &,
  4830. const std::string &, ContentReceiver)>
  4831. request_func) {
  4832. Headers headers;
  4833. headers.emplace("X-Error-Test", "true");
  4834. std::string received_body;
  4835. auto receiver_failed = false;
  4836. auto res =
  4837. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4838. [&](const char *data, size_t data_length) {
  4839. received_body.append(data, data_length);
  4840. receiver_failed = true;
  4841. return false;
  4842. });
  4843. ASSERT_FALSE(res);
  4844. EXPECT_TRUE(receiver_failed);
  4845. }
  4846. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4847. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4848. using ClientT = SSLClient;
  4849. #else
  4850. using ClientT = Client;
  4851. #endif
  4852. TestWithHeadersAndContentReceiverError<ClientT>(
  4853. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4854. const std::string &body, const std::string &content_type,
  4855. ContentReceiver receiver) {
  4856. return cli.Post(path, headers, body, content_type, receiver);
  4857. });
  4858. }
  4859. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4860. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4861. using ClientT = SSLClient;
  4862. #else
  4863. using ClientT = Client;
  4864. #endif
  4865. TestWithHeadersAndContentReceiverError<ClientT>(
  4866. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4867. const std::string &body, const std::string &content_type,
  4868. ContentReceiver receiver) {
  4869. return cli.Put(path, headers, body, content_type, receiver);
  4870. });
  4871. }
  4872. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4873. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4874. using ClientT = SSLClient;
  4875. #else
  4876. using ClientT = Client;
  4877. #endif
  4878. TestWithHeadersAndContentReceiverError<ClientT>(
  4879. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4880. const std::string &body, const std::string &content_type,
  4881. ContentReceiver receiver) {
  4882. return cli.Patch(path, headers, body, content_type, receiver);
  4883. });
  4884. }
  4885. TEST_F(ServerTest, PostQueryStringAndBody) {
  4886. auto res =
  4887. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4888. ASSERT_TRUE(res);
  4889. ASSERT_EQ(StatusCode::OK_200, res->status);
  4890. }
  4891. TEST_F(ServerTest, HTTP2Magic) {
  4892. Request req;
  4893. req.method = "PRI";
  4894. req.path = "*";
  4895. req.body = "SM";
  4896. auto res = std::make_shared<Response>();
  4897. auto error = Error::Success;
  4898. auto ret = cli_.send(req, *res, error);
  4899. ASSERT_TRUE(ret);
  4900. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4901. }
  4902. TEST_F(ServerTest, KeepAlive) {
  4903. auto res = cli_.Get("/hi");
  4904. ASSERT_TRUE(res);
  4905. EXPECT_EQ(StatusCode::OK_200, res->status);
  4906. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4907. EXPECT_EQ("Hello World!", res->body);
  4908. res = cli_.Get("/hi");
  4909. ASSERT_TRUE(res);
  4910. EXPECT_EQ(StatusCode::OK_200, res->status);
  4911. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4912. EXPECT_EQ("Hello World!", res->body);
  4913. res = cli_.Get("/hi");
  4914. ASSERT_TRUE(res);
  4915. EXPECT_EQ(StatusCode::OK_200, res->status);
  4916. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4917. EXPECT_EQ("Hello World!", res->body);
  4918. res = cli_.Get("/not-exist");
  4919. ASSERT_TRUE(res);
  4920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4921. res = cli_.Post("/empty", "", "text/plain");
  4922. ASSERT_TRUE(res);
  4923. EXPECT_EQ(StatusCode::OK_200, res->status);
  4924. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4925. EXPECT_EQ("empty", res->body);
  4926. EXPECT_EQ("close", res->get_header_value("Connection"));
  4927. res = cli_.Post(
  4928. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4929. "text/plain");
  4930. ASSERT_TRUE(res);
  4931. EXPECT_EQ(StatusCode::OK_200, res->status);
  4932. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4933. EXPECT_EQ("empty", res->body);
  4934. cli_.set_keep_alive(false);
  4935. res = cli_.Get("/last-request");
  4936. ASSERT_TRUE(res);
  4937. EXPECT_EQ(StatusCode::OK_200, res->status);
  4938. EXPECT_EQ("close", res->get_header_value("Connection"));
  4939. }
  4940. TEST_F(ServerTest, TooManyRedirect) {
  4941. cli_.set_follow_location(true);
  4942. auto res = cli_.Get("/redirect/0");
  4943. ASSERT_TRUE(!res);
  4944. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4945. }
  4946. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  4947. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4948. TEST_F(ServerTest, Gzip) {
  4949. Headers headers;
  4950. headers.emplace("Accept-Encoding", "gzip, deflate");
  4951. auto res = cli_.Get("/compress", headers);
  4952. ASSERT_TRUE(res);
  4953. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4954. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4955. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4956. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4957. "7890123456789012345678901234567890",
  4958. res->body);
  4959. EXPECT_EQ(StatusCode::OK_200, res->status);
  4960. }
  4961. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4962. Headers headers;
  4963. headers.emplace("Accept-Encoding", "");
  4964. auto res = cli_.Get("/compress", headers);
  4965. ASSERT_TRUE(res);
  4966. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4967. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4968. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4969. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4970. "7890123456789012345678901234567890",
  4971. res->body);
  4972. EXPECT_EQ(StatusCode::OK_200, res->status);
  4973. }
  4974. TEST_F(ServerTest, GzipWithContentReceiver) {
  4975. Headers headers;
  4976. headers.emplace("Accept-Encoding", "gzip, deflate");
  4977. std::string body;
  4978. auto res = cli_.Get("/compress", headers,
  4979. [&](const char *data, uint64_t data_length) {
  4980. EXPECT_EQ(100U, data_length);
  4981. body.append(data, data_length);
  4982. return true;
  4983. });
  4984. ASSERT_TRUE(res);
  4985. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4986. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4987. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4988. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4989. "7890123456789012345678901234567890",
  4990. body);
  4991. EXPECT_EQ(StatusCode::OK_200, res->status);
  4992. }
  4993. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4994. Headers headers;
  4995. headers.emplace("Accept-Encoding", "gzip, deflate");
  4996. cli_.set_decompress(false);
  4997. auto res = cli_.Get("/compress", headers);
  4998. ASSERT_TRUE(res);
  4999. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5000. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5001. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5002. EXPECT_EQ(33U, res->body.size());
  5003. EXPECT_EQ(StatusCode::OK_200, res->status);
  5004. }
  5005. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5006. Headers headers;
  5007. headers.emplace("Accept-Encoding", "");
  5008. std::string body;
  5009. auto res = cli_.Get("/compress", headers,
  5010. [&](const char *data, uint64_t data_length) {
  5011. EXPECT_EQ(100U, data_length);
  5012. body.append(data, data_length);
  5013. return true;
  5014. });
  5015. ASSERT_TRUE(res);
  5016. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5017. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5018. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5019. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5020. "7890123456789012345678901234567890",
  5021. body);
  5022. EXPECT_EQ(StatusCode::OK_200, res->status);
  5023. }
  5024. TEST_F(ServerTest, NoGzip) {
  5025. Headers headers;
  5026. headers.emplace("Accept-Encoding", "gzip, deflate");
  5027. auto res = cli_.Get("/nocompress", headers);
  5028. ASSERT_TRUE(res);
  5029. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5030. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5031. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5032. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5033. "7890123456789012345678901234567890",
  5034. res->body);
  5035. EXPECT_EQ(StatusCode::OK_200, res->status);
  5036. }
  5037. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5038. Headers headers;
  5039. headers.emplace("Accept-Encoding", "gzip, deflate");
  5040. std::string body;
  5041. auto res = cli_.Get("/nocompress", headers,
  5042. [&](const char *data, uint64_t data_length) {
  5043. EXPECT_EQ(100U, data_length);
  5044. body.append(data, data_length);
  5045. return true;
  5046. });
  5047. ASSERT_TRUE(res);
  5048. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5049. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5050. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5051. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5052. "7890123456789012345678901234567890",
  5053. body);
  5054. EXPECT_EQ(StatusCode::OK_200, res->status);
  5055. }
  5056. TEST_F(ServerTest, MultipartFormDataGzip) {
  5057. UploadFormDataItems items = {
  5058. {"key1", "test", "", ""},
  5059. {"key2", "--abcdefg123", "", ""},
  5060. };
  5061. cli_.set_compress(true);
  5062. auto res = cli_.Post("/compress-multipart", items);
  5063. ASSERT_TRUE(res);
  5064. EXPECT_EQ(StatusCode::OK_200, res->status);
  5065. }
  5066. #endif
  5067. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5068. TEST_F(ServerTest, Brotli) {
  5069. Headers headers;
  5070. headers.emplace("Accept-Encoding", "br");
  5071. auto res = cli_.Get("/compress", headers);
  5072. ASSERT_TRUE(res);
  5073. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5074. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5075. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5076. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5077. "7890123456789012345678901234567890",
  5078. res->body);
  5079. EXPECT_EQ(StatusCode::OK_200, res->status);
  5080. }
  5081. #endif
  5082. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5083. TEST_F(ServerTest, Zstd) {
  5084. Headers headers;
  5085. headers.emplace("Accept-Encoding", "zstd");
  5086. auto res = cli_.Get("/compress", headers);
  5087. ASSERT_TRUE(res);
  5088. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5089. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5090. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5091. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5092. "7890123456789012345678901234567890",
  5093. res->body);
  5094. EXPECT_EQ(StatusCode::OK_200, res->status);
  5095. }
  5096. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5097. Headers headers;
  5098. headers.emplace("Accept-Encoding", "");
  5099. auto res = cli_.Get("/compress", headers);
  5100. ASSERT_TRUE(res);
  5101. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5102. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5103. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5104. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5105. "7890123456789012345678901234567890",
  5106. res->body);
  5107. EXPECT_EQ(StatusCode::OK_200, res->status);
  5108. }
  5109. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5110. Headers headers;
  5111. headers.emplace("Accept-Encoding", "zstd");
  5112. std::string body;
  5113. auto res = cli_.Get("/compress", headers,
  5114. [&](const char *data, uint64_t data_length) {
  5115. EXPECT_EQ(100U, data_length);
  5116. body.append(data, data_length);
  5117. return true;
  5118. });
  5119. ASSERT_TRUE(res);
  5120. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5121. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5122. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5123. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5124. "7890123456789012345678901234567890",
  5125. body);
  5126. EXPECT_EQ(StatusCode::OK_200, res->status);
  5127. }
  5128. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5129. Headers headers;
  5130. headers.emplace("Accept-Encoding", "zstd");
  5131. cli_.set_decompress(false);
  5132. auto res = cli_.Get("/compress", headers);
  5133. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5134. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5135. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5136. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5137. ASSERT_TRUE(res);
  5138. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5139. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5140. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5141. EXPECT_EQ(StatusCode::OK_200, res->status);
  5142. ASSERT_EQ(26U, res->body.size());
  5143. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5144. 0);
  5145. }
  5146. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5147. Headers headers;
  5148. headers.emplace("Accept-Encoding", "");
  5149. std::string body;
  5150. auto res = cli_.Get("/compress", headers,
  5151. [&](const char *data, uint64_t data_length) {
  5152. EXPECT_EQ(100U, data_length);
  5153. body.append(data, data_length);
  5154. return true;
  5155. });
  5156. ASSERT_TRUE(res);
  5157. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5158. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5159. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5160. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5161. "7890123456789012345678901234567890",
  5162. body);
  5163. EXPECT_EQ(StatusCode::OK_200, res->status);
  5164. }
  5165. TEST_F(ServerTest, NoZstd) {
  5166. Headers headers;
  5167. headers.emplace("Accept-Encoding", "zstd");
  5168. auto res = cli_.Get("/nocompress", headers);
  5169. ASSERT_TRUE(res);
  5170. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5171. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5172. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5173. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5174. "7890123456789012345678901234567890",
  5175. res->body);
  5176. EXPECT_EQ(StatusCode::OK_200, res->status);
  5177. }
  5178. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5179. Headers headers;
  5180. headers.emplace("Accept-Encoding", "zstd");
  5181. std::string body;
  5182. auto res = cli_.Get("/nocompress", headers,
  5183. [&](const char *data, uint64_t data_length) {
  5184. EXPECT_EQ(100U, data_length);
  5185. body.append(data, data_length);
  5186. return true;
  5187. });
  5188. ASSERT_TRUE(res);
  5189. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5190. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5191. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5192. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5193. "7890123456789012345678901234567890",
  5194. body);
  5195. EXPECT_EQ(StatusCode::OK_200, res->status);
  5196. }
  5197. // TODO: How to enable zstd ??
  5198. TEST_F(ServerTest, MultipartFormDataZstd) {
  5199. UploadFormDataItems items = {
  5200. {"key1", "test", "", ""},
  5201. {"key2", "--abcdefg123", "", ""},
  5202. };
  5203. Headers headers;
  5204. headers.emplace("Accept-Encoding", "zstd");
  5205. cli_.set_compress(true);
  5206. auto res = cli_.Post("/compress-multipart", headers, items);
  5207. ASSERT_TRUE(res);
  5208. EXPECT_EQ(StatusCode::OK_200, res->status);
  5209. }
  5210. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5211. Headers headers;
  5212. headers.emplace("Accept-Encoding", "zstd");
  5213. cli_.set_compress(true);
  5214. auto res = cli_.Put(
  5215. "/put", headers, 3,
  5216. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5217. sink.os << "PUT";
  5218. return true;
  5219. },
  5220. "text/plain");
  5221. ASSERT_TRUE(res);
  5222. EXPECT_EQ(StatusCode::OK_200, res->status);
  5223. EXPECT_EQ("PUT", res->body);
  5224. }
  5225. // Pre-compression logging tests
  5226. TEST_F(ServerTest, PreCompressionLogging) {
  5227. // Test data for compression (matches the actual /compress endpoint content)
  5228. const std::string test_content =
  5229. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5230. "3456789012345678901234567890";
  5231. // Variables to capture logging data
  5232. std::string pre_compression_body;
  5233. std::string pre_compression_content_type;
  5234. std::string pre_compression_content_encoding;
  5235. std::string post_compression_body;
  5236. std::string post_compression_content_type;
  5237. std::string post_compression_content_encoding;
  5238. // Set up pre-compression logger
  5239. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5240. const Response &res) {
  5241. pre_compression_body = res.body;
  5242. pre_compression_content_type = res.get_header_value("Content-Type");
  5243. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5244. });
  5245. // Set up post-compression logger
  5246. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5247. post_compression_body = res.body;
  5248. post_compression_content_type = res.get_header_value("Content-Type");
  5249. post_compression_content_encoding =
  5250. res.get_header_value("Content-Encoding");
  5251. });
  5252. // Test with gzip compression
  5253. Headers headers;
  5254. headers.emplace("Accept-Encoding", "gzip");
  5255. auto res = cli_.Get("/compress", headers);
  5256. // Verify response was compressed
  5257. ASSERT_TRUE(res);
  5258. EXPECT_EQ(StatusCode::OK_200, res->status);
  5259. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5260. // Verify pre-compression logger captured uncompressed content
  5261. EXPECT_EQ(test_content, pre_compression_body);
  5262. EXPECT_EQ("text/plain", pre_compression_content_type);
  5263. EXPECT_TRUE(pre_compression_content_encoding
  5264. .empty()); // No encoding header before compression
  5265. // Verify post-compression logger captured compressed content
  5266. EXPECT_NE(test_content,
  5267. post_compression_body); // Should be different after compression
  5268. EXPECT_EQ("text/plain", post_compression_content_type);
  5269. EXPECT_EQ("gzip", post_compression_content_encoding);
  5270. // Verify compressed content is smaller
  5271. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5272. }
  5273. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5274. const std::string test_content =
  5275. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5276. "3456789012345678901234567890";
  5277. std::string pre_compression_body;
  5278. std::string post_compression_body;
  5279. svr_.set_pre_compression_logger(
  5280. [&](const Request & /*req*/, const Response &res) {
  5281. pre_compression_body = res.body;
  5282. });
  5283. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5284. post_compression_body = res.body;
  5285. });
  5286. Headers headers;
  5287. headers.emplace("Accept-Encoding", "br");
  5288. auto res = cli_.Get("/compress", headers);
  5289. ASSERT_TRUE(res);
  5290. EXPECT_EQ(StatusCode::OK_200, res->status);
  5291. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5292. // Verify pre-compression content is uncompressed
  5293. EXPECT_EQ(test_content, pre_compression_body);
  5294. // Verify post-compression content is compressed
  5295. EXPECT_NE(test_content, post_compression_body);
  5296. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5297. }
  5298. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5299. const std::string test_content =
  5300. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5301. "3456789012345678901234567890";
  5302. std::string pre_compression_body;
  5303. std::string post_compression_body;
  5304. svr_.set_pre_compression_logger(
  5305. [&](const Request & /*req*/, const Response &res) {
  5306. pre_compression_body = res.body;
  5307. });
  5308. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5309. post_compression_body = res.body;
  5310. });
  5311. // Request without compression (use /nocompress endpoint)
  5312. Headers headers;
  5313. auto res = cli_.Get("/nocompress", headers);
  5314. ASSERT_TRUE(res);
  5315. EXPECT_EQ(StatusCode::OK_200, res->status);
  5316. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5317. // Pre-compression logger should not be called when no compression is applied
  5318. EXPECT_TRUE(
  5319. pre_compression_body.empty()); // Pre-compression logger not called
  5320. EXPECT_EQ(
  5321. test_content,
  5322. post_compression_body); // Post-compression logger captures final content
  5323. }
  5324. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5325. const std::string test_content =
  5326. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5327. "3456789012345678901234567890";
  5328. std::string pre_compression_body;
  5329. bool pre_logger_called = false;
  5330. // Set only pre-compression logger
  5331. svr_.set_pre_compression_logger(
  5332. [&](const Request & /*req*/, const Response &res) {
  5333. pre_compression_body = res.body;
  5334. pre_logger_called = true;
  5335. });
  5336. Headers headers;
  5337. headers.emplace("Accept-Encoding", "gzip");
  5338. auto res = cli_.Get("/compress", headers);
  5339. ASSERT_TRUE(res);
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5342. // Verify pre-compression logger was called
  5343. EXPECT_TRUE(pre_logger_called);
  5344. EXPECT_EQ(test_content, pre_compression_body);
  5345. }
  5346. TEST(ZstdDecompressor, ChunkedDecompression) {
  5347. std::string data;
  5348. for (size_t i = 0; i < 32 * 1024; ++i) {
  5349. data.push_back(static_cast<char>('a' + i % 26));
  5350. }
  5351. std::string compressed_data;
  5352. {
  5353. httplib::detail::zstd_compressor compressor;
  5354. bool result = compressor.compress(
  5355. data.data(), data.size(),
  5356. /*last=*/true,
  5357. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5358. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5359. compressed_data_size);
  5360. return true;
  5361. });
  5362. ASSERT_TRUE(result);
  5363. }
  5364. std::string decompressed_data;
  5365. {
  5366. httplib::detail::zstd_decompressor decompressor;
  5367. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5368. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5369. size_t chunk_size = 130;
  5370. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5371. chunk_begin += chunk_size) {
  5372. size_t current_chunk_size =
  5373. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5374. bool result = decompressor.decompress(
  5375. compressed_data.data() + chunk_begin, current_chunk_size,
  5376. [&](const char *decompressed_data_chunk,
  5377. size_t decompressed_data_chunk_size) {
  5378. decompressed_data.insert(decompressed_data.size(),
  5379. decompressed_data_chunk,
  5380. decompressed_data_chunk_size);
  5381. return true;
  5382. });
  5383. ASSERT_TRUE(result);
  5384. }
  5385. }
  5386. ASSERT_EQ(data, decompressed_data);
  5387. }
  5388. TEST(ZstdDecompressor, Decompress) {
  5389. std::string original_text = "Compressed with ZSTD";
  5390. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5391. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5392. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5393. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5394. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5395. std::string decompressed_data;
  5396. {
  5397. httplib::detail::zstd_decompressor decompressor;
  5398. bool result = decompressor.decompress(
  5399. compressed_data.data(), compressed_data.size(),
  5400. [&](const char *decompressed_data_chunk,
  5401. size_t decompressed_data_chunk_size) {
  5402. decompressed_data.insert(decompressed_data.size(),
  5403. decompressed_data_chunk,
  5404. decompressed_data_chunk_size);
  5405. return true;
  5406. });
  5407. ASSERT_TRUE(result);
  5408. }
  5409. ASSERT_EQ(original_text, decompressed_data);
  5410. }
  5411. #endif
  5412. // Sends a raw request to a server listening at HOST:PORT.
  5413. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5414. std::string *resp = nullptr) {
  5415. auto error = Error::Success;
  5416. auto client_sock = detail::create_client_socket(
  5417. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5418. /*connection_timeout_sec=*/5, 0,
  5419. /*read_timeout_sec=*/5, 0,
  5420. /*write_timeout_sec=*/5, 0, std::string(), error);
  5421. if (client_sock == INVALID_SOCKET) { return false; }
  5422. auto ret = detail::process_client_socket(
  5423. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5424. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5425. if (req.size() !=
  5426. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5427. return false;
  5428. }
  5429. char buf[512];
  5430. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5431. while (line_reader.getline()) {
  5432. if (resp) { *resp += line_reader.ptr(); }
  5433. }
  5434. return true;
  5435. });
  5436. detail::close_socket(client_sock);
  5437. return ret;
  5438. }
  5439. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5440. Server svr;
  5441. std::string header_value;
  5442. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5443. header_value = req.get_header_value("foo");
  5444. res.set_content("ok", "text/plain");
  5445. });
  5446. thread t = thread([&] { svr.listen(HOST, PORT); });
  5447. auto se = detail::scope_exit([&] {
  5448. svr.stop();
  5449. t.join();
  5450. ASSERT_FALSE(svr.is_running());
  5451. });
  5452. svr.wait_until_ready();
  5453. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5454. // like characters are not treated the same - use vertical tab and escape.
  5455. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5456. "foo: \t \v bar \x1B\t \r\n"
  5457. "Connection: close\r\n"
  5458. "\r\n";
  5459. std::string res;
  5460. ASSERT_TRUE(send_request(5, req, &res));
  5461. EXPECT_EQ(header_value, "");
  5462. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5463. }
  5464. // Sends a raw request and verifies that there isn't a crash or exception.
  5465. static void test_raw_request(const std::string &req,
  5466. std::string *out = nullptr) {
  5467. Server svr;
  5468. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5469. res.set_content("ok", "text/plain");
  5470. });
  5471. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5472. res.set_content("ok", "text/plain");
  5473. });
  5474. svr.Get("/header_field_value_check",
  5475. [&](const Request & /*req*/, Response &res) {
  5476. res.set_content("ok", "text/plain");
  5477. });
  5478. // Server read timeout must be longer than the client read timeout for the
  5479. // bug to reproduce, probably to force the server to process a request
  5480. // without a trailing blank line.
  5481. const time_t client_read_timeout_sec = 1;
  5482. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5483. bool listen_thread_ok = false;
  5484. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5485. auto se = detail::scope_exit([&] {
  5486. svr.stop();
  5487. t.join();
  5488. ASSERT_FALSE(svr.is_running());
  5489. EXPECT_TRUE(listen_thread_ok);
  5490. });
  5491. svr.wait_until_ready();
  5492. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5493. }
  5494. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5495. // A certain header line causes an exception if the header property is parsed
  5496. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5497. test_raw_request(
  5498. "GET /hi HTTP/1.1\r\n"
  5499. " : "
  5500. " "
  5501. " ");
  5502. }
  5503. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5504. // A certain header line causes an exception if the header property *name* is
  5505. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5506. // greedy matcher and requires backtracking when there are a lot of ":"
  5507. // characters.
  5508. // This occurs with libc++ but not libstdc++.
  5509. test_raw_request(
  5510. "GET /hi HTTP/1.1\r\n"
  5511. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5512. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5513. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5514. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5515. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5516. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5517. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5518. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5519. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5520. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5521. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5522. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5523. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5524. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5525. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5526. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5527. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5528. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5529. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5530. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5531. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5532. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5533. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5534. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5535. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5536. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5537. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5538. "&&&%%%");
  5539. }
  5540. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5541. // Make sure this doesn't crash the server.
  5542. // In a previous version of the header line regex, the "\r" rendered the line
  5543. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5544. // a new position where the leading white space ended and the field value
  5545. // began.
  5546. // The crash occurs with libc++ but not libstdc++.
  5547. test_raw_request("GET /hi HTTP/1.1\r\n"
  5548. "a:" +
  5549. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5550. "\r\n"
  5551. "\r\n");
  5552. }
  5553. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5554. std::string out;
  5555. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5556. "Content-Type: text/plain\r\n"
  5557. "Transfer-Encoding: chunked\r\n"
  5558. "\r\n"
  5559. "nothex\r\n",
  5560. &out);
  5561. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5562. }
  5563. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5564. std::string out;
  5565. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5566. "Content-Type: text/plain\r\n"
  5567. "Transfer-Encoding: chunked\r\n"
  5568. "\r\n"
  5569. "3\r\n"
  5570. "xyz\r\n"
  5571. "NaN\r\n",
  5572. &out);
  5573. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5574. }
  5575. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5576. std::string out;
  5577. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5578. "Content-Type: text/plain\r\n"
  5579. "Transfer-Encoding: chunked\r\n"
  5580. "\r\n"
  5581. // Length is too large for 64 bits.
  5582. "1ffffffffffffffff\r\n"
  5583. "xyz\r\n",
  5584. &out);
  5585. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5586. }
  5587. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5588. test_raw_request("GET /hi HTTP/1.1\r\n"
  5589. "Content-Type: text/plain\r\n\r");
  5590. }
  5591. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5592. std::string out;
  5593. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5594. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5595. }
  5596. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5597. std::string out;
  5598. std::string request(
  5599. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5600. test_raw_request(request, &out);
  5601. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5602. }
  5603. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5604. std::string out;
  5605. std::string request(
  5606. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5607. test_raw_request(request, &out);
  5608. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5609. }
  5610. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5611. std::string out;
  5612. std::string request(
  5613. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5614. test_raw_request(request, &out);
  5615. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5616. }
  5617. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5618. std::string out;
  5619. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5620. "Test: \r\n\r\n",
  5621. &out);
  5622. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5623. }
  5624. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5625. Server svr;
  5626. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5627. res.set_header("Cache-Control", "no-cache");
  5628. res.set_chunked_content_provider(
  5629. "text/event-stream", [](size_t offset, DataSink &sink) {
  5630. std::string s = "data:";
  5631. s += std::to_string(offset);
  5632. s += "\n\n";
  5633. auto ret = sink.write(s.data(), s.size());
  5634. EXPECT_TRUE(ret);
  5635. std::this_thread::sleep_for(std::chrono::seconds(1));
  5636. return true;
  5637. });
  5638. });
  5639. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5640. svr.wait_until_ready();
  5641. Client client(HOST, PORT);
  5642. const Headers headers = {{"Accept", "text/event-stream"}};
  5643. auto get_thread = std::thread([&client, &headers]() {
  5644. auto res = client.Get(
  5645. "/events", headers,
  5646. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5647. });
  5648. auto se = detail::scope_exit([&] {
  5649. svr.stop();
  5650. get_thread.join();
  5651. listen_thread.join();
  5652. ASSERT_FALSE(svr.is_running());
  5653. });
  5654. // Give GET time to get a few messages.
  5655. std::this_thread::sleep_for(std::chrono::seconds(2));
  5656. }
  5657. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5658. httplib::Server svr;
  5659. svr.Post("/hi",
  5660. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5661. res.status = StatusCode::OK_200;
  5662. });
  5663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5664. svr.wait_until_ready();
  5665. Client cli(HOST, PORT);
  5666. auto res = cli.Post("/hi", "data", "text/plain");
  5667. ASSERT_TRUE(res);
  5668. EXPECT_EQ(StatusCode::OK_200, res->status);
  5669. svr.stop();
  5670. thread.join();
  5671. ASSERT_FALSE(svr.is_running());
  5672. res = cli.Post("/hi", "data", "text/plain");
  5673. ASSERT_FALSE(res);
  5674. }
  5675. TEST(ServerStopTest, ListenFailure) {
  5676. Server svr;
  5677. auto t = thread([&]() {
  5678. auto ret = svr.listen("????", PORT);
  5679. EXPECT_FALSE(ret);
  5680. });
  5681. svr.wait_until_ready();
  5682. svr.stop();
  5683. t.join();
  5684. }
  5685. TEST(ServerStopTest, Decommision) {
  5686. Server svr;
  5687. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5688. for (int i = 0; i < 4; i++) {
  5689. auto is_even = !(i % 2);
  5690. std::thread t{[&] {
  5691. try {
  5692. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5693. if (is_even) {
  5694. throw std::runtime_error("Some thing that happens to go wrong.");
  5695. }
  5696. svr.listen(HOST, PORT);
  5697. } catch (...) { svr.decommission(); }
  5698. }};
  5699. svr.wait_until_ready();
  5700. // Server is up
  5701. {
  5702. Client cli(HOST, PORT);
  5703. auto res = cli.Get("/hi");
  5704. if (is_even) {
  5705. EXPECT_FALSE(res);
  5706. } else {
  5707. EXPECT_TRUE(res);
  5708. EXPECT_EQ("hi...", res->body);
  5709. }
  5710. }
  5711. svr.stop();
  5712. t.join();
  5713. // Server is down...
  5714. {
  5715. Client cli(HOST, PORT);
  5716. auto res = cli.Get("/hi");
  5717. EXPECT_FALSE(res);
  5718. }
  5719. }
  5720. }
  5721. // Helper function for string body upload progress tests
  5722. template <typename SetupHandler, typename ClientCall>
  5723. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5724. ClientCall &&client_call,
  5725. const string &body) {
  5726. Server svr;
  5727. setup_handler(svr);
  5728. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5729. auto se = detail::scope_exit([&] {
  5730. svr.stop();
  5731. t.join();
  5732. });
  5733. svr.wait_until_ready();
  5734. Client cli(HOST, PORT);
  5735. vector<uint64_t> progress_values;
  5736. bool progress_called = false;
  5737. auto res =
  5738. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5739. progress_values.push_back(current);
  5740. progress_called = true;
  5741. return true;
  5742. });
  5743. ASSERT_TRUE(res);
  5744. EXPECT_EQ(200, res->status);
  5745. EXPECT_TRUE(progress_called);
  5746. }
  5747. TEST(UploadProgressTest, PostStringBodyBasic) {
  5748. TestStringBodyUploadProgress(
  5749. [](Server &svr) {
  5750. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5751. res.set_content("received", "text/plain");
  5752. });
  5753. },
  5754. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5755. return cli.Post("/test", body, "text/plain", progress_callback);
  5756. },
  5757. "test data for upload progress");
  5758. }
  5759. TEST(UploadProgressTest, PutStringBodyBasic) {
  5760. TestStringBodyUploadProgress(
  5761. [](Server &svr) {
  5762. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5763. res.set_content("put received", "text/plain");
  5764. });
  5765. },
  5766. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5767. return cli.Put("/test", body, "text/plain", progress_callback);
  5768. },
  5769. "put test data for upload progress");
  5770. }
  5771. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5772. TestStringBodyUploadProgress(
  5773. [](Server &svr) {
  5774. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5775. res.set_content("patch received", "text/plain");
  5776. });
  5777. },
  5778. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5779. return cli.Patch("/test", body, "text/plain", progress_callback);
  5780. },
  5781. "patch test data for upload progress");
  5782. }
  5783. // Helper function for content provider upload progress tests
  5784. template <typename SetupHandler, typename ClientCall>
  5785. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5786. ClientCall &&client_call) {
  5787. Server svr;
  5788. setup_handler(svr);
  5789. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5790. auto se = detail::scope_exit([&] {
  5791. svr.stop();
  5792. t.join();
  5793. });
  5794. svr.wait_until_ready();
  5795. Client cli(HOST, PORT);
  5796. vector<uint64_t> progress_values;
  5797. auto res =
  5798. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5799. progress_values.push_back(current);
  5800. return true;
  5801. });
  5802. ASSERT_TRUE(res);
  5803. EXPECT_EQ(200, res->status);
  5804. EXPECT_FALSE(progress_values.empty());
  5805. }
  5806. TEST(UploadProgressTest, PostContentProviderProgress) {
  5807. TestContentProviderUploadProgress(
  5808. [](Server &svr) {
  5809. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5810. res.set_content("provider received", "text/plain");
  5811. });
  5812. },
  5813. [](Client &cli, UploadProgress progress_callback) {
  5814. return cli.Post(
  5815. "/test", 10,
  5816. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5817. sink.os << "test data";
  5818. return true;
  5819. },
  5820. "text/plain", progress_callback);
  5821. });
  5822. }
  5823. // Helper function for multipart upload progress tests
  5824. template <typename SetupHandler, typename ClientCall>
  5825. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5826. ClientCall &&client_call,
  5827. const string &endpoint) {
  5828. Server svr;
  5829. setup_handler(svr);
  5830. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5831. auto se = detail::scope_exit([&] {
  5832. svr.stop();
  5833. t.join();
  5834. });
  5835. svr.wait_until_ready();
  5836. Client cli(HOST, PORT);
  5837. vector<uint64_t> progress_values;
  5838. UploadFormDataItems items = {
  5839. {"field1", "value1", "", ""},
  5840. {"field2", "longer value for progress tracking test", "", ""},
  5841. {"file1", "file content data for upload progress", "test.txt",
  5842. "text/plain"}};
  5843. auto res = client_call(cli, endpoint, items,
  5844. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5845. progress_values.push_back(current);
  5846. return true;
  5847. });
  5848. ASSERT_TRUE(res);
  5849. EXPECT_EQ(200, res->status);
  5850. EXPECT_FALSE(progress_values.empty());
  5851. }
  5852. TEST(UploadProgressTest, PostMultipartProgress) {
  5853. TestMultipartUploadProgress(
  5854. [](Server &svr) {
  5855. svr.Post("/multipart", [](const Request &req, Response &res) {
  5856. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5857. res.set_content("multipart received", "text/plain");
  5858. });
  5859. },
  5860. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5861. UploadProgress progress_callback) {
  5862. return cli.Post(endpoint, items, progress_callback);
  5863. },
  5864. "/multipart");
  5865. }
  5866. // Helper function for basic download progress tests
  5867. template <typename SetupHandler, typename ClientCall>
  5868. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5869. ClientCall &&client_call, const string &endpoint,
  5870. size_t expected_content_size) {
  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. auto res = client_call(cli, endpoint,
  5882. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5883. progress_values.push_back(current);
  5884. return true;
  5885. });
  5886. ASSERT_TRUE(res);
  5887. EXPECT_EQ(200, res->status);
  5888. EXPECT_FALSE(progress_values.empty());
  5889. EXPECT_EQ(expected_content_size, res->body.size());
  5890. }
  5891. TEST(DownloadProgressTest, GetBasic) {
  5892. TestBasicDownloadProgress(
  5893. [](Server &svr) {
  5894. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5895. string content(1000, 'D');
  5896. res.set_content(content, "text/plain");
  5897. });
  5898. },
  5899. [](Client &cli, const string &endpoint,
  5900. DownloadProgress progress_callback) {
  5901. return cli.Get(endpoint, progress_callback);
  5902. },
  5903. "/download", 1000u);
  5904. }
  5905. // Helper function for content receiver download progress tests
  5906. template <typename SetupHandler, typename ClientCall>
  5907. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5908. ClientCall &&client_call,
  5909. const string &endpoint,
  5910. size_t expected_content_size) {
  5911. Server svr;
  5912. setup_handler(svr);
  5913. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5914. auto se = detail::scope_exit([&] {
  5915. svr.stop();
  5916. t.join();
  5917. });
  5918. svr.wait_until_ready();
  5919. Client cli(HOST, PORT);
  5920. vector<uint64_t> progress_values;
  5921. string received_body;
  5922. auto res = client_call(
  5923. cli, endpoint,
  5924. [&](const char *data, size_t data_length) -> bool {
  5925. received_body.append(data, data_length);
  5926. return true;
  5927. },
  5928. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5929. progress_values.push_back(current);
  5930. return true;
  5931. });
  5932. ASSERT_TRUE(res);
  5933. EXPECT_EQ(200, res->status);
  5934. EXPECT_FALSE(progress_values.empty());
  5935. EXPECT_EQ(expected_content_size, received_body.size());
  5936. EXPECT_TRUE(res->body.empty());
  5937. }
  5938. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5939. TestContentReceiverDownloadProgress(
  5940. [](Server &svr) {
  5941. svr.Get("/download-receiver",
  5942. [](const Request & /*req*/, Response &res) {
  5943. string content(2000, 'R');
  5944. res.set_content(content, "text/plain");
  5945. });
  5946. },
  5947. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5948. DownloadProgress progress_callback) {
  5949. return cli.Get(endpoint, content_receiver, progress_callback);
  5950. },
  5951. "/download-receiver", 2000u);
  5952. }
  5953. TEST(StreamingTest, NoContentLengthStreaming) {
  5954. Server svr;
  5955. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5956. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5957. if (offset < 6) {
  5958. sink.os << (offset < 3 ? "a" : "b");
  5959. } else {
  5960. sink.done();
  5961. }
  5962. return true;
  5963. });
  5964. });
  5965. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5966. auto listen_se = detail::scope_exit([&] {
  5967. svr.stop();
  5968. listen_thread.join();
  5969. ASSERT_FALSE(svr.is_running());
  5970. });
  5971. svr.wait_until_ready();
  5972. Client client(HOST, PORT);
  5973. auto get_thread = std::thread([&client]() {
  5974. std::string s;
  5975. auto res =
  5976. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5977. s += std::string(data, len);
  5978. return true;
  5979. });
  5980. ASSERT_TRUE(res);
  5981. EXPECT_EQ(StatusCode::OK_200, res->status);
  5982. EXPECT_EQ("aaabbb", s);
  5983. });
  5984. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5985. // Give GET time to get a few messages.
  5986. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5987. }
  5988. TEST(MountTest, Unmount) {
  5989. Server svr;
  5990. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5991. auto se = detail::scope_exit([&] {
  5992. svr.stop();
  5993. listen_thread.join();
  5994. ASSERT_FALSE(svr.is_running());
  5995. });
  5996. svr.wait_until_ready();
  5997. Client cli("localhost", PORT);
  5998. svr.set_mount_point("/mount2", "./www2");
  5999. auto res = cli.Get("/");
  6000. ASSERT_TRUE(res);
  6001. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6002. res = cli.Get("/mount2/dir/test.html");
  6003. ASSERT_TRUE(res);
  6004. EXPECT_EQ(StatusCode::OK_200, res->status);
  6005. svr.set_mount_point("/", "./www");
  6006. res = cli.Get("/dir/");
  6007. ASSERT_TRUE(res);
  6008. EXPECT_EQ(StatusCode::OK_200, res->status);
  6009. svr.remove_mount_point("/");
  6010. res = cli.Get("/dir/");
  6011. ASSERT_TRUE(res);
  6012. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6013. svr.remove_mount_point("/mount2");
  6014. res = cli.Get("/mount2/dir/test.html");
  6015. ASSERT_TRUE(res);
  6016. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6017. }
  6018. TEST(MountTest, Redicect) {
  6019. Server svr;
  6020. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6021. auto se = detail::scope_exit([&] {
  6022. svr.stop();
  6023. listen_thread.join();
  6024. ASSERT_FALSE(svr.is_running());
  6025. });
  6026. svr.set_mount_point("/", "./www");
  6027. svr.wait_until_ready();
  6028. Client cli("localhost", PORT);
  6029. auto res = cli.Get("/dir/");
  6030. ASSERT_TRUE(res);
  6031. EXPECT_EQ(StatusCode::OK_200, res->status);
  6032. res = cli.Get("/dir");
  6033. ASSERT_TRUE(res);
  6034. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6035. res = cli.Get("/file");
  6036. ASSERT_TRUE(res);
  6037. EXPECT_EQ(StatusCode::OK_200, res->status);
  6038. res = cli.Get("/file/");
  6039. ASSERT_TRUE(res);
  6040. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6041. cli.set_follow_location(true);
  6042. res = cli.Get("/dir");
  6043. ASSERT_TRUE(res);
  6044. EXPECT_EQ(StatusCode::OK_200, res->status);
  6045. }
  6046. TEST(MountTest, MultibytesPathName) {
  6047. Server svr;
  6048. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6049. auto se = detail::scope_exit([&] {
  6050. svr.stop();
  6051. listen_thread.join();
  6052. ASSERT_FALSE(svr.is_running());
  6053. });
  6054. svr.set_mount_point("/", "./www");
  6055. svr.wait_until_ready();
  6056. Client cli("localhost", PORT);
  6057. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6058. ASSERT_TRUE(res);
  6059. EXPECT_EQ(StatusCode::OK_200, res->status);
  6060. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6061. }
  6062. TEST(KeepAliveTest, ReadTimeout) {
  6063. Server svr;
  6064. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6065. std::this_thread::sleep_for(std::chrono::seconds(2));
  6066. res.set_content("a", "text/plain");
  6067. });
  6068. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6069. res.set_content("b", "text/plain");
  6070. });
  6071. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6072. auto se = detail::scope_exit([&] {
  6073. svr.stop();
  6074. listen_thread.join();
  6075. ASSERT_FALSE(svr.is_running());
  6076. });
  6077. svr.wait_until_ready();
  6078. Client cli("localhost", PORT);
  6079. cli.set_keep_alive(true);
  6080. cli.set_read_timeout(std::chrono::seconds(1));
  6081. auto resa = cli.Get("/a");
  6082. ASSERT_FALSE(resa);
  6083. EXPECT_EQ(Error::Read, resa.error());
  6084. auto resb = cli.Get("/b");
  6085. ASSERT_TRUE(resb);
  6086. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6087. EXPECT_EQ("b", resb->body);
  6088. }
  6089. TEST(KeepAliveTest, MaxCount) {
  6090. size_t keep_alive_max_count = 3;
  6091. Server svr;
  6092. svr.set_keep_alive_max_count(keep_alive_max_count);
  6093. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6094. res.set_content("Hello World!", "text/plain");
  6095. });
  6096. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6097. auto se = detail::scope_exit([&] {
  6098. svr.stop();
  6099. listen_thread.join();
  6100. ASSERT_FALSE(svr.is_running());
  6101. });
  6102. svr.wait_until_ready();
  6103. Client cli(HOST, PORT);
  6104. cli.set_keep_alive(true);
  6105. for (size_t i = 0; i < 5; i++) {
  6106. auto result = cli.Get("/hi");
  6107. ASSERT_TRUE(result);
  6108. EXPECT_EQ(StatusCode::OK_200, result->status);
  6109. if (i == keep_alive_max_count - 1) {
  6110. EXPECT_EQ("close", result->get_header_value("Connection"));
  6111. } else {
  6112. EXPECT_FALSE(result->has_header("Connection"));
  6113. }
  6114. }
  6115. }
  6116. TEST(KeepAliveTest, Issue1041) {
  6117. Server svr;
  6118. svr.set_keep_alive_timeout(3);
  6119. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6120. res.set_content("Hello World!", "text/plain");
  6121. });
  6122. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6123. auto se = detail::scope_exit([&] {
  6124. svr.stop();
  6125. listen_thread.join();
  6126. ASSERT_FALSE(svr.is_running());
  6127. });
  6128. svr.wait_until_ready();
  6129. Client cli(HOST, PORT);
  6130. cli.set_keep_alive(true);
  6131. auto result = cli.Get("/hi");
  6132. ASSERT_TRUE(result);
  6133. EXPECT_EQ(StatusCode::OK_200, result->status);
  6134. std::this_thread::sleep_for(std::chrono::seconds(5));
  6135. result = cli.Get("/hi");
  6136. ASSERT_TRUE(result);
  6137. EXPECT_EQ(StatusCode::OK_200, result->status);
  6138. }
  6139. TEST(KeepAliveTest, Issue1959) {
  6140. Server svr;
  6141. svr.set_keep_alive_timeout(5);
  6142. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6143. res.set_content("a", "text/plain");
  6144. });
  6145. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6146. auto se = detail::scope_exit([&] {
  6147. if (!svr.is_running()) return;
  6148. svr.stop();
  6149. listen_thread.join();
  6150. ASSERT_FALSE(svr.is_running());
  6151. });
  6152. svr.wait_until_ready();
  6153. Client cli("localhost", PORT);
  6154. cli.set_keep_alive(true);
  6155. using namespace std::chrono;
  6156. auto start = steady_clock::now();
  6157. cli.Get("/a");
  6158. svr.stop();
  6159. listen_thread.join();
  6160. auto end = steady_clock::now();
  6161. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6162. EXPECT_LT(elapsed, 5000);
  6163. }
  6164. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6165. TEST(KeepAliveTest, SSLClientReconnection) {
  6166. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6167. ASSERT_TRUE(svr.is_valid());
  6168. svr.set_keep_alive_timeout(1);
  6169. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6170. res.set_content("Hello World!", "text/plain");
  6171. });
  6172. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6173. auto se = detail::scope_exit([&] {
  6174. svr.stop();
  6175. listen_thread.join();
  6176. ASSERT_FALSE(svr.is_running());
  6177. });
  6178. svr.wait_until_ready();
  6179. SSLClient cli(HOST, PORT);
  6180. cli.enable_server_certificate_verification(false);
  6181. cli.set_keep_alive(true);
  6182. auto result = cli.Get("/hi");
  6183. ASSERT_TRUE(result);
  6184. EXPECT_EQ(StatusCode::OK_200, result->status);
  6185. result = cli.Get("/hi");
  6186. ASSERT_TRUE(result);
  6187. EXPECT_EQ(StatusCode::OK_200, result->status);
  6188. std::this_thread::sleep_for(std::chrono::seconds(2));
  6189. // Recoonect
  6190. result = cli.Get("/hi");
  6191. ASSERT_TRUE(result);
  6192. EXPECT_EQ(StatusCode::OK_200, result->status);
  6193. result = cli.Get("/hi");
  6194. ASSERT_TRUE(result);
  6195. EXPECT_EQ(StatusCode::OK_200, result->status);
  6196. }
  6197. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6198. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6199. ASSERT_TRUE(svr.is_valid());
  6200. svr.set_keep_alive_timeout(1);
  6201. std::string content = "reconnect";
  6202. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6203. res.set_content("Hello World!", "text/plain");
  6204. });
  6205. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6206. auto se = detail::scope_exit([&] {
  6207. svr.stop();
  6208. listen_thread.join();
  6209. ASSERT_FALSE(svr.is_running());
  6210. });
  6211. svr.wait_until_ready();
  6212. SSLClient cli(HOST, PORT);
  6213. cli.enable_server_certificate_verification(false);
  6214. cli.set_keep_alive(true);
  6215. auto result = cli.Post(
  6216. "/hi", content.size(),
  6217. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6218. sink.write(content.c_str(), content.size());
  6219. return true;
  6220. },
  6221. "text/plain");
  6222. ASSERT_TRUE(result);
  6223. EXPECT_EQ(200, result->status);
  6224. std::this_thread::sleep_for(std::chrono::seconds(2));
  6225. // Recoonect
  6226. result = cli.Post(
  6227. "/hi", content.size(),
  6228. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6229. sink.write(content.c_str(), content.size());
  6230. return true;
  6231. },
  6232. "text/plain");
  6233. ASSERT_TRUE(result);
  6234. EXPECT_EQ(200, result->status);
  6235. result = cli.Post(
  6236. "/hi", content.size(),
  6237. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6238. sink.write(content.c_str(), content.size());
  6239. return true;
  6240. },
  6241. "text/plain");
  6242. ASSERT_TRUE(result);
  6243. EXPECT_EQ(200, result->status);
  6244. }
  6245. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6246. {
  6247. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6248. ASSERT_TRUE(svr.is_valid());
  6249. svr.Get("/sni", [&](const Request &req, Response &res) {
  6250. std::string expected;
  6251. if (req.ssl) {
  6252. if (const char *sni =
  6253. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6254. expected = sni;
  6255. }
  6256. }
  6257. EXPECT_EQ(expected, req.get_param_value("expected"));
  6258. res.set_content("ok", "text/plain");
  6259. });
  6260. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6261. auto se = detail::scope_exit([&] {
  6262. svr.stop();
  6263. listen_thread.join();
  6264. ASSERT_FALSE(svr.is_running());
  6265. });
  6266. svr.wait_until_ready();
  6267. {
  6268. SSLClient cli("localhost", PORT);
  6269. cli.enable_server_certificate_verification(false);
  6270. auto res = cli.Get("/sni?expected=localhost");
  6271. ASSERT_TRUE(res);
  6272. }
  6273. {
  6274. SSLClient cli("::1", PORT);
  6275. cli.enable_server_certificate_verification(false);
  6276. auto res = cli.Get("/sni?expected=");
  6277. ASSERT_TRUE(res);
  6278. }
  6279. }
  6280. }
  6281. #endif
  6282. TEST(ClientProblemDetectionTest, ContentProvider) {
  6283. Server svr;
  6284. size_t content_length = 1024 * 1024;
  6285. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6286. res.set_content_provider(
  6287. content_length, "text/plain",
  6288. [&](size_t offset, size_t length, DataSink &sink) {
  6289. auto out_len = std::min(length, static_cast<size_t>(1024));
  6290. std::string out(out_len, '@');
  6291. sink.write(out.data(), out_len);
  6292. return offset < 4096;
  6293. },
  6294. [](bool success) { ASSERT_FALSE(success); });
  6295. });
  6296. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6297. res.set_content_provider(
  6298. 0, "text/plain",
  6299. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6300. EXPECT_TRUE(false);
  6301. return true;
  6302. },
  6303. [](bool success) { ASSERT_FALSE(success); });
  6304. });
  6305. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6306. auto se = detail::scope_exit([&] {
  6307. svr.stop();
  6308. listen_thread.join();
  6309. ASSERT_FALSE(svr.is_running());
  6310. });
  6311. svr.wait_until_ready();
  6312. Client cli("localhost", PORT);
  6313. {
  6314. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6315. size_t /*data_length*/) { return false; });
  6316. ASSERT_FALSE(res);
  6317. }
  6318. {
  6319. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6320. size_t /*data_length*/) { return false; });
  6321. ASSERT_TRUE(res);
  6322. }
  6323. }
  6324. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6325. Server svr;
  6326. svr.set_error_handler([](Request const &, Response &res) -> void {
  6327. res.set_chunked_content_provider(
  6328. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6329. sink.os << "hello";
  6330. sink.os << "world";
  6331. sink.done();
  6332. return true;
  6333. });
  6334. });
  6335. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6336. auto se = detail::scope_exit([&] {
  6337. svr.stop();
  6338. listen_thread.join();
  6339. ASSERT_FALSE(svr.is_running());
  6340. });
  6341. svr.wait_until_ready();
  6342. Client cli("localhost", PORT);
  6343. auto res = cli.Get("/");
  6344. ASSERT_TRUE(res);
  6345. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6346. EXPECT_EQ("helloworld", res->body);
  6347. }
  6348. TEST(LongPollingTest, ClientCloseDetection) {
  6349. Server svr;
  6350. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6351. res.set_chunked_content_provider(
  6352. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6353. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6354. sink.os << "hello";
  6355. auto count = 10;
  6356. while (count > 0 && sink.is_writable()) {
  6357. this_thread::sleep_for(chrono::milliseconds(10));
  6358. count--;
  6359. }
  6360. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6361. return true;
  6362. });
  6363. });
  6364. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6365. auto se = detail::scope_exit([&] {
  6366. svr.stop();
  6367. listen_thread.join();
  6368. ASSERT_FALSE(svr.is_running());
  6369. });
  6370. svr.wait_until_ready();
  6371. Client cli("localhost", PORT);
  6372. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6373. EXPECT_EQ("hello", string(data, data_length));
  6374. return false; // close the socket immediately.
  6375. });
  6376. ASSERT_FALSE(res);
  6377. }
  6378. TEST(GetWithParametersTest, GetWithParameters) {
  6379. Server svr;
  6380. svr.Get("/", [&](const Request &req, Response &) {
  6381. EXPECT_EQ("world", req.get_param_value("hello"));
  6382. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6383. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6384. });
  6385. svr.Get("/params", [&](const Request &req, Response &) {
  6386. EXPECT_EQ("world", req.get_param_value("hello"));
  6387. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6388. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6389. });
  6390. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6391. EXPECT_EQ("resource-id", req.matches[1]);
  6392. EXPECT_EQ("foo", req.get_param_value("param1"));
  6393. EXPECT_EQ("bar", req.get_param_value("param2"));
  6394. });
  6395. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6396. EXPECT_EQ("user-id", req.path_params.at("id"));
  6397. EXPECT_EQ("foo", req.get_param_value("param1"));
  6398. EXPECT_EQ("bar", req.get_param_value("param2"));
  6399. });
  6400. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6401. auto se = detail::scope_exit([&] {
  6402. svr.stop();
  6403. listen_thread.join();
  6404. ASSERT_FALSE(svr.is_running());
  6405. });
  6406. svr.wait_until_ready();
  6407. {
  6408. Client cli(HOST, PORT);
  6409. Params params;
  6410. params.emplace("hello", "world");
  6411. params.emplace("hello2", "world2");
  6412. params.emplace("hello3", "world3");
  6413. auto res = cli.Get("/", params, Headers{});
  6414. ASSERT_TRUE(res);
  6415. EXPECT_EQ(StatusCode::OK_200, res->status);
  6416. }
  6417. {
  6418. Client cli(HOST, PORT);
  6419. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6420. ASSERT_TRUE(res);
  6421. EXPECT_EQ(StatusCode::OK_200, res->status);
  6422. }
  6423. {
  6424. Client cli(HOST, PORT);
  6425. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6426. ASSERT_TRUE(res);
  6427. EXPECT_EQ(StatusCode::OK_200, res->status);
  6428. }
  6429. {
  6430. Client cli(HOST, PORT);
  6431. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6432. ASSERT_TRUE(res);
  6433. EXPECT_EQ(StatusCode::OK_200, res->status);
  6434. }
  6435. }
  6436. TEST(GetWithParametersTest, GetWithParameters2) {
  6437. Server svr;
  6438. svr.Get("/", [&](const Request &req, Response &res) {
  6439. auto text = req.get_param_value("hello");
  6440. res.set_content(text, "text/plain");
  6441. });
  6442. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6443. auto se = detail::scope_exit([&] {
  6444. svr.stop();
  6445. listen_thread.join();
  6446. ASSERT_FALSE(svr.is_running());
  6447. });
  6448. svr.wait_until_ready();
  6449. Client cli("localhost", PORT);
  6450. Params params;
  6451. params.emplace("hello", "world");
  6452. std::string body;
  6453. auto res = cli.Get("/", params, Headers{},
  6454. [&](const char *data, size_t data_length) {
  6455. body.append(data, data_length);
  6456. return true;
  6457. });
  6458. ASSERT_TRUE(res);
  6459. EXPECT_EQ(StatusCode::OK_200, res->status);
  6460. EXPECT_EQ("world", body);
  6461. }
  6462. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6463. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6464. auto host = "httpbin.org";
  6465. auto path = std::string{"/range/32"};
  6466. #else
  6467. auto host = "nghttp2.org";
  6468. auto path = std::string{"/httpbin/range/32"};
  6469. #endif
  6470. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6471. SSLClient cli(host);
  6472. #else
  6473. Client cli(host);
  6474. #endif
  6475. cli.set_default_headers({make_range_header({{1, 10}})});
  6476. cli.set_connection_timeout(5);
  6477. {
  6478. auto res = cli.Get(path);
  6479. ASSERT_TRUE(res);
  6480. EXPECT_EQ("bcdefghijk", res->body);
  6481. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6482. }
  6483. {
  6484. auto res = cli.Get(path);
  6485. ASSERT_TRUE(res);
  6486. EXPECT_EQ("bcdefghijk", res->body);
  6487. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6488. }
  6489. }
  6490. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6491. Server svr;
  6492. svr.set_default_headers({{"Hello", "World"}});
  6493. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6494. res.set_content("ok", "text/plain");
  6495. });
  6496. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6497. auto se = detail::scope_exit([&] {
  6498. svr.stop();
  6499. listen_thread.join();
  6500. ASSERT_FALSE(svr.is_running());
  6501. });
  6502. svr.wait_until_ready();
  6503. Client cli("localhost", PORT);
  6504. auto res = cli.Get("/");
  6505. ASSERT_TRUE(res);
  6506. EXPECT_EQ(StatusCode::OK_200, res->status);
  6507. EXPECT_EQ("ok", res->body);
  6508. EXPECT_EQ("World", res->get_header_value("Hello"));
  6509. }
  6510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6511. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6513. ASSERT_TRUE(svr.is_valid());
  6514. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6515. std::this_thread::sleep_for(std::chrono::seconds(2));
  6516. res.set_content("a", "text/plain");
  6517. });
  6518. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6519. res.set_content("b", "text/plain");
  6520. });
  6521. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6522. auto se = detail::scope_exit([&] {
  6523. svr.stop();
  6524. listen_thread.join();
  6525. ASSERT_FALSE(svr.is_running());
  6526. });
  6527. svr.wait_until_ready();
  6528. SSLClient cli("localhost", PORT);
  6529. cli.enable_server_certificate_verification(false);
  6530. cli.set_keep_alive(true);
  6531. cli.set_read_timeout(std::chrono::seconds(1));
  6532. auto resa = cli.Get("/a");
  6533. ASSERT_TRUE(!resa);
  6534. EXPECT_EQ(Error::Read, resa.error());
  6535. auto resb = cli.Get("/b");
  6536. ASSERT_TRUE(resb);
  6537. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6538. EXPECT_EQ("b", resb->body);
  6539. }
  6540. #endif
  6541. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6542. protected:
  6543. ServerTestWithAI_PASSIVE()
  6544. : cli_(HOST, PORT)
  6545. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6546. ,
  6547. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6548. #endif
  6549. {
  6550. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6551. cli_.enable_server_certificate_verification(false);
  6552. #endif
  6553. }
  6554. virtual void SetUp() {
  6555. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6556. res.set_content("Hello World!", "text/plain");
  6557. });
  6558. t_ = thread(
  6559. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6560. svr_.wait_until_ready();
  6561. }
  6562. virtual void TearDown() {
  6563. svr_.stop();
  6564. t_.join();
  6565. }
  6566. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6567. SSLClient cli_;
  6568. SSLServer svr_;
  6569. #else
  6570. Client cli_;
  6571. Server svr_;
  6572. #endif
  6573. thread t_;
  6574. };
  6575. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6576. auto res = cli_.Get("/hi");
  6577. ASSERT_TRUE(res);
  6578. EXPECT_EQ(StatusCode::OK_200, res->status);
  6579. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6580. EXPECT_EQ("Hello World!", res->body);
  6581. }
  6582. class ServerUpDownTest : public ::testing::Test {
  6583. protected:
  6584. ServerUpDownTest() : cli_(HOST, PORT) {}
  6585. virtual void SetUp() {
  6586. t_ = thread([&]() {
  6587. svr_.bind_to_any_port(HOST);
  6588. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6589. ASSERT_TRUE(svr_.listen_after_bind());
  6590. });
  6591. svr_.wait_until_ready();
  6592. }
  6593. virtual void TearDown() {
  6594. svr_.stop();
  6595. t_.join();
  6596. }
  6597. Client cli_;
  6598. Server svr_;
  6599. thread t_;
  6600. };
  6601. TEST_F(ServerUpDownTest, QuickStartStop) {
  6602. // Should not crash, especially when run with
  6603. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6604. }
  6605. class PayloadMaxLengthTest : public ::testing::Test {
  6606. protected:
  6607. PayloadMaxLengthTest()
  6608. : cli_(HOST, PORT)
  6609. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6610. ,
  6611. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6612. #endif
  6613. {
  6614. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6615. cli_.enable_server_certificate_verification(false);
  6616. #endif
  6617. }
  6618. virtual void SetUp() {
  6619. svr_.set_payload_max_length(8);
  6620. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6621. res.set_content("test", "text/plain");
  6622. });
  6623. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6624. svr_.wait_until_ready();
  6625. }
  6626. virtual void TearDown() {
  6627. svr_.stop();
  6628. t_.join();
  6629. }
  6630. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6631. SSLClient cli_;
  6632. SSLServer svr_;
  6633. #else
  6634. Client cli_;
  6635. Server svr_;
  6636. #endif
  6637. thread t_;
  6638. };
  6639. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6640. auto res = cli_.Post("/test", "123456789", "text/plain");
  6641. ASSERT_TRUE(res);
  6642. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6643. res = cli_.Post("/test", "12345678", "text/plain");
  6644. ASSERT_TRUE(res);
  6645. EXPECT_EQ(StatusCode::OK_200, res->status);
  6646. }
  6647. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6648. // Test chunked encoding with payload exceeding the 8-byte limit
  6649. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6650. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6651. ASSERT_TRUE(res);
  6652. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6653. }
  6654. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6655. // Test chunked encoding with payload within the 8-byte limit
  6656. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6657. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6658. ASSERT_TRUE(res);
  6659. EXPECT_EQ(StatusCode::OK_200, res->status);
  6660. }
  6661. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6662. // Test using send_request to send chunked data exceeding payload limit
  6663. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6664. "Host: " +
  6665. std::string(HOST) + ":" + std::to_string(PORT) +
  6666. "\r\n"
  6667. "Transfer-Encoding: chunked\r\n"
  6668. "Connection: close\r\n"
  6669. "\r\n"
  6670. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6671. "0123456789\r\n"
  6672. "0\r\n" // End chunk
  6673. "\r\n";
  6674. std::string response;
  6675. bool result = send_request(1, chunked_request, &response);
  6676. if (!result) {
  6677. // If send_request fails, it might be because the server closed the
  6678. // connection due to payload limit enforcement, which is acceptable
  6679. SUCCEED()
  6680. << "Server rejected oversized chunked request (connection closed)";
  6681. } else {
  6682. // If we got a response, check if it's an error response or connection was
  6683. // closed early Short response length indicates connection was closed due to
  6684. // payload limit
  6685. if (response.length() <= 10) {
  6686. SUCCEED() << "Server closed connection for oversized chunked request";
  6687. } else {
  6688. // Check for error status codes
  6689. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6690. response.find("Payload Too Large") != std::string::npos ||
  6691. response.find("400") != std::string::npos);
  6692. }
  6693. }
  6694. }
  6695. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6696. // Test request without Content-Length header exceeding payload limit
  6697. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6698. "Host: " +
  6699. std::string(HOST) + ":" +
  6700. std::to_string(PORT) +
  6701. "\r\n"
  6702. "Connection: close\r\n"
  6703. "\r\n";
  6704. // Add payload exceeding the 8-byte limit
  6705. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6706. request_without_content_length += large_payload;
  6707. std::string response;
  6708. bool result = send_request(1, request_without_content_length, &response);
  6709. if (!result) {
  6710. // If send_request fails, server likely closed connection due to payload
  6711. // limit
  6712. SUCCEED() << "Server rejected oversized request without Content-Length "
  6713. "(connection closed)";
  6714. } else {
  6715. // Check if server responded with error or closed connection early
  6716. if (response.length() <= 10) {
  6717. SUCCEED() << "Server closed connection for oversized request without "
  6718. "Content-Length";
  6719. } else {
  6720. // Check for error status codes
  6721. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6722. response.find("Payload Too Large") != std::string::npos ||
  6723. response.find("400") != std::string::npos);
  6724. }
  6725. }
  6726. }
  6727. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6728. // Test request without Content-Length header within payload limit
  6729. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6730. "Host: " +
  6731. std::string(HOST) + ":" +
  6732. std::to_string(PORT) +
  6733. "\r\n"
  6734. "Connection: close\r\n"
  6735. "\r\n";
  6736. // Add payload within the 8-byte limit
  6737. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6738. request_without_content_length += small_payload;
  6739. std::string response;
  6740. bool result = send_request(1, request_without_content_length, &response);
  6741. // For requests without Content-Length, the server may have different behavior
  6742. // The key is that it should not reject due to payload limit for small
  6743. // payloads
  6744. if (result) {
  6745. // Check for any HTTP response (success or error, but not connection closed)
  6746. if (response.length() > 10) {
  6747. SUCCEED()
  6748. << "Server processed request without Content-Length within limit";
  6749. } else {
  6750. // Short response might indicate connection closed, which is acceptable
  6751. SUCCEED() << "Server closed connection for request without "
  6752. "Content-Length (acceptable behavior)";
  6753. }
  6754. } else {
  6755. // Connection failure might be due to protocol requirements
  6756. SUCCEED() << "Connection issue with request without Content-Length "
  6757. "(environment-specific)";
  6758. }
  6759. }
  6760. class LargePayloadMaxLengthTest : public ::testing::Test {
  6761. protected:
  6762. LargePayloadMaxLengthTest()
  6763. : cli_(HOST, PORT)
  6764. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6765. ,
  6766. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6767. #endif
  6768. {
  6769. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6770. cli_.enable_server_certificate_verification(false);
  6771. #endif
  6772. }
  6773. virtual void SetUp() {
  6774. // Set 10MB payload limit
  6775. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6776. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6777. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6778. res.set_content("Large payload test", "text/plain");
  6779. });
  6780. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6781. svr_.wait_until_ready();
  6782. }
  6783. virtual void TearDown() {
  6784. svr_.stop();
  6785. t_.join();
  6786. }
  6787. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6788. SSLClient cli_;
  6789. SSLServer svr_;
  6790. #else
  6791. Client cli_;
  6792. Server svr_;
  6793. #endif
  6794. thread t_;
  6795. };
  6796. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6797. // Test chunked encoding with payload within 10MB limit
  6798. std::string medium_payload(5 * 1024 * 1024,
  6799. 'A'); // 5MB payload, within 10MB limit
  6800. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6801. ASSERT_TRUE(res);
  6802. EXPECT_EQ(StatusCode::OK_200, res->status);
  6803. }
  6804. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6805. // Test chunked encoding with payload exceeding 10MB limit
  6806. std::string large_payload(12 * 1024 * 1024,
  6807. 'B'); // 12MB payload, exceeds 10MB limit
  6808. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6809. ASSERT_TRUE(res);
  6810. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6811. }
  6812. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6813. // Test request without Content-Length header within 10MB limit
  6814. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6815. "Host: " +
  6816. std::string(HOST) + ":" +
  6817. std::to_string(PORT) +
  6818. "\r\n"
  6819. "Connection: close\r\n"
  6820. "\r\n";
  6821. // Add 1MB payload (within 10MB limit)
  6822. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6823. request_without_content_length += medium_payload;
  6824. std::string response;
  6825. bool result = send_request(5, request_without_content_length, &response);
  6826. if (result) {
  6827. // Should get a proper HTTP response for payloads within limit
  6828. if (response.length() > 10) {
  6829. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6830. "10MB limit";
  6831. } else {
  6832. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6833. "Content-Length)";
  6834. }
  6835. } else {
  6836. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6837. }
  6838. }
  6839. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6840. // Test request without Content-Length header exceeding 10MB limit
  6841. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6842. "Host: " +
  6843. std::string(HOST) + ":" +
  6844. std::to_string(PORT) +
  6845. "\r\n"
  6846. "Connection: close\r\n"
  6847. "\r\n";
  6848. // Add 12MB payload (exceeds 10MB limit)
  6849. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6850. request_without_content_length += large_payload;
  6851. std::string response;
  6852. bool result = send_request(10, request_without_content_length, &response);
  6853. if (!result) {
  6854. // Server should close connection due to payload limit
  6855. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6856. "(connection closed)";
  6857. } else {
  6858. // Check for error response
  6859. if (response.length() <= 10) {
  6860. SUCCEED()
  6861. << "Server closed connection for 12MB request exceeding 10MB limit";
  6862. } else {
  6863. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6864. response.find("Payload Too Large") != std::string::npos ||
  6865. response.find("400") != std::string::npos);
  6866. }
  6867. }
  6868. }
  6869. TEST(HostAndPortPropertiesTest, NoSSL) {
  6870. httplib::Client cli("www.google.com", 1234);
  6871. ASSERT_EQ("www.google.com", cli.host());
  6872. ASSERT_EQ(1234, cli.port());
  6873. }
  6874. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6875. httplib::Client cli("www.google.com:1234");
  6876. ASSERT_EQ("www.google.com", cli.host());
  6877. ASSERT_EQ(1234, cli.port());
  6878. }
  6879. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6880. TEST(HostAndPortPropertiesTest, SSL) {
  6881. httplib::SSLClient cli("www.google.com");
  6882. ASSERT_EQ("www.google.com", cli.host());
  6883. ASSERT_EQ(443, cli.port());
  6884. }
  6885. #endif
  6886. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6887. TEST(SSLClientTest, UpdateCAStore) {
  6888. httplib::SSLClient httplib_client("www.google.com");
  6889. auto ca_store_1 = X509_STORE_new();
  6890. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6891. nullptr);
  6892. httplib_client.set_ca_cert_store(ca_store_1);
  6893. auto ca_store_2 = X509_STORE_new();
  6894. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6895. nullptr);
  6896. httplib_client.set_ca_cert_store(ca_store_2);
  6897. }
  6898. TEST(SSLClientTest, ServerNameIndication_Online) {
  6899. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6900. auto host = "httpbin.org";
  6901. auto path = std::string{"/get"};
  6902. #else
  6903. auto host = "nghttp2.org";
  6904. auto path = std::string{"/httpbin/get"};
  6905. #endif
  6906. SSLClient cli(host, 443);
  6907. auto res = cli.Get(path);
  6908. ASSERT_TRUE(res);
  6909. ASSERT_EQ(StatusCode::OK_200, res->status);
  6910. }
  6911. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6912. // Use a site that will cause SSL verification failure due to self-signed cert
  6913. SSLClient cli("self-signed.badssl.com", 443);
  6914. cli.enable_server_certificate_verification(true);
  6915. auto res = cli.Get("/");
  6916. ASSERT_TRUE(!res);
  6917. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6918. // For SSL server verification errors, ssl_error should be 0, only
  6919. // ssl_openssl_error should be set
  6920. EXPECT_EQ(0, res.ssl_error());
  6921. // Verify OpenSSL error is captured for SSLServerVerification
  6922. // This occurs when SSL_get_verify_result() returns a verification failure
  6923. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6924. res.ssl_openssl_error());
  6925. }
  6926. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6927. // Use a site where hostname doesn't match the certificate
  6928. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6929. SSLClient cli("wrong.host.badssl.com", 443);
  6930. cli.enable_server_certificate_verification(true);
  6931. cli.enable_server_hostname_verification(true);
  6932. auto res = cli.Get("/");
  6933. ASSERT_TRUE(!res);
  6934. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6935. // For SSL hostname verification errors, ssl_error should be 0, only
  6936. // ssl_openssl_error should be set
  6937. EXPECT_EQ(0, res.ssl_error());
  6938. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6939. // This occurs when verify_host() fails due to hostname mismatch
  6940. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6941. res.ssl_openssl_error());
  6942. }
  6943. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6944. Client cli("https://google.com");
  6945. auto res = cli.Get("/");
  6946. ASSERT_TRUE(res);
  6947. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6948. }
  6949. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6950. SSLClient cli("google.com");
  6951. cli.set_ca_cert_path(CA_CERT_FILE);
  6952. auto res = cli.Get("/");
  6953. ASSERT_TRUE(res);
  6954. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6955. }
  6956. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6957. SSLClient cli("google.com");
  6958. cli.enable_server_certificate_verification(true);
  6959. cli.set_ca_cert_path("hello");
  6960. auto res = cli.Get("/");
  6961. ASSERT_TRUE(!res);
  6962. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6963. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6964. // should be set
  6965. EXPECT_EQ(0, res.ssl_error());
  6966. // Verify OpenSSL error is captured for SSLLoadingCerts
  6967. // This error occurs when SSL_CTX_load_verify_locations() fails
  6968. // > openssl errstr 0x80000002
  6969. // error:80000002:system library::No such file or directory
  6970. // > openssl errstr 0xA000126
  6971. // error:0A000126:SSL routines::unexpected eof while reading
  6972. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6973. res.ssl_openssl_error() == 0xA000126);
  6974. }
  6975. TEST(SSLClientTest, ServerCertificateVerification4) {
  6976. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6977. ASSERT_TRUE(svr.is_valid());
  6978. svr.Get("/test", [&](const Request &, Response &res) {
  6979. res.set_content("test", "text/plain");
  6980. svr.stop();
  6981. ASSERT_TRUE(true);
  6982. });
  6983. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6984. auto se = detail::scope_exit([&] {
  6985. t.join();
  6986. ASSERT_FALSE(svr.is_running());
  6987. });
  6988. svr.wait_until_ready();
  6989. SSLClient cli("127.0.0.1", PORT);
  6990. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6991. cli.enable_server_certificate_verification(true);
  6992. cli.set_connection_timeout(30);
  6993. auto res = cli.Get("/test");
  6994. ASSERT_TRUE(res);
  6995. ASSERT_EQ(StatusCode::OK_200, res->status);
  6996. }
  6997. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6998. std::string cert;
  6999. read_file(CA_CERT_FILE, cert);
  7000. SSLClient cli("google.com");
  7001. cli.load_ca_cert_store(cert.data(), cert.size());
  7002. const auto res = cli.Get("/");
  7003. ASSERT_TRUE(res);
  7004. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7005. }
  7006. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7007. // clang-format off
  7008. static constexpr char cert[] =
  7009. "GlobalSign Root CA\n"
  7010. "==================\n"
  7011. "-----BEGIN CERTIFICATE-----\n"
  7012. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7013. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7014. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7015. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7016. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7017. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7018. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7019. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7020. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7021. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7022. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7023. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7024. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7025. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7026. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7027. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7028. "-----END CERTIFICATE-----\n";
  7029. // clang-format on
  7030. SSLClient cli("google.com");
  7031. cli.load_ca_cert_store(cert, sizeof(cert));
  7032. const auto res = cli.Get("/");
  7033. ASSERT_TRUE(res);
  7034. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7035. }
  7036. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7037. SSLClient cli("www.youtube.com");
  7038. cli.set_ca_cert_path(CA_CERT_FILE);
  7039. cli.enable_server_certificate_verification(true);
  7040. cli.set_follow_location(true);
  7041. auto res = cli.Get("/");
  7042. ASSERT_TRUE(res);
  7043. ASSERT_EQ(StatusCode::OK_200, res->status);
  7044. }
  7045. TEST(SSLClientTest, Issue2004_Online) {
  7046. Client client("https://google.com");
  7047. client.set_follow_location(true);
  7048. auto res = client.Get("/");
  7049. ASSERT_TRUE(res);
  7050. ASSERT_EQ(StatusCode::OK_200, res->status);
  7051. auto body = res->body;
  7052. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7053. }
  7054. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7055. // Create SSLClient with invalid cert/key to make is_valid() return false
  7056. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7057. "nonexistent_key.pem");
  7058. // is_valid() should be false due to cert loading failure
  7059. ASSERT_FALSE(cli.is_valid());
  7060. auto res = cli.Get("/");
  7061. ASSERT_FALSE(res);
  7062. EXPECT_EQ(Error::SSLConnection, res.error());
  7063. }
  7064. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7065. // Test for Issue #2251: SSL error not properly reported when client cert
  7066. // and key paths are swapped or mismatched
  7067. // This simulates the scenario where user accidentally swaps the cert and key
  7068. // files
  7069. // Using client cert file as private key and vice versa (completely wrong)
  7070. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7071. // Should fail validation due to cert/key mismatch
  7072. ASSERT_FALSE(cli.is_valid());
  7073. // Attempt to make a request should fail with proper error
  7074. auto res = cli.Get("/");
  7075. ASSERT_FALSE(res);
  7076. EXPECT_EQ(Error::SSLConnection, res.error());
  7077. // SSL error should be recorded in the Result object (this is the key fix for
  7078. // Issue #2251)
  7079. auto openssl_error = res.ssl_openssl_error();
  7080. EXPECT_NE(0u, openssl_error);
  7081. }
  7082. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7083. // Another variant: using valid file paths but with mismatched cert/key pair
  7084. // This tests the case where files exist but contain incompatible key material
  7085. // Using client cert with wrong key (cert2 key)
  7086. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7087. // Should fail validation
  7088. ASSERT_FALSE(cli.is_valid());
  7089. auto res = cli.Get("/");
  7090. ASSERT_FALSE(res);
  7091. // Must report error properly, not appear as success
  7092. EXPECT_EQ(Error::SSLConnection, res.error());
  7093. // OpenSSL error should be captured in Result
  7094. EXPECT_NE(0u, res.ssl_openssl_error());
  7095. }
  7096. #if 0
  7097. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7098. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7099. ASSERT_TRUE(cli != nullptr);
  7100. cli->set_address_family(AF_INET6);
  7101. cli->set_interface("en0");
  7102. auto res = cli->Get("/get");
  7103. ASSERT_TRUE(res);
  7104. ASSERT_EQ(StatusCode::OK_200, res->status);
  7105. }
  7106. #endif
  7107. void ClientCertPresent(
  7108. const std::string &client_cert_file,
  7109. const std::string &client_private_key_file,
  7110. const std::string &client_encrypted_private_key_pass = std::string()) {
  7111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7112. CLIENT_CA_CERT_DIR);
  7113. ASSERT_TRUE(svr.is_valid());
  7114. svr.Get("/test", [&](const Request &req, Response &res) {
  7115. res.set_content("test", "text/plain");
  7116. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7117. ASSERT_TRUE(peer_cert != nullptr);
  7118. auto subject_name = X509_get_subject_name(peer_cert);
  7119. ASSERT_TRUE(subject_name != nullptr);
  7120. std::string common_name;
  7121. {
  7122. char name[BUFSIZ];
  7123. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7124. name, sizeof(name));
  7125. common_name.assign(name, static_cast<size_t>(name_len));
  7126. }
  7127. EXPECT_EQ("Common Name", common_name);
  7128. X509_free(peer_cert);
  7129. });
  7130. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7131. auto se = detail::scope_exit([&] {
  7132. svr.stop();
  7133. t.join();
  7134. ASSERT_FALSE(svr.is_running());
  7135. });
  7136. svr.wait_until_ready();
  7137. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7138. client_encrypted_private_key_pass);
  7139. cli.enable_server_certificate_verification(false);
  7140. cli.set_connection_timeout(30);
  7141. auto res = cli.Get("/test");
  7142. ASSERT_TRUE(res);
  7143. ASSERT_EQ(StatusCode::OK_200, res->status);
  7144. }
  7145. TEST(SSLClientServerTest, ClientCertPresent) {
  7146. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7147. }
  7148. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7149. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7150. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7151. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7152. }
  7153. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7154. void MemoryClientCertPresent(
  7155. const std::string &client_cert_file,
  7156. const std::string &client_private_key_file,
  7157. const std::string &client_encrypted_private_key_pass = std::string()) {
  7158. auto f = fopen(SERVER_CERT_FILE, "r+");
  7159. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7160. fclose(f);
  7161. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7162. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7163. fclose(f);
  7164. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7165. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7166. auto client_ca_cert_store = X509_STORE_new();
  7167. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7168. X509_free(client_cert);
  7169. fclose(f);
  7170. f = fopen(client_cert_file.c_str(), "r+");
  7171. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7172. fclose(f);
  7173. f = fopen(client_private_key_file.c_str(), "r+");
  7174. auto client_private_key = PEM_read_PrivateKey(
  7175. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7176. fclose(f);
  7177. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7178. ASSERT_TRUE(svr.is_valid());
  7179. svr.Get("/test", [&](const Request &req, Response &res) {
  7180. res.set_content("test", "text/plain");
  7181. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7182. ASSERT_TRUE(peer_cert != nullptr);
  7183. auto subject_name = X509_get_subject_name(peer_cert);
  7184. ASSERT_TRUE(subject_name != nullptr);
  7185. std::string common_name;
  7186. {
  7187. char name[BUFSIZ];
  7188. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7189. name, sizeof(name));
  7190. common_name.assign(name, static_cast<size_t>(name_len));
  7191. }
  7192. EXPECT_EQ("Common Name", common_name);
  7193. X509_free(peer_cert);
  7194. });
  7195. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7196. auto se = detail::scope_exit([&] {
  7197. svr.stop();
  7198. t.join();
  7199. ASSERT_FALSE(svr.is_running());
  7200. });
  7201. svr.wait_until_ready();
  7202. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7203. client_encrypted_private_key_pass);
  7204. cli.enable_server_certificate_verification(false);
  7205. cli.set_connection_timeout(30);
  7206. auto res = cli.Get("/test");
  7207. ASSERT_TRUE(res);
  7208. ASSERT_EQ(StatusCode::OK_200, res->status);
  7209. X509_free(server_cert);
  7210. EVP_PKEY_free(server_private_key);
  7211. X509_free(client_cert);
  7212. EVP_PKEY_free(client_private_key);
  7213. }
  7214. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7215. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7216. }
  7217. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7218. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7219. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7220. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7221. }
  7222. #endif
  7223. TEST(SSLClientServerTest, ClientCertMissing) {
  7224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7225. CLIENT_CA_CERT_DIR);
  7226. ASSERT_TRUE(svr.is_valid());
  7227. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7229. auto se = detail::scope_exit([&] {
  7230. svr.stop();
  7231. t.join();
  7232. ASSERT_FALSE(svr.is_running());
  7233. });
  7234. svr.wait_until_ready();
  7235. SSLClient cli(HOST, PORT);
  7236. cli.set_connection_timeout(30);
  7237. auto res = cli.Get("/test");
  7238. ASSERT_TRUE(!res);
  7239. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7240. // For SSL server verification errors, ssl_error should be 0, only
  7241. // ssl_openssl_error should be set
  7242. EXPECT_EQ(0, res.ssl_error());
  7243. // Verify OpenSSL error is captured for SSLServerVerification
  7244. // Note: This test may have different error codes depending on the exact
  7245. // verification failure
  7246. EXPECT_NE(0UL, res.ssl_openssl_error());
  7247. }
  7248. TEST(SSLClientServerTest, TrustDirOptional) {
  7249. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7250. ASSERT_TRUE(svr.is_valid());
  7251. svr.Get("/test", [&](const Request &, Response &res) {
  7252. res.set_content("test", "text/plain");
  7253. });
  7254. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7255. auto se = detail::scope_exit([&] {
  7256. svr.stop();
  7257. t.join();
  7258. ASSERT_FALSE(svr.is_running());
  7259. });
  7260. svr.wait_until_ready();
  7261. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7262. cli.enable_server_certificate_verification(false);
  7263. cli.set_connection_timeout(30);
  7264. auto res = cli.Get("/test");
  7265. ASSERT_TRUE(res);
  7266. ASSERT_EQ(StatusCode::OK_200, res->status);
  7267. }
  7268. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7269. class NoListenSSLServer : public SSLServer {
  7270. public:
  7271. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7272. const char *client_ca_cert_file_path,
  7273. const char *client_ca_cert_dir_path = nullptr)
  7274. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7275. client_ca_cert_dir_path),
  7276. stop_(false) {}
  7277. std::atomic_bool stop_;
  7278. private:
  7279. bool process_and_close_socket(socket_t /*sock*/) override {
  7280. // Don't create SSL context
  7281. while (!stop_.load()) {
  7282. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7283. }
  7284. return true;
  7285. }
  7286. };
  7287. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7288. CLIENT_CA_CERT_FILE);
  7289. ASSERT_TRUE(svr.is_valid());
  7290. svr.Get("/test", [&](const Request &, Response &res) {
  7291. res.set_content("test", "text/plain");
  7292. });
  7293. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7294. auto se = detail::scope_exit([&] {
  7295. svr.stop_ = true;
  7296. svr.stop();
  7297. t.join();
  7298. ASSERT_FALSE(svr.is_running());
  7299. });
  7300. svr.wait_until_ready();
  7301. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7302. cli.enable_server_certificate_verification(false);
  7303. cli.set_connection_timeout(1);
  7304. auto res = cli.Get("/test");
  7305. ASSERT_TRUE(!res);
  7306. EXPECT_EQ(Error::SSLConnection, res.error());
  7307. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7308. }
  7309. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7310. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7311. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7312. SSL_CTX_set_options(&ssl_ctx,
  7313. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7314. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7315. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7316. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7317. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7318. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7319. "ECDHE-DSS-AES128-SHA256:"
  7320. "ECDHE-RSA-AES256-SHA256:"
  7321. "ECDHE-DSS-AES256-SHA256:";
  7322. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7323. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7324. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7325. SSL_FILETYPE_PEM) != 1) {
  7326. return false;
  7327. }
  7328. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7329. CLIENT_CA_CERT_DIR);
  7330. SSL_CTX_set_verify(
  7331. &ssl_ctx,
  7332. SSL_VERIFY_PEER |
  7333. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7334. nullptr);
  7335. return true;
  7336. };
  7337. SSLServer svr(setup_ssl_ctx_callback);
  7338. ASSERT_TRUE(svr.is_valid());
  7339. svr.Get("/test", [&](const Request &req, Response &res) {
  7340. res.set_content("test", "text/plain");
  7341. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7342. ASSERT_TRUE(peer_cert != nullptr);
  7343. auto subject_name = X509_get_subject_name(peer_cert);
  7344. ASSERT_TRUE(subject_name != nullptr);
  7345. std::string common_name;
  7346. {
  7347. char name[BUFSIZ];
  7348. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7349. name, sizeof(name));
  7350. common_name.assign(name, static_cast<size_t>(name_len));
  7351. }
  7352. EXPECT_EQ("Common Name", common_name);
  7353. X509_free(peer_cert);
  7354. });
  7355. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7356. auto se = detail::scope_exit([&] {
  7357. svr.stop();
  7358. t.join();
  7359. ASSERT_FALSE(svr.is_running());
  7360. });
  7361. svr.wait_until_ready();
  7362. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7363. cli.enable_server_certificate_verification(false);
  7364. cli.set_connection_timeout(30);
  7365. auto res = cli.Get("/test");
  7366. ASSERT_TRUE(res);
  7367. ASSERT_EQ(StatusCode::OK_200, res->status);
  7368. }
  7369. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7371. ASSERT_TRUE(svr.is_valid());
  7372. // Set up a handler to verify client certificate is present
  7373. bool client_cert_verified = false;
  7374. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7375. // Verify that client certificate was provided
  7376. client_cert_verified = true;
  7377. res.set_content("success", "text/plain");
  7378. });
  7379. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7380. auto se = detail::scope_exit([&] {
  7381. svr.stop();
  7382. t.join();
  7383. ASSERT_FALSE(svr.is_running());
  7384. });
  7385. svr.wait_until_ready();
  7386. // Client with certificate
  7387. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7388. cli.enable_server_certificate_verification(false);
  7389. cli.set_connection_timeout(30);
  7390. auto res = cli.Get("/test");
  7391. ASSERT_TRUE(res);
  7392. ASSERT_EQ(StatusCode::OK_200, res->status);
  7393. ASSERT_TRUE(client_cert_verified);
  7394. EXPECT_EQ("success", res->body);
  7395. }
  7396. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7397. // Test that when client CA cert file is provided,
  7398. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7399. // Create a server with client authentication
  7400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7401. ASSERT_TRUE(svr.is_valid());
  7402. // We can't directly access the SSL_CTX from SSLServer to verify,
  7403. // but we can test that the server properly requests client certificates
  7404. // and accepts valid ones from the specified CA
  7405. bool handler_called = false;
  7406. svr.Get("/test", [&](const Request &req, Response &res) {
  7407. handler_called = true;
  7408. // Verify that a client certificate was provided
  7409. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7410. ASSERT_TRUE(peer_cert != nullptr);
  7411. // Get the issuer name
  7412. auto issuer_name = X509_get_issuer_name(peer_cert);
  7413. ASSERT_TRUE(issuer_name != nullptr);
  7414. char issuer_buf[256];
  7415. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7416. // The client certificate should be issued by our test CA
  7417. std::string issuer_str(issuer_buf);
  7418. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7419. X509_free(peer_cert);
  7420. res.set_content("authenticated", "text/plain");
  7421. });
  7422. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7423. auto se = detail::scope_exit([&] {
  7424. svr.stop();
  7425. t.join();
  7426. ASSERT_FALSE(svr.is_running());
  7427. });
  7428. svr.wait_until_ready();
  7429. // Connect with a client certificate issued by the CA
  7430. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7431. cli.enable_server_certificate_verification(false);
  7432. cli.set_connection_timeout(30);
  7433. auto res = cli.Get("/test");
  7434. ASSERT_TRUE(res);
  7435. ASSERT_EQ(StatusCode::OK_200, res->status);
  7436. ASSERT_TRUE(handler_called);
  7437. EXPECT_EQ("authenticated", res->body);
  7438. }
  7439. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7440. // Test 1: Valid CA file - no error should be recorded
  7441. {
  7442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7443. CLIENT_CA_CERT_FILE);
  7444. ASSERT_TRUE(svr.is_valid());
  7445. // With valid setup, last_ssl_error should be 0
  7446. EXPECT_EQ(0, svr.ssl_last_error());
  7447. }
  7448. // Test 2: Invalid CA file content
  7449. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7450. {
  7451. // Create a temporary file with completely invalid content
  7452. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7453. {
  7454. std::ofstream ofs(temp_invalid_ca);
  7455. ofs << "This is not a certificate file at all\n";
  7456. ofs << "Just plain text content\n";
  7457. }
  7458. // Create server with invalid CA file
  7459. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7460. // Clean up temporary file
  7461. std::remove(temp_invalid_ca);
  7462. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7463. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7464. // Note: SSL_CTX_load_verify_locations typically fails first,
  7465. // but our error handling code path is still exercised
  7466. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7467. }
  7468. }
  7469. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7470. // Test SSL server using X509_STORE constructor with client CA certificates
  7471. // This test verifies that Phase 2 implementation correctly extracts CA names
  7472. // from an X509_STORE and sets them in the SSL context
  7473. // Load the CA certificate into memory
  7474. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7475. ASSERT_NE(nullptr, bio);
  7476. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7477. BIO_free(bio);
  7478. ASSERT_NE(nullptr, ca_cert);
  7479. // Create an X509_STORE and add the CA certificate
  7480. auto store = X509_STORE_new();
  7481. ASSERT_NE(nullptr, store);
  7482. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7483. // Load server certificate and private key
  7484. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7485. ASSERT_NE(nullptr, cert_bio);
  7486. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7487. BIO_free(cert_bio);
  7488. ASSERT_NE(nullptr, server_cert);
  7489. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7490. ASSERT_NE(nullptr, key_bio);
  7491. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7492. BIO_free(key_bio);
  7493. ASSERT_NE(nullptr, server_key);
  7494. // Create SSLServer with X509_STORE constructor
  7495. // Note: X509_STORE ownership is transferred to SSL_CTX
  7496. SSLServer svr(server_cert, server_key, store);
  7497. ASSERT_TRUE(svr.is_valid());
  7498. // No SSL error should be recorded for valid setup
  7499. EXPECT_EQ(0, svr.ssl_last_error());
  7500. // Set up server endpoints
  7501. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7502. res.set_content("ok", "text/plain");
  7503. });
  7504. // Start server in a thread
  7505. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7506. svr.wait_until_ready();
  7507. // Connect with client certificate (using constructor with paths)
  7508. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7509. cli.enable_server_certificate_verification(false);
  7510. auto res = cli.Get("/test-x509store");
  7511. ASSERT_TRUE(res);
  7512. EXPECT_EQ(200, res->status);
  7513. EXPECT_EQ("ok", res->body);
  7514. // Clean up
  7515. X509_free(server_cert);
  7516. EVP_PKEY_free(server_key);
  7517. X509_free(ca_cert);
  7518. svr.stop();
  7519. server_thread.join();
  7520. }
  7521. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7522. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7523. // prepare large data
  7524. std::random_device seed_gen;
  7525. std::mt19937 random(seed_gen());
  7526. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7527. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7528. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7529. // server
  7530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7531. ASSERT_TRUE(svr.is_valid());
  7532. svr.Post("/binary", [&](const Request &req, Response &res) {
  7533. EXPECT_EQ(large_size_byte, req.body.size());
  7534. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7535. res.set_content(req.body, "application/octet-stream");
  7536. });
  7537. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7538. auto se = detail::scope_exit([&] {
  7539. svr.stop();
  7540. listen_thread.join();
  7541. ASSERT_FALSE(svr.is_running());
  7542. });
  7543. svr.wait_until_ready();
  7544. // client POST
  7545. SSLClient cli("localhost", PORT);
  7546. cli.enable_server_certificate_verification(false);
  7547. cli.set_read_timeout(std::chrono::seconds(100));
  7548. cli.set_write_timeout(std::chrono::seconds(100));
  7549. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7550. large_size_byte, "application/octet-stream");
  7551. // compare
  7552. EXPECT_EQ(StatusCode::OK_200, res->status);
  7553. EXPECT_EQ(large_size_byte, res->body.size());
  7554. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7555. }
  7556. #endif
  7557. #ifdef _WIN32
  7558. TEST(CleanupTest, WSACleanup) {
  7559. int ret = WSACleanup();
  7560. ASSERT_EQ(0, ret);
  7561. }
  7562. #endif
  7563. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7564. TEST(NoSSLSupport, SimpleInterface) {
  7565. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7566. }
  7567. #endif
  7568. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7569. TEST(InvalidScheme, SimpleInterface) {
  7570. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7571. }
  7572. #endif
  7573. TEST(NoScheme, SimpleInterface) {
  7574. Client cli("yahoo.com:80");
  7575. ASSERT_TRUE(cli.is_valid());
  7576. }
  7577. TEST(SendAPI, SimpleInterface_Online) {
  7578. Client cli("http://yahoo.com");
  7579. Request req;
  7580. req.method = "GET";
  7581. req.path = "/";
  7582. auto res = cli.send(req);
  7583. ASSERT_TRUE(res);
  7584. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7585. }
  7586. TEST(SendAPI, WithParamsInRequest) {
  7587. Server svr;
  7588. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7589. EXPECT_TRUE(req.has_param("test"));
  7590. EXPECT_EQ("test_value", req.get_param_value("test"));
  7591. });
  7592. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7593. auto se = detail::scope_exit([&] {
  7594. svr.stop();
  7595. t.join();
  7596. ASSERT_FALSE(svr.is_running());
  7597. });
  7598. svr.wait_until_ready();
  7599. Client cli(HOST, PORT);
  7600. {
  7601. Request req;
  7602. req.method = "GET";
  7603. req.path = "/";
  7604. req.params.emplace("test", "test_value");
  7605. auto res = cli.send(req);
  7606. ASSERT_TRUE(res);
  7607. }
  7608. {
  7609. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7610. ASSERT_TRUE(res);
  7611. }
  7612. }
  7613. TEST(ClientImplMethods, GetSocketTest) {
  7614. httplib::Server svr;
  7615. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7616. res.status = StatusCode::OK_200;
  7617. });
  7618. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7619. auto se = detail::scope_exit([&] {
  7620. svr.stop();
  7621. thread.join();
  7622. ASSERT_FALSE(svr.is_running());
  7623. });
  7624. svr.wait_until_ready();
  7625. {
  7626. httplib::Client cli("http://127.0.0.1:3333");
  7627. cli.set_keep_alive(true);
  7628. // Use the behavior of cpp-httplib of opening the connection
  7629. // only when the first request happens. If that changes,
  7630. // this test would be obsolete.
  7631. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7632. // This also implicitly tests the server. But other tests would fail much
  7633. // earlier than this one to be considered.
  7634. auto res = cli.Get("/");
  7635. ASSERT_TRUE(res);
  7636. EXPECT_EQ(StatusCode::OK_200, res->status);
  7637. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7638. }
  7639. }
  7640. // Disabled due to out-of-memory problem on GitHub Actions
  7641. #ifdef _WIN64
  7642. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7643. // allocate content size larger than 2GB in memory
  7644. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7645. char *content = (char *)malloc(content_size);
  7646. ASSERT_TRUE(content);
  7647. Server svr;
  7648. svr.Get("/foo",
  7649. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7650. res.set_content(content, content_size, "application/octet-stream");
  7651. });
  7652. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7653. auto se = detail::scope_exit([&] {
  7654. svr.stop();
  7655. listen_thread.join();
  7656. if (content) free(content);
  7657. ASSERT_FALSE(svr.is_running());
  7658. });
  7659. svr.wait_until_ready();
  7660. Client cli(HOST, PORT);
  7661. auto res = cli.Get("/foo");
  7662. ASSERT_TRUE(res);
  7663. EXPECT_EQ(StatusCode::OK_200, res->status);
  7664. EXPECT_EQ(content_size, res->body.length());
  7665. }
  7666. #endif
  7667. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7668. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7669. Client cli("http://yahoo.com");
  7670. auto res = cli.Get("/");
  7671. ASSERT_TRUE(res);
  7672. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7673. cli.set_follow_location(true);
  7674. res = cli.Get("/");
  7675. ASSERT_TRUE(res);
  7676. EXPECT_EQ(StatusCode::OK_200, res->status);
  7677. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7678. }
  7679. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7680. Client cli("https://yahoo.com");
  7681. auto res = cli.Get("/");
  7682. ASSERT_TRUE(res);
  7683. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7684. cli.set_follow_location(true);
  7685. res = cli.Get("/");
  7686. ASSERT_TRUE(res);
  7687. EXPECT_EQ(StatusCode::OK_200, res->status);
  7688. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7689. }
  7690. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7691. Client cli("https://yahoo.com");
  7692. auto res = cli.Get("/");
  7693. ASSERT_TRUE(res);
  7694. ASSERT_FALSE(!res);
  7695. ASSERT_TRUE(res);
  7696. ASSERT_FALSE(res == nullptr);
  7697. ASSERT_TRUE(res != nullptr);
  7698. EXPECT_EQ(Error::Success, res.error());
  7699. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7700. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7701. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7702. cli.set_follow_location(true);
  7703. res = cli.Get("/");
  7704. ASSERT_TRUE(res);
  7705. EXPECT_EQ(Error::Success, res.error());
  7706. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7707. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7708. EXPECT_EQ(StatusCode::OK_200, res->status);
  7709. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7710. }
  7711. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7712. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7713. Client cli("https://cdnjs.cloudflare.com");
  7714. auto res =
  7715. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7716. ASSERT_TRUE(res);
  7717. EXPECT_EQ(StatusCode::OK_200, res->status);
  7718. EXPECT_EQ(287630U, res->body.size());
  7719. EXPECT_EQ("application/javascript; charset=utf-8",
  7720. res->get_header_value("Content-Type"));
  7721. }
  7722. #endif
  7723. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7724. #undef REDIR_HOST // Silence compiler warning
  7725. #define REDIR_HOST "https://httpbingo.org"
  7726. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7727. Client cli(REDIR_HOST);
  7728. cli.set_follow_location(true);
  7729. auto res =
  7730. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7731. ASSERT_TRUE(res);
  7732. EXPECT_EQ(StatusCode::OK_200, res->status);
  7733. }
  7734. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7735. Client cli(REDIR_HOST);
  7736. cli.set_follow_location(true);
  7737. Params params;
  7738. params.emplace("url", "http://example.com");
  7739. params.emplace("status_code", "302");
  7740. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7741. ASSERT_TRUE(res);
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. }
  7744. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7745. Client cli(REDIR_HOST);
  7746. cli.set_follow_location(true);
  7747. Params params;
  7748. params.emplace("url", "http://example.com");
  7749. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7750. ASSERT_TRUE(res);
  7751. EXPECT_EQ(StatusCode::OK_200, res->status);
  7752. }
  7753. TEST(HttpToHttpsRedirectTest, CertFile) {
  7754. Server svr;
  7755. ASSERT_TRUE(svr.is_valid());
  7756. svr.Get("/index", [&](const Request &, Response &res) {
  7757. res.set_redirect("https://127.0.0.1:1235/index");
  7758. svr.stop();
  7759. });
  7760. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7761. ASSERT_TRUE(ssl_svr.is_valid());
  7762. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7763. res.set_content("test", "text/plain");
  7764. ssl_svr.stop();
  7765. });
  7766. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7767. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7768. auto se = detail::scope_exit([&] {
  7769. t2.join();
  7770. t.join();
  7771. ASSERT_FALSE(svr.is_running());
  7772. });
  7773. svr.wait_until_ready();
  7774. ssl_svr.wait_until_ready();
  7775. Client cli("127.0.0.1", PORT);
  7776. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7777. cli.enable_server_certificate_verification(true);
  7778. cli.set_follow_location(true);
  7779. cli.set_connection_timeout(30);
  7780. auto res = cli.Get("/index");
  7781. ASSERT_TRUE(res);
  7782. ASSERT_EQ(StatusCode::OK_200, res->status);
  7783. }
  7784. TEST(SSLClientRedirectTest, CertFile) {
  7785. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7786. ASSERT_TRUE(ssl_svr1.is_valid());
  7787. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7788. res.set_redirect("https://127.0.0.1:1235/index");
  7789. ssl_svr1.stop();
  7790. });
  7791. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7792. ASSERT_TRUE(ssl_svr2.is_valid());
  7793. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7794. res.set_content("test", "text/plain");
  7795. ssl_svr2.stop();
  7796. });
  7797. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7798. thread t2 =
  7799. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7800. auto se = detail::scope_exit([&] {
  7801. t2.join();
  7802. t.join();
  7803. ASSERT_FALSE(ssl_svr1.is_running());
  7804. });
  7805. ssl_svr1.wait_until_ready();
  7806. ssl_svr2.wait_until_ready();
  7807. SSLClient cli("127.0.0.1", PORT);
  7808. std::string cert;
  7809. read_file(SERVER_CERT2_FILE, cert);
  7810. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7811. cli.enable_server_certificate_verification(true);
  7812. cli.set_follow_location(true);
  7813. cli.set_connection_timeout(30);
  7814. auto res = cli.Get("/index");
  7815. ASSERT_TRUE(res);
  7816. ASSERT_EQ(StatusCode::OK_200, res->status);
  7817. }
  7818. TEST(MultipartFormDataTest, LargeData) {
  7819. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7820. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7821. const ContentReader &content_reader) {
  7822. if (req.is_multipart_form_data()) {
  7823. std::vector<FormData> items;
  7824. content_reader(
  7825. [&](const FormData &file) {
  7826. items.push_back(file);
  7827. return true;
  7828. },
  7829. [&](const char *data, size_t data_length) {
  7830. items.back().content.append(data, data_length);
  7831. return true;
  7832. });
  7833. EXPECT_TRUE(std::string(items[0].name) == "document");
  7834. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7835. EXPECT_TRUE(items[0].filename == "2MB_data");
  7836. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7837. EXPECT_TRUE(items[1].name == "hello");
  7838. EXPECT_TRUE(items[1].content == "world");
  7839. EXPECT_TRUE(items[1].filename == "");
  7840. EXPECT_TRUE(items[1].content_type == "");
  7841. } else {
  7842. std::string body;
  7843. content_reader([&](const char *data, size_t data_length) {
  7844. body.append(data, data_length);
  7845. return true;
  7846. });
  7847. }
  7848. });
  7849. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7850. auto se = detail::scope_exit([&] {
  7851. svr.stop();
  7852. t.join();
  7853. ASSERT_FALSE(svr.is_running());
  7854. });
  7855. svr.wait_until_ready();
  7856. {
  7857. std::string data(1024 * 1024 * 2, '.');
  7858. std::stringstream buffer;
  7859. buffer << data;
  7860. Client cli("https://localhost:8080");
  7861. cli.enable_server_certificate_verification(false);
  7862. UploadFormDataItems items{
  7863. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7864. {"hello", "world", "", ""},
  7865. };
  7866. auto res = cli.Post("/post", items);
  7867. ASSERT_TRUE(res);
  7868. ASSERT_EQ(StatusCode::OK_200, res->status);
  7869. }
  7870. }
  7871. TEST(MultipartFormDataTest, DataProviderItems) {
  7872. std::random_device seed_gen;
  7873. std::mt19937 random(seed_gen());
  7874. std::string rand1;
  7875. rand1.resize(1000);
  7876. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7877. std::string rand2;
  7878. rand2.resize(3000);
  7879. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7881. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7882. const ContentReader &content_reader) {
  7883. ASSERT_FALSE(req.is_multipart_form_data());
  7884. std::string body;
  7885. content_reader([&](const char *data, size_t data_length) {
  7886. body.append(data, data_length);
  7887. return true;
  7888. });
  7889. EXPECT_EQ(body, "");
  7890. });
  7891. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7892. const ContentReader &content_reader) {
  7893. ASSERT_TRUE(req.is_multipart_form_data());
  7894. std::vector<FormData> items;
  7895. content_reader(
  7896. [&](const FormData &file) {
  7897. items.push_back(file);
  7898. return true;
  7899. },
  7900. [&](const char *data, size_t data_length) {
  7901. items.back().content.append(data, data_length);
  7902. return true;
  7903. });
  7904. ASSERT_TRUE(items.size() == 2);
  7905. EXPECT_EQ(std::string(items[0].name), "name1");
  7906. EXPECT_EQ(items[0].content, "Testing123");
  7907. EXPECT_EQ(items[0].filename, "filename1");
  7908. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7909. EXPECT_EQ(items[1].name, "name2");
  7910. EXPECT_EQ(items[1].content, "Testing456");
  7911. EXPECT_EQ(items[1].filename, "");
  7912. EXPECT_EQ(items[1].content_type, "");
  7913. });
  7914. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7915. const ContentReader &content_reader) {
  7916. ASSERT_TRUE(req.is_multipart_form_data());
  7917. std::vector<FormData> items;
  7918. content_reader(
  7919. [&](const FormData &file) {
  7920. items.push_back(file);
  7921. return true;
  7922. },
  7923. [&](const char *data, size_t data_length) {
  7924. items.back().content.append(data, data_length);
  7925. return true;
  7926. });
  7927. ASSERT_TRUE(items.size() == 2);
  7928. EXPECT_EQ(items[0].name, "name3");
  7929. EXPECT_EQ(items[0].content, rand1);
  7930. EXPECT_EQ(items[0].filename, "filename3");
  7931. EXPECT_EQ(items[0].content_type, "");
  7932. EXPECT_EQ(items[1].name, "name4");
  7933. EXPECT_EQ(items[1].content, rand2);
  7934. EXPECT_EQ(items[1].filename, "filename4");
  7935. EXPECT_EQ(items[1].content_type, "");
  7936. });
  7937. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7938. const ContentReader &content_reader) {
  7939. ASSERT_TRUE(req.is_multipart_form_data());
  7940. std::vector<FormData> items;
  7941. content_reader(
  7942. [&](const FormData &file) {
  7943. items.push_back(file);
  7944. return true;
  7945. },
  7946. [&](const char *data, size_t data_length) {
  7947. items.back().content.append(data, data_length);
  7948. return true;
  7949. });
  7950. ASSERT_TRUE(items.size() == 4);
  7951. EXPECT_EQ(std::string(items[0].name), "name1");
  7952. EXPECT_EQ(items[0].content, "Testing123");
  7953. EXPECT_EQ(items[0].filename, "filename1");
  7954. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7955. EXPECT_EQ(items[1].name, "name2");
  7956. EXPECT_EQ(items[1].content, "Testing456");
  7957. EXPECT_EQ(items[1].filename, "");
  7958. EXPECT_EQ(items[1].content_type, "");
  7959. EXPECT_EQ(items[2].name, "name3");
  7960. EXPECT_EQ(items[2].content, rand1);
  7961. EXPECT_EQ(items[2].filename, "filename3");
  7962. EXPECT_EQ(items[2].content_type, "");
  7963. EXPECT_EQ(items[3].name, "name4");
  7964. EXPECT_EQ(items[3].content, rand2);
  7965. EXPECT_EQ(items[3].filename, "filename4");
  7966. EXPECT_EQ(items[3].content_type, "");
  7967. });
  7968. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7969. auto se = detail::scope_exit([&] {
  7970. svr.stop();
  7971. t.join();
  7972. ASSERT_FALSE(svr.is_running());
  7973. });
  7974. svr.wait_until_ready();
  7975. {
  7976. Client cli("https://localhost:8080");
  7977. cli.enable_server_certificate_verification(false);
  7978. UploadFormDataItems items{
  7979. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7980. {"name2", "Testing456", "", ""}, // not a file
  7981. };
  7982. {
  7983. auto res = cli.Post("/post-none", {}, {}, {});
  7984. ASSERT_TRUE(res);
  7985. ASSERT_EQ(StatusCode::OK_200, res->status);
  7986. }
  7987. FormDataProviderItems providers;
  7988. {
  7989. auto res =
  7990. cli.Post("/post-items", {}, items, providers); // empty providers
  7991. ASSERT_TRUE(res);
  7992. ASSERT_EQ(StatusCode::OK_200, res->status);
  7993. }
  7994. providers.push_back({"name3",
  7995. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7996. // test the offset is given correctly at each step
  7997. if (!offset)
  7998. sink.os.write(rand1.data(), 30);
  7999. else if (offset == 30)
  8000. sink.os.write(rand1.data() + 30, 300);
  8001. else if (offset == 330)
  8002. sink.os.write(rand1.data() + 330, 670);
  8003. else if (offset == rand1.size())
  8004. sink.done();
  8005. return true;
  8006. },
  8007. "filename3",
  8008. {}});
  8009. providers.push_back({"name4",
  8010. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8011. // test the offset is given correctly at each step
  8012. if (!offset)
  8013. sink.os.write(rand2.data(), 2000);
  8014. else if (offset == 2000)
  8015. sink.os.write(rand2.data() + 2000, 1);
  8016. else if (offset == 2001)
  8017. sink.os.write(rand2.data() + 2001, 999);
  8018. else if (offset == rand2.size())
  8019. sink.done();
  8020. return true;
  8021. },
  8022. "filename4",
  8023. {}});
  8024. {
  8025. auto res = cli.Post("/post-providers", {}, {}, providers);
  8026. ASSERT_TRUE(res);
  8027. ASSERT_EQ(StatusCode::OK_200, res->status);
  8028. }
  8029. {
  8030. auto res = cli.Post("/post-both", {}, items, providers);
  8031. ASSERT_TRUE(res);
  8032. ASSERT_EQ(StatusCode::OK_200, res->status);
  8033. }
  8034. }
  8035. }
  8036. TEST(MultipartFormDataTest, BadHeader) {
  8037. Server svr;
  8038. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8039. res.set_content("ok", "text/plain");
  8040. });
  8041. thread t = thread([&] { svr.listen(HOST, PORT); });
  8042. auto se = detail::scope_exit([&] {
  8043. svr.stop();
  8044. t.join();
  8045. ASSERT_FALSE(svr.is_running());
  8046. });
  8047. svr.wait_until_ready();
  8048. const std::string body =
  8049. "This is the preamble. It is to be ignored, though it\r\n"
  8050. "is a handy place for composition agents to include an\r\n"
  8051. "explanatory note to non-MIME conformant readers.\r\n"
  8052. "\r\n"
  8053. "\r\n"
  8054. "--simple boundary\r\n"
  8055. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8056. ": BAD...\r\n"
  8057. "\r\n"
  8058. "value1\r\n"
  8059. "--simple boundary\r\n"
  8060. "Content-Disposition: form-data; name=\"field2\"; "
  8061. "filename=\"example.txt\"\r\n"
  8062. "\r\n"
  8063. "value2\r\n"
  8064. "--simple boundary--\r\n"
  8065. "This is the epilogue. It is also to be ignored.\r\n";
  8066. std::string content_type =
  8067. R"(multipart/form-data; boundary="simple boundary")";
  8068. Client cli(HOST, PORT);
  8069. auto res = cli.Post("/post", body, content_type.c_str());
  8070. ASSERT_TRUE(res);
  8071. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8072. }
  8073. TEST(MultipartFormDataTest, WithPreamble) {
  8074. Server svr;
  8075. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8076. res.set_content("ok", "text/plain");
  8077. });
  8078. thread t = thread([&] { svr.listen(HOST, PORT); });
  8079. auto se = detail::scope_exit([&] {
  8080. svr.stop();
  8081. t.join();
  8082. ASSERT_FALSE(svr.is_running());
  8083. });
  8084. svr.wait_until_ready();
  8085. const std::string body =
  8086. "This is the preamble. It is to be ignored, though it\r\n"
  8087. "is a handy place for composition agents to include an\r\n"
  8088. "explanatory note to non-MIME conformant readers.\r\n"
  8089. "\r\n"
  8090. "\r\n"
  8091. "--simple boundary\r\n"
  8092. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8093. "\r\n"
  8094. "value1\r\n"
  8095. "--simple boundary\r\n"
  8096. "Content-Disposition: form-data; name=\"field2\"; "
  8097. "filename=\"example.txt\"\r\n"
  8098. "\r\n"
  8099. "value2\r\n"
  8100. "--simple boundary--\r\n"
  8101. "This is the epilogue. It is also to be ignored.\r\n";
  8102. std::string content_type =
  8103. R"(multipart/form-data; boundary="simple boundary")";
  8104. Client cli(HOST, PORT);
  8105. auto res = cli.Post("/post", body, content_type.c_str());
  8106. ASSERT_TRUE(res);
  8107. EXPECT_EQ(StatusCode::OK_200, res->status);
  8108. }
  8109. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8110. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8111. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8112. const ContentReader &content_reader) {
  8113. if (req.is_multipart_form_data()) {
  8114. std::vector<FormData> items;
  8115. content_reader(
  8116. [&](const FormData &file) {
  8117. items.push_back(file);
  8118. return true;
  8119. },
  8120. [&](const char *data, size_t data_length) {
  8121. items.back().content.append(data, data_length);
  8122. return true;
  8123. });
  8124. EXPECT_TRUE(std::string(items[0].name) == "document");
  8125. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8126. EXPECT_TRUE(items[0].filename == "2MB_data");
  8127. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8128. EXPECT_TRUE(items[1].name == "hello");
  8129. EXPECT_TRUE(items[1].content == "world");
  8130. EXPECT_TRUE(items[1].filename == "");
  8131. EXPECT_TRUE(items[1].content_type == "");
  8132. } else {
  8133. std::string body;
  8134. content_reader([&](const char *data, size_t data_length) {
  8135. body.append(data, data_length);
  8136. return true;
  8137. });
  8138. }
  8139. });
  8140. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8141. auto se = detail::scope_exit([&] {
  8142. svr.stop();
  8143. t.join();
  8144. ASSERT_FALSE(svr.is_running());
  8145. });
  8146. svr.wait_until_ready();
  8147. {
  8148. std::string data(1024 * 1024 * 2, '.');
  8149. std::stringstream buffer;
  8150. buffer << data;
  8151. Client cli("https://localhost:8080");
  8152. cli.enable_server_certificate_verification(false);
  8153. UploadFormDataItems items{
  8154. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8155. {"hello", "world", "", ""},
  8156. };
  8157. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8158. ASSERT_TRUE(res);
  8159. ASSERT_EQ(StatusCode::OK_200, res->status);
  8160. }
  8161. }
  8162. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8163. std::string data(1024 * 1024 * 2, '&');
  8164. std::stringstream buffer;
  8165. buffer << data;
  8166. Client cli("https://localhost:8080");
  8167. UploadFormDataItems items{
  8168. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8169. {"hello", "world", "", ""},
  8170. };
  8171. for (const char &c : " \t\r\n") {
  8172. auto res =
  8173. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8174. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8175. ASSERT_FALSE(res);
  8176. }
  8177. }
  8178. TEST(MultipartFormDataTest, PutFormData) {
  8179. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8180. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8181. const ContentReader &content_reader) {
  8182. if (req.is_multipart_form_data()) {
  8183. std::vector<FormData> items;
  8184. content_reader(
  8185. [&](const FormData &file) {
  8186. items.push_back(file);
  8187. return true;
  8188. },
  8189. [&](const char *data, size_t data_length) {
  8190. items.back().content.append(data, data_length);
  8191. return true;
  8192. });
  8193. EXPECT_TRUE(std::string(items[0].name) == "document");
  8194. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8195. EXPECT_TRUE(items[0].filename == "2MB_data");
  8196. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8197. EXPECT_TRUE(items[1].name == "hello");
  8198. EXPECT_TRUE(items[1].content == "world");
  8199. EXPECT_TRUE(items[1].filename == "");
  8200. EXPECT_TRUE(items[1].content_type == "");
  8201. } else {
  8202. std::string body;
  8203. content_reader([&](const char *data, size_t data_length) {
  8204. body.append(data, data_length);
  8205. return true;
  8206. });
  8207. }
  8208. });
  8209. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8210. auto se = detail::scope_exit([&] {
  8211. svr.stop();
  8212. t.join();
  8213. ASSERT_FALSE(svr.is_running());
  8214. });
  8215. svr.wait_until_ready();
  8216. {
  8217. std::string data(1024 * 1024 * 2, '&');
  8218. std::stringstream buffer;
  8219. buffer << data;
  8220. Client cli("https://localhost:8080");
  8221. cli.enable_server_certificate_verification(false);
  8222. UploadFormDataItems items{
  8223. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8224. {"hello", "world", "", ""},
  8225. };
  8226. auto res = cli.Put("/put", items);
  8227. ASSERT_TRUE(res);
  8228. ASSERT_EQ(StatusCode::OK_200, res->status);
  8229. }
  8230. }
  8231. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8233. svr.Put("/put_customboundary",
  8234. [&](const Request &req, const Response & /*res*/,
  8235. const ContentReader &content_reader) {
  8236. if (req.is_multipart_form_data()) {
  8237. std::vector<FormData> items;
  8238. content_reader(
  8239. [&](const FormData &file) {
  8240. items.push_back(file);
  8241. return true;
  8242. },
  8243. [&](const char *data, size_t data_length) {
  8244. items.back().content.append(data, data_length);
  8245. return true;
  8246. });
  8247. EXPECT_TRUE(std::string(items[0].name) == "document");
  8248. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8249. EXPECT_TRUE(items[0].filename == "2MB_data");
  8250. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8251. EXPECT_TRUE(items[1].name == "hello");
  8252. EXPECT_TRUE(items[1].content == "world");
  8253. EXPECT_TRUE(items[1].filename == "");
  8254. EXPECT_TRUE(items[1].content_type == "");
  8255. } else {
  8256. std::string body;
  8257. content_reader([&](const char *data, size_t data_length) {
  8258. body.append(data, data_length);
  8259. return true;
  8260. });
  8261. }
  8262. });
  8263. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8264. auto se = detail::scope_exit([&] {
  8265. svr.stop();
  8266. t.join();
  8267. ASSERT_FALSE(svr.is_running());
  8268. });
  8269. svr.wait_until_ready();
  8270. {
  8271. std::string data(1024 * 1024 * 2, '&');
  8272. std::stringstream buffer;
  8273. buffer << data;
  8274. Client cli("https://localhost:8080");
  8275. cli.enable_server_certificate_verification(false);
  8276. UploadFormDataItems items{
  8277. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8278. {"hello", "world", "", ""},
  8279. };
  8280. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8281. ASSERT_TRUE(res);
  8282. ASSERT_EQ(StatusCode::OK_200, res->status);
  8283. }
  8284. }
  8285. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8286. std::string data(1024 * 1024 * 2, '&');
  8287. std::stringstream buffer;
  8288. buffer << data;
  8289. Client cli("https://localhost:8080");
  8290. cli.enable_server_certificate_verification(false);
  8291. UploadFormDataItems items{
  8292. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8293. {"hello", "world", "", ""},
  8294. };
  8295. for (const char &c : " \t\r\n") {
  8296. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8297. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8298. ASSERT_FALSE(res);
  8299. }
  8300. }
  8301. TEST(MultipartFormDataTest, AlternateFilename) {
  8302. auto handled = false;
  8303. Server svr;
  8304. svr.Post("/test", [&](const Request &req, Response &res) {
  8305. ASSERT_EQ(2u, req.form.files.size());
  8306. ASSERT_EQ(1u, req.form.fields.size());
  8307. // Test files
  8308. const auto &file1 = req.form.get_file("file1");
  8309. ASSERT_EQ("file1", file1.name);
  8310. ASSERT_EQ("A.txt", file1.filename);
  8311. ASSERT_EQ("text/plain", file1.content_type);
  8312. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8313. const auto &file2 = req.form.get_file("file2");
  8314. ASSERT_EQ("file2", file2.name);
  8315. ASSERT_EQ("a.html", file2.filename);
  8316. ASSERT_EQ("text/html", file2.content_type);
  8317. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8318. file2.content);
  8319. // Test text field
  8320. const auto &text = req.form.get_field("text");
  8321. ASSERT_EQ("text default", text);
  8322. res.set_content("ok", "text/plain");
  8323. handled = true;
  8324. });
  8325. thread t = thread([&] { svr.listen(HOST, PORT); });
  8326. auto se = detail::scope_exit([&] {
  8327. svr.stop();
  8328. t.join();
  8329. ASSERT_FALSE(svr.is_running());
  8330. ASSERT_TRUE(handled);
  8331. });
  8332. svr.wait_until_ready();
  8333. auto req = "POST /test HTTP/1.1\r\n"
  8334. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8335. "Content-Length: 399\r\n"
  8336. "\r\n"
  8337. "----------\r\n"
  8338. "Content-Disposition: form-data; name=\"text\"\r\n"
  8339. "\r\n"
  8340. "text default\r\n"
  8341. "----------\r\n"
  8342. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8343. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8344. "Content-Type: text/plain\r\n"
  8345. "\r\n"
  8346. "Content of a.txt.\r\n"
  8347. "\r\n"
  8348. "----------\r\n"
  8349. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8350. "\"a.html\"\r\n"
  8351. "Content-Type: text/html\r\n"
  8352. "\r\n"
  8353. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8354. "\r\n"
  8355. "------------\r\n";
  8356. ASSERT_TRUE(send_request(1, req));
  8357. }
  8358. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8359. auto handled = false;
  8360. Server svr;
  8361. svr.Post("/test", [&](const Request &req, Response &) {
  8362. ASSERT_EQ(2u, req.form.fields.size());
  8363. const auto &text1 = req.form.get_field("text1");
  8364. ASSERT_EQ("text1", text1);
  8365. const auto &text2 = req.form.get_field("text2");
  8366. ASSERT_EQ("text2", text2);
  8367. handled = true;
  8368. });
  8369. thread t = thread([&] { svr.listen(HOST, PORT); });
  8370. auto se = detail::scope_exit([&] {
  8371. svr.stop();
  8372. t.join();
  8373. ASSERT_FALSE(svr.is_running());
  8374. ASSERT_TRUE(handled);
  8375. });
  8376. svr.wait_until_ready();
  8377. auto req = "POST /test HTTP/1.1\r\n"
  8378. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8379. "Content-Length: 146\r\n"
  8380. "\r\n----------\r\n"
  8381. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8382. "\r\n"
  8383. "text1"
  8384. "\r\n----------\r\n"
  8385. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8386. "\r\n"
  8387. "text2"
  8388. "\r\n------------";
  8389. std::string response;
  8390. ASSERT_TRUE(send_request(1, req, &response));
  8391. ASSERT_EQ("200", response.substr(9, 3));
  8392. }
  8393. TEST(MultipartFormDataTest, ContentLength) {
  8394. auto handled = false;
  8395. Server svr;
  8396. svr.Post("/test", [&](const Request &req, Response &) {
  8397. ASSERT_EQ(2u, req.form.fields.size());
  8398. const auto &text1 = req.form.get_field("text1");
  8399. ASSERT_EQ("text1", text1);
  8400. const auto &text2 = req.form.get_field("text2");
  8401. ASSERT_EQ("text2", text2);
  8402. handled = true;
  8403. });
  8404. thread t = thread([&] { svr.listen(HOST, PORT); });
  8405. auto se = detail::scope_exit([&] {
  8406. svr.stop();
  8407. t.join();
  8408. ASSERT_FALSE(svr.is_running());
  8409. ASSERT_TRUE(handled);
  8410. });
  8411. svr.wait_until_ready();
  8412. auto req = "POST /test HTTP/1.1\r\n"
  8413. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8414. "Content-Length: 167\r\n"
  8415. "\r\n----------\r\n"
  8416. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8417. "Content-Length: 5\r\n"
  8418. "\r\n"
  8419. "text1"
  8420. "\r\n----------\r\n"
  8421. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8422. "\r\n"
  8423. "text2"
  8424. "\r\n------------\r\n";
  8425. std::string response;
  8426. ASSERT_TRUE(send_request(1, req, &response));
  8427. ASSERT_EQ("200", response.substr(9, 3));
  8428. }
  8429. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8430. auto handled = false;
  8431. Server svr;
  8432. svr.Post("/test", [&](const Request &req, Response &) {
  8433. ASSERT_EQ(2u, req.form.fields.size());
  8434. const auto &text1 = req.form.get_field("text1");
  8435. ASSERT_EQ("text1", text1);
  8436. // TODO: Add header access for text fields if needed
  8437. const auto &text2 = req.form.get_field("text2");
  8438. ASSERT_EQ("text2", text2);
  8439. // TODO: Header access for text fields needs to be implemented
  8440. // auto &headers = it->second.headers;
  8441. // ASSERT_EQ(3U, headers.size());
  8442. // auto custom_header = headers.find("x-whatever");
  8443. // ASSERT_TRUE(custom_header != headers.end());
  8444. // ASSERT_NE("customvalue", custom_header->second);
  8445. // ASSERT_EQ("CustomValue", custom_header->second);
  8446. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8447. handled = true;
  8448. });
  8449. thread t = thread([&] { svr.listen(HOST, PORT); });
  8450. auto se = detail::scope_exit([&] {
  8451. svr.stop();
  8452. t.join();
  8453. ASSERT_FALSE(svr.is_running());
  8454. ASSERT_TRUE(handled);
  8455. });
  8456. svr.wait_until_ready();
  8457. auto req = "POST /test HTTP/1.1\r\n"
  8458. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8459. "Content-Length: 232\r\n"
  8460. "\r\n----------\r\n"
  8461. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8462. "Content-Length: 5\r\n"
  8463. "X-Test: 1\r\n"
  8464. "\r\n"
  8465. "text1"
  8466. "\r\n----------\r\n"
  8467. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8468. "Content-Type: text/plain\r\n"
  8469. "X-Whatever: CustomValue\r\n"
  8470. "\r\n"
  8471. "text2"
  8472. "\r\n------------\r\n"
  8473. "That should be disregarded. Not even read";
  8474. std::string response;
  8475. ASSERT_TRUE(send_request(1, req, &response));
  8476. ASSERT_EQ("200", response.substr(9, 3));
  8477. }
  8478. #endif
  8479. TEST(MultipartFormDataTest, LargeHeader) {
  8480. auto handled = false;
  8481. Server svr;
  8482. svr.Post("/test", [&](const Request &req, Response &) {
  8483. ASSERT_EQ(1u, req.form.fields.size());
  8484. const auto &text = req.form.get_field("name1");
  8485. ASSERT_EQ("text1", text);
  8486. handled = true;
  8487. });
  8488. thread t = thread([&] { svr.listen(HOST, PORT); });
  8489. auto se = detail::scope_exit([&] {
  8490. svr.stop();
  8491. t.join();
  8492. ASSERT_FALSE(svr.is_running());
  8493. ASSERT_TRUE(handled);
  8494. });
  8495. svr.wait_until_ready();
  8496. auto boundary = std::string("cpp-httplib-multipart-data");
  8497. std::string content = "--" + boundary +
  8498. "\r\n"
  8499. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8500. "\r\n"
  8501. "text1\r\n"
  8502. "--" +
  8503. boundary + "--\r\n";
  8504. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8505. "Content-Type: multipart/form-data;boundary=" +
  8506. boundary +
  8507. "\r\n"
  8508. "Content-Length: " +
  8509. std::to_string(content.size()) +
  8510. "\r\n"
  8511. "Dummy-Header: ";
  8512. std::string header_suffix = "\r\n"
  8513. "\r\n";
  8514. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8515. size_t header_dummy_size =
  8516. read_buff_size -
  8517. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8518. auto header_dummy = std::string(header_dummy_size, '@');
  8519. auto req = header_prefix + header_dummy + header_suffix + content;
  8520. std::string response;
  8521. ASSERT_TRUE(send_request(1, req, &response));
  8522. ASSERT_EQ("200", response.substr(9, 3));
  8523. }
  8524. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8525. static constexpr unsigned int number_of_tasks{1000000};
  8526. std::atomic_uint count{0};
  8527. std::unique_ptr<TaskQueue> task_queue{
  8528. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8529. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8530. auto queued = task_queue->enqueue(
  8531. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8532. EXPECT_TRUE(queued);
  8533. }
  8534. EXPECT_NO_THROW(task_queue->shutdown());
  8535. EXPECT_EQ(number_of_tasks, count.load());
  8536. }
  8537. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8538. static constexpr unsigned int number_of_tasks{1000000};
  8539. static constexpr unsigned int qlimit{2};
  8540. unsigned int queued_count{0};
  8541. std::atomic_uint count{0};
  8542. std::unique_ptr<TaskQueue> task_queue{
  8543. new ThreadPool{/*num_threads=*/1, qlimit}};
  8544. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8545. if (task_queue->enqueue(
  8546. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8547. queued_count++;
  8548. }
  8549. }
  8550. EXPECT_NO_THROW(task_queue->shutdown());
  8551. EXPECT_EQ(queued_count, count.load());
  8552. EXPECT_TRUE(queued_count <= number_of_tasks);
  8553. EXPECT_TRUE(queued_count >= qlimit);
  8554. }
  8555. TEST(TaskQueueTest, MaxQueuedRequests) {
  8556. static constexpr unsigned int qlimit{3};
  8557. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8558. std::condition_variable sem_cv;
  8559. std::mutex sem_mtx;
  8560. int credits = 0;
  8561. bool queued;
  8562. /* Fill up the queue with tasks that will block until we give them credits to
  8563. * complete. */
  8564. for (unsigned int n = 0; n <= qlimit;) {
  8565. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8566. std::unique_lock<std::mutex> lock(sem_mtx);
  8567. while (credits <= 0) {
  8568. sem_cv.wait(lock);
  8569. }
  8570. /* Consume the credit and signal the test code if they are all gone. */
  8571. if (--credits == 0) { sem_cv.notify_one(); }
  8572. });
  8573. if (n < qlimit) {
  8574. /* The first qlimit enqueues must succeed. */
  8575. EXPECT_TRUE(queued);
  8576. } else {
  8577. /* The last one will succeed only when the worker thread
  8578. * starts and dequeues the first blocking task. Although
  8579. * not necessary for the correctness of this test, we sleep for
  8580. * a short while to avoid busy waiting. */
  8581. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8582. }
  8583. if (queued) { n++; }
  8584. }
  8585. /* Further enqueues must fail since the queue is full. */
  8586. for (auto i = 0; i < 4; i++) {
  8587. queued = task_queue->enqueue([] {});
  8588. EXPECT_FALSE(queued);
  8589. }
  8590. /* Give the credits to allow the previous tasks to complete. */
  8591. {
  8592. std::unique_lock<std::mutex> lock(sem_mtx);
  8593. credits += qlimit + 1;
  8594. }
  8595. sem_cv.notify_all();
  8596. /* Wait for all the credits to be consumed. */
  8597. {
  8598. std::unique_lock<std::mutex> lock(sem_mtx);
  8599. while (credits > 0) {
  8600. sem_cv.wait(lock);
  8601. }
  8602. }
  8603. /* Check that we are able again to enqueue at least qlimit tasks. */
  8604. for (unsigned int i = 0; i < qlimit; i++) {
  8605. queued = task_queue->enqueue([] {});
  8606. EXPECT_TRUE(queued);
  8607. }
  8608. EXPECT_NO_THROW(task_queue->shutdown());
  8609. }
  8610. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8611. Server svr;
  8612. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8613. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8614. });
  8615. svr.Get("/hello", [](const Request &req, Response &res) {
  8616. res.set_content(req.get_param_value("key"), "text/plain");
  8617. });
  8618. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8619. auto se = detail::scope_exit([&] {
  8620. svr.stop();
  8621. thread.join();
  8622. ASSERT_FALSE(svr.is_running());
  8623. });
  8624. svr.wait_until_ready();
  8625. {
  8626. Client cli(HOST, PORT);
  8627. cli.set_follow_location(true);
  8628. auto res = cli.Get("/");
  8629. ASSERT_TRUE(res);
  8630. EXPECT_EQ(StatusCode::OK_200, res->status);
  8631. EXPECT_EQ("val&key2=val2", res->body);
  8632. }
  8633. }
  8634. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8635. Server svr;
  8636. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8637. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8638. });
  8639. svr.Get("/hello", [](const Request &req, Response &res) {
  8640. res.set_content(req.get_param_value("key"), "text/plain");
  8641. });
  8642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8643. auto se = detail::scope_exit([&] {
  8644. svr.stop();
  8645. thread.join();
  8646. ASSERT_FALSE(svr.is_running());
  8647. });
  8648. svr.wait_until_ready();
  8649. {
  8650. Client cli(HOST, PORT);
  8651. cli.set_follow_location(true);
  8652. auto res = cli.Get("/");
  8653. ASSERT_TRUE(res);
  8654. EXPECT_EQ(StatusCode::OK_200, res->status);
  8655. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8656. }
  8657. }
  8658. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8659. TEST(RedirectTest, Issue2185_Online) {
  8660. SSLClient client("github.com");
  8661. client.set_follow_location(true);
  8662. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8663. "Coollab-Windows.zip");
  8664. ASSERT_TRUE(res);
  8665. EXPECT_EQ(StatusCode::OK_200, res->status);
  8666. EXPECT_EQ(9920427U, res->body.size());
  8667. }
  8668. #endif
  8669. TEST(VulnerabilityTest, CRLFInjection) {
  8670. Server svr;
  8671. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8672. res.set_content("Hello 1", "text/plain");
  8673. });
  8674. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8675. res.set_content("Hello 2", "text/plain");
  8676. });
  8677. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8678. res.set_content("Hello 3", "text/plain");
  8679. });
  8680. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8681. res.set_content("Hello 4", "text/plain");
  8682. });
  8683. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8684. for (const auto &x : req.headers) {
  8685. auto key = x.first;
  8686. EXPECT_STRNE("evil", key.c_str());
  8687. }
  8688. });
  8689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8690. auto se = detail::scope_exit([&] {
  8691. svr.stop();
  8692. thread.join();
  8693. ASSERT_FALSE(svr.is_running());
  8694. });
  8695. svr.wait_until_ready();
  8696. {
  8697. Client cli(HOST, PORT);
  8698. cli.Post("/test1", "A=B",
  8699. "application/x-www-form-urlencoded\r\nevil: hello1");
  8700. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8701. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8702. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8703. }
  8704. }
  8705. TEST(PathParamsTest, StaticMatch) {
  8706. const auto pattern = "/users/all";
  8707. detail::PathParamsMatcher matcher(pattern);
  8708. Request request;
  8709. request.path = "/users/all";
  8710. ASSERT_TRUE(matcher.match(request));
  8711. std::unordered_map<std::string, std::string> expected_params = {};
  8712. EXPECT_EQ(request.path_params, expected_params);
  8713. }
  8714. TEST(PathParamsTest, StaticMismatch) {
  8715. const auto pattern = "/users/all";
  8716. detail::PathParamsMatcher matcher(pattern);
  8717. Request request;
  8718. request.path = "/users/1";
  8719. ASSERT_FALSE(matcher.match(request));
  8720. }
  8721. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8722. const auto pattern = "/users/:id/subscriptions";
  8723. detail::PathParamsMatcher matcher(pattern);
  8724. Request request;
  8725. request.path = "/users/42/subscriptions";
  8726. ASSERT_TRUE(matcher.match(request));
  8727. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8728. EXPECT_EQ(request.path_params, expected_params);
  8729. }
  8730. TEST(PathParamsTest, SingleParamInTheEnd) {
  8731. const auto pattern = "/users/:id";
  8732. detail::PathParamsMatcher matcher(pattern);
  8733. Request request;
  8734. request.path = "/users/24";
  8735. ASSERT_TRUE(matcher.match(request));
  8736. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8737. EXPECT_EQ(request.path_params, expected_params);
  8738. }
  8739. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8740. const auto pattern = "/users/:id/";
  8741. detail::PathParamsMatcher matcher(pattern);
  8742. Request request;
  8743. request.path = "/users/42/";
  8744. ASSERT_TRUE(matcher.match(request));
  8745. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8746. EXPECT_EQ(request.path_params, expected_params);
  8747. }
  8748. TEST(PathParamsTest, EmptyParam) {
  8749. const auto pattern = "/users/:id/";
  8750. detail::PathParamsMatcher matcher(pattern);
  8751. Request request;
  8752. request.path = "/users//";
  8753. ASSERT_TRUE(matcher.match(request));
  8754. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8755. EXPECT_EQ(request.path_params, expected_params);
  8756. }
  8757. TEST(PathParamsTest, FragmentMismatch) {
  8758. const auto pattern = "/users/:id/";
  8759. detail::PathParamsMatcher matcher(pattern);
  8760. Request request;
  8761. request.path = "/admins/24/";
  8762. ASSERT_FALSE(matcher.match(request));
  8763. }
  8764. TEST(PathParamsTest, ExtraFragments) {
  8765. const auto pattern = "/users/:id";
  8766. detail::PathParamsMatcher matcher(pattern);
  8767. Request request;
  8768. request.path = "/users/42/subscriptions";
  8769. ASSERT_FALSE(matcher.match(request));
  8770. }
  8771. TEST(PathParamsTest, MissingTrailingParam) {
  8772. const auto pattern = "/users/:id";
  8773. detail::PathParamsMatcher matcher(pattern);
  8774. Request request;
  8775. request.path = "/users";
  8776. ASSERT_FALSE(matcher.match(request));
  8777. }
  8778. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8779. const auto pattern = "/users/:id/subscriptions";
  8780. detail::PathParamsMatcher matcher(pattern);
  8781. Request request;
  8782. request.path = "/users/subscriptions";
  8783. ASSERT_FALSE(matcher.match(request));
  8784. }
  8785. TEST(PathParamsTest, MultipleParams) {
  8786. const auto pattern = "/users/:userid/subscriptions/:subid";
  8787. detail::PathParamsMatcher matcher(pattern);
  8788. Request request;
  8789. request.path = "/users/42/subscriptions/2";
  8790. ASSERT_TRUE(matcher.match(request));
  8791. std::unordered_map<std::string, std::string> expected_params = {
  8792. {"userid", "42"}, {"subid", "2"}};
  8793. EXPECT_EQ(request.path_params, expected_params);
  8794. }
  8795. TEST(PathParamsTest, SequenceOfParams) {
  8796. const auto pattern = "/values/:x/:y/:z";
  8797. detail::PathParamsMatcher matcher(pattern);
  8798. Request request;
  8799. request.path = "/values/1/2/3";
  8800. ASSERT_TRUE(matcher.match(request));
  8801. std::unordered_map<std::string, std::string> expected_params = {
  8802. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8803. EXPECT_EQ(request.path_params, expected_params);
  8804. }
  8805. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8806. const auto pattern = "/prefix:suffix";
  8807. detail::PathParamsMatcher matcher(pattern);
  8808. Request request;
  8809. request.path = "/prefix:suffix";
  8810. ASSERT_TRUE(matcher.match(request));
  8811. const std::unordered_map<std::string, std::string> expected_params = {};
  8812. EXPECT_EQ(request.path_params, expected_params);
  8813. }
  8814. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8815. // If ipv6 regex working, regex match codepath is taken.
  8816. // else port will default to 80 in Client impl
  8817. int clientImplMagicPort = 80;
  8818. int port = 4321;
  8819. // above ports must be different to avoid false negative
  8820. EXPECT_NE(clientImplMagicPort, port);
  8821. std::string ipV6TestURL = "http://[ff06::c3]";
  8822. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8823. CLIENT_PRIVATE_KEY_FILE);
  8824. EXPECT_EQ(cli.port(), port);
  8825. }
  8826. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8827. auto file_path = "./www/dir/index.html";
  8828. auto dir_path = "./www/dir";
  8829. detail::FileStat stat_file(file_path);
  8830. EXPECT_TRUE(stat_file.is_file());
  8831. EXPECT_FALSE(stat_file.is_dir());
  8832. detail::FileStat stat_dir(dir_path);
  8833. EXPECT_FALSE(stat_dir.is_file());
  8834. EXPECT_TRUE(stat_dir.is_dir());
  8835. }
  8836. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  8837. // IPv4 with default HTTP port (80)
  8838. EXPECT_EQ("example.com",
  8839. detail::make_host_and_port_string("example.com", 80, false));
  8840. // IPv4 with default HTTPS port (443)
  8841. EXPECT_EQ("example.com",
  8842. detail::make_host_and_port_string("example.com", 443, true));
  8843. // IPv4 with non-default HTTP port
  8844. EXPECT_EQ("example.com:8080",
  8845. detail::make_host_and_port_string("example.com", 8080, false));
  8846. // IPv4 with non-default HTTPS port
  8847. EXPECT_EQ("example.com:8443",
  8848. detail::make_host_and_port_string("example.com", 8443, true));
  8849. // IPv6 with default HTTP port (80)
  8850. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  8851. // IPv6 with default HTTPS port (443)
  8852. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  8853. // IPv6 with non-default HTTP port
  8854. EXPECT_EQ("[::1]:8080",
  8855. detail::make_host_and_port_string("::1", 8080, false));
  8856. // IPv6 with non-default HTTPS port
  8857. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  8858. // IPv6 full address with default port
  8859. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  8860. detail::make_host_and_port_string(
  8861. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  8862. // IPv6 full address with non-default port
  8863. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  8864. detail::make_host_and_port_string(
  8865. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  8866. // IPv6 localhost with non-default port
  8867. EXPECT_EQ("[::1]:3000",
  8868. detail::make_host_and_port_string("::1", 3000, false));
  8869. // IPv6 with zone ID (link-local address) with default port
  8870. EXPECT_EQ("[fe80::1%eth0]",
  8871. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  8872. // IPv6 with zone ID (link-local address) with non-default port
  8873. EXPECT_EQ("[fe80::1%eth0]:8080",
  8874. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  8875. // Edge case: Port 443 with is_ssl=false (should add port)
  8876. EXPECT_EQ("example.com:443",
  8877. detail::make_host_and_port_string("example.com", 443, false));
  8878. // Edge case: Port 80 with is_ssl=true (should add port)
  8879. EXPECT_EQ("example.com:80",
  8880. detail::make_host_and_port_string("example.com", 80, true));
  8881. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  8882. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  8883. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  8884. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  8885. // Security fix: Already bracketed IPv6 should not get double brackets
  8886. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  8887. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  8888. EXPECT_EQ("[::1]:8080",
  8889. detail::make_host_and_port_string("[::1]", 8080, false));
  8890. EXPECT_EQ("[2001:db8::1]:8080",
  8891. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  8892. EXPECT_EQ("[fe80::1%eth0]",
  8893. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  8894. EXPECT_EQ("[fe80::1%eth0]:8080",
  8895. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  8896. // Edge case: Empty host (should return as-is)
  8897. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  8898. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  8899. // This is a known limitation but shouldn't crash
  8900. EXPECT_EQ("[host:name]",
  8901. detail::make_host_and_port_string("host:name", 80, false));
  8902. // Port number edge cases (no validation, but should not crash)
  8903. EXPECT_EQ("example.com:0",
  8904. detail::make_host_and_port_string("example.com", 0, false));
  8905. EXPECT_EQ("example.com:-1",
  8906. detail::make_host_and_port_string("example.com", -1, false));
  8907. EXPECT_EQ("example.com:65535",
  8908. detail::make_host_and_port_string("example.com", 65535, false));
  8909. EXPECT_EQ("example.com:65536",
  8910. detail::make_host_and_port_string("example.com", 65536, false));
  8911. }
  8912. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8913. Server svr;
  8914. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8915. EXPECT_EQ(res.status, 400);
  8916. });
  8917. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8918. auto se = detail::scope_exit([&] {
  8919. svr.stop();
  8920. thread.join();
  8921. ASSERT_FALSE(svr.is_running());
  8922. });
  8923. svr.wait_until_ready();
  8924. Client cli(HOST, PORT);
  8925. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8926. }
  8927. TEST(InvalidHeaderCharsTest, is_field_name) {
  8928. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8929. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8930. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8931. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8932. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8933. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8934. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8935. EXPECT_FALSE(detail::fields::is_field_name(""));
  8936. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8937. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8938. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8939. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8940. }
  8941. TEST(InvalidHeaderCharsTest, is_field_value) {
  8942. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8943. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8944. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8945. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8946. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8947. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8948. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8949. EXPECT_TRUE(detail::fields::is_field_value(""));
  8950. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8951. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8952. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8953. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8954. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8955. }
  8956. TEST(InvalidHeaderCharsTest, OnServer) {
  8957. Server svr;
  8958. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8959. std::string header = "Not Set";
  8960. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8961. res.set_header(header, "value");
  8962. res.set_content("Page Content Page Content", "text/plain");
  8963. });
  8964. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8965. std::string header = "Not Set";
  8966. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8967. res.set_header("X-Test", header);
  8968. res.set_content("Page Content Page Content", "text/plain");
  8969. });
  8970. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8971. auto se = detail::scope_exit([&] {
  8972. svr.stop();
  8973. thread.join();
  8974. ASSERT_FALSE(svr.is_running());
  8975. });
  8976. svr.wait_until_ready();
  8977. Client cli(HOST, PORT);
  8978. {
  8979. auto res = cli.Get(
  8980. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8981. ASSERT_TRUE(res);
  8982. EXPECT_EQ("Page Content Page Content", res->body);
  8983. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8984. }
  8985. {
  8986. auto res = cli.Get(
  8987. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8988. ASSERT_TRUE(res);
  8989. EXPECT_EQ("Page Content Page Content", res->body);
  8990. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8991. }
  8992. }
  8993. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8994. auto handled = false;
  8995. Server svr;
  8996. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8997. thread t = thread([&] { svr.listen(HOST, PORT); });
  8998. auto se = detail::scope_exit([&] {
  8999. svr.stop();
  9000. t.join();
  9001. ASSERT_FALSE(svr.is_running());
  9002. ASSERT_FALSE(handled);
  9003. });
  9004. svr.wait_until_ready();
  9005. auto req = "POST /test HTTP/1.1\r\n"
  9006. "Content-Length: x\r\n"
  9007. "\r\n";
  9008. std::string response;
  9009. ASSERT_TRUE(send_request(1, req, &response));
  9010. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9011. response.substr(0, response.find("\r\n")));
  9012. }
  9013. #ifndef _WIN32
  9014. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9015. static constexpr char reject[] = "Unauthorized";
  9016. static constexpr char accept[] = "Upload accepted";
  9017. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9018. Server svr;
  9019. svr.set_expect_100_continue_handler(
  9020. [](const Request & /*req*/, Response &res) {
  9021. res.status = StatusCode::Unauthorized_401;
  9022. res.set_content(reject, "text/plain");
  9023. return res.status;
  9024. });
  9025. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9026. res.set_content(accept, "text/plain");
  9027. });
  9028. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9029. auto se = detail::scope_exit([&] {
  9030. svr.stop();
  9031. thread.join();
  9032. ASSERT_FALSE(svr.is_running());
  9033. });
  9034. svr.wait_until_ready();
  9035. {
  9036. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9037. curl_easy_init(), &curl_easy_cleanup};
  9038. ASSERT_NE(curl, nullptr);
  9039. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9040. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9041. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9042. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9043. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9044. &curl_slist_free_all};
  9045. ASSERT_NE(list, nullptr);
  9046. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9047. struct read_data {
  9048. size_t read_size;
  9049. size_t total_size;
  9050. } data = {0, total_size};
  9051. using read_callback_t =
  9052. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9053. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9054. void *userdata) -> size_t {
  9055. read_data *data = (read_data *)userdata;
  9056. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9057. std::fill_n(ptr, size * nmemb, 'A');
  9058. data->read_size += size * nmemb;
  9059. return size * nmemb;
  9060. };
  9061. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9062. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9063. std::vector<char> buffer;
  9064. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9065. using write_callback_t =
  9066. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9067. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9068. void *userdata) -> size_t {
  9069. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9070. buffer->reserve(buffer->size() + size * nmemb + 1);
  9071. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9072. return size * nmemb;
  9073. };
  9074. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9075. {
  9076. const auto res = curl_easy_perform(curl.get());
  9077. ASSERT_EQ(res, CURLE_OK);
  9078. }
  9079. {
  9080. auto response_code = long{};
  9081. const auto res =
  9082. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9083. ASSERT_EQ(res, CURLE_OK);
  9084. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9085. }
  9086. {
  9087. auto dl = curl_off_t{};
  9088. const auto res =
  9089. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9090. ASSERT_EQ(res, CURLE_OK);
  9091. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9092. }
  9093. {
  9094. buffer.push_back('\0');
  9095. ASSERT_STRCASEEQ(buffer.data(), reject);
  9096. }
  9097. }
  9098. }
  9099. #endif
  9100. template <typename S, typename C>
  9101. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9102. svr.Get("/stream", [&](const Request &, Response &res) {
  9103. auto data = new std::string("01234567890123456789");
  9104. res.set_content_provider(
  9105. data->size(), "text/plain",
  9106. [&, data](size_t offset, size_t length, DataSink &sink) {
  9107. const size_t DATA_CHUNK_SIZE = 4;
  9108. const auto &d = *data;
  9109. std::this_thread::sleep_for(std::chrono::seconds(1));
  9110. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9111. return true;
  9112. },
  9113. [data](bool success) {
  9114. EXPECT_FALSE(success);
  9115. delete data;
  9116. });
  9117. });
  9118. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9119. auto i = new size_t(0);
  9120. res.set_content_provider(
  9121. "text/plain",
  9122. [i](size_t, DataSink &sink) {
  9123. if (*i < 5) {
  9124. std::this_thread::sleep_for(std::chrono::seconds(1));
  9125. sink.write("abcd", 4);
  9126. (*i)++;
  9127. } else {
  9128. sink.done();
  9129. }
  9130. return true;
  9131. },
  9132. [i](bool success) {
  9133. EXPECT_FALSE(success);
  9134. delete i;
  9135. });
  9136. });
  9137. svr.Get("/chunked", [&](const Request &, Response &res) {
  9138. auto i = new size_t(0);
  9139. res.set_chunked_content_provider(
  9140. "text/plain",
  9141. [i](size_t, DataSink &sink) {
  9142. if (*i < 5) {
  9143. std::this_thread::sleep_for(std::chrono::seconds(1));
  9144. sink.os << "abcd";
  9145. (*i)++;
  9146. } else {
  9147. sink.done();
  9148. }
  9149. return true;
  9150. },
  9151. [i](bool success) {
  9152. EXPECT_FALSE(success);
  9153. delete i;
  9154. });
  9155. });
  9156. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9157. auto se = detail::scope_exit([&] {
  9158. svr.stop();
  9159. listen_thread.join();
  9160. ASSERT_FALSE(svr.is_running());
  9161. });
  9162. svr.wait_until_ready();
  9163. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9164. {
  9165. auto start = std::chrono::steady_clock::now();
  9166. auto res = cli.Get("/stream");
  9167. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9168. std::chrono::steady_clock::now() - start)
  9169. .count();
  9170. ASSERT_FALSE(res);
  9171. EXPECT_EQ(Error::Read, res.error());
  9172. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9173. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9174. }
  9175. {
  9176. auto start = std::chrono::steady_clock::now();
  9177. auto res = cli.Get("/stream_without_length");
  9178. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9179. std::chrono::steady_clock::now() - start)
  9180. .count();
  9181. ASSERT_FALSE(res);
  9182. EXPECT_EQ(Error::Read, res.error());
  9183. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9184. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9185. }
  9186. {
  9187. auto start = std::chrono::steady_clock::now();
  9188. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9189. EXPECT_EQ("abcd", string(data, data_length));
  9190. return true;
  9191. });
  9192. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9193. std::chrono::steady_clock::now() - start)
  9194. .count();
  9195. ASSERT_FALSE(res);
  9196. EXPECT_EQ(Error::Read, res.error());
  9197. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9198. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9199. }
  9200. }
  9201. TEST(MaxTimeoutTest, ContentStream) {
  9202. time_t timeout = 2000;
  9203. time_t threshold = 200;
  9204. Server svr;
  9205. Client cli("localhost", PORT);
  9206. max_timeout_test(svr, cli, timeout, threshold);
  9207. }
  9208. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9209. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9210. time_t timeout = 2000;
  9211. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9212. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9213. SSLClient cli("localhost", PORT);
  9214. cli.enable_server_certificate_verification(false);
  9215. max_timeout_test(svr, cli, timeout, threshold);
  9216. }
  9217. #endif
  9218. class EventDispatcher {
  9219. public:
  9220. EventDispatcher() {}
  9221. bool wait_event(DataSink *sink) {
  9222. unique_lock<mutex> lk(m_);
  9223. int id = id_;
  9224. // Wait with timeout to prevent hanging if client disconnects
  9225. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9226. [&] { return cid_ == id; })) {
  9227. return false; // Timeout occurred
  9228. }
  9229. sink->write(message_.data(), message_.size());
  9230. return true;
  9231. }
  9232. void send_event(const string &message) {
  9233. lock_guard<mutex> lk(m_);
  9234. cid_ = id_++;
  9235. message_ = message;
  9236. cv_.notify_all();
  9237. }
  9238. private:
  9239. mutex m_;
  9240. condition_variable cv_;
  9241. atomic_int id_{0};
  9242. atomic_int cid_{-1};
  9243. string message_;
  9244. };
  9245. TEST(ClientInThreadTest, Issue2068) {
  9246. EventDispatcher ed;
  9247. Server svr;
  9248. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9249. res.set_chunked_content_provider("text/event-stream",
  9250. [&](size_t /*offset*/, DataSink &sink) {
  9251. return ed.wait_event(&sink);
  9252. });
  9253. });
  9254. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9255. svr.wait_until_ready();
  9256. thread event_thread([&] {
  9257. int id = 0;
  9258. while (svr.is_running()) {
  9259. this_thread::sleep_for(chrono::milliseconds(500));
  9260. std::stringstream ss;
  9261. ss << "data: " << id << "\n\n";
  9262. ed.send_event(ss.str());
  9263. id++;
  9264. }
  9265. });
  9266. auto se = detail::scope_exit([&] {
  9267. svr.stop();
  9268. listen_thread.join();
  9269. event_thread.join();
  9270. ASSERT_FALSE(svr.is_running());
  9271. });
  9272. {
  9273. auto client = detail::make_unique<Client>(HOST, PORT);
  9274. client->set_read_timeout(std::chrono::minutes(10));
  9275. std::atomic<bool> stop{false};
  9276. std::thread t([&] {
  9277. client->Get("/event1",
  9278. [&](const char *, size_t) -> bool { return !stop; });
  9279. });
  9280. std::this_thread::sleep_for(std::chrono::seconds(2));
  9281. stop = true;
  9282. client->stop();
  9283. t.join();
  9284. // Reset client after thread has finished
  9285. client.reset();
  9286. }
  9287. }
  9288. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9289. Server svr;
  9290. svr.Get("/", [](const Request &req, Response &res) {
  9291. EXPECT_EQ(2U, req.trailers.size());
  9292. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9293. // Denied
  9294. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9295. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9296. // Accepted
  9297. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9298. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9299. EXPECT_TRUE(req.has_trailer("X-World"));
  9300. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9301. res.set_content("ok", "text/plain");
  9302. });
  9303. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9304. auto se = detail::scope_exit([&] {
  9305. svr.stop();
  9306. t.join();
  9307. ASSERT_FALSE(svr.is_running());
  9308. });
  9309. svr.wait_until_ready();
  9310. const std::string req = "GET / HTTP/1.1\r\n"
  9311. "Transfer-Encoding: chunked\r\n"
  9312. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9313. "\r\n"
  9314. "0\r\n"
  9315. "Content-Length: 10\r\n"
  9316. "Host: internal.local\r\n"
  9317. "Content-Type: malicious/content\r\n"
  9318. "Cookie: any\r\n"
  9319. "Set-Cookie: any\r\n"
  9320. "X-Forwarded-For: attacker.com\r\n"
  9321. "X-Real-Ip: 1.1.1.1\r\n"
  9322. "X-Hello: hello\r\n"
  9323. "X-World: world\r\n"
  9324. "\r\n";
  9325. std::string res;
  9326. ASSERT_TRUE(send_request(1, req, &res));
  9327. }
  9328. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9329. Server svr;
  9330. std::string observed_remote_addr;
  9331. std::string observed_xff;
  9332. svr.Get("/ip", [&](const Request &req, Response &res) {
  9333. observed_remote_addr = req.remote_addr;
  9334. observed_xff = req.get_header_value("X-Forwarded-For");
  9335. res.set_content("ok", "text/plain");
  9336. });
  9337. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9338. auto se = detail::scope_exit([&] {
  9339. svr.stop();
  9340. t.join();
  9341. ASSERT_FALSE(svr.is_running());
  9342. });
  9343. svr.wait_until_ready();
  9344. Client cli(HOST, PORT);
  9345. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9346. ASSERT_TRUE(res);
  9347. EXPECT_EQ(StatusCode::OK_200, res->status);
  9348. EXPECT_EQ(observed_xff, "203.0.113.66");
  9349. EXPECT_TRUE(observed_remote_addr == "::1" || observed_remote_addr == "127.0.0.1");
  9350. }
  9351. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9352. Server svr;
  9353. svr.set_trusted_proxies({"203.0.113.66"});
  9354. std::string observed_remote_addr;
  9355. std::string observed_xff;
  9356. svr.Get("/ip", [&](const Request &req, Response &res) {
  9357. observed_remote_addr = req.remote_addr;
  9358. observed_xff = req.get_header_value("X-Forwarded-For");
  9359. res.set_content("ok", "text/plain");
  9360. });
  9361. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9362. auto se = detail::scope_exit([&] {
  9363. svr.stop();
  9364. t.join();
  9365. ASSERT_FALSE(svr.is_running());
  9366. });
  9367. svr.wait_until_ready();
  9368. Client cli(HOST, PORT);
  9369. auto res = cli.Get("/ip");
  9370. ASSERT_TRUE(res);
  9371. EXPECT_EQ(StatusCode::OK_200, res->status);
  9372. EXPECT_EQ(observed_xff, "");
  9373. EXPECT_TRUE(observed_remote_addr == "::1" || observed_remote_addr == "127.0.0.1");
  9374. }
  9375. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9376. Server svr;
  9377. svr.set_trusted_proxies({"203.0.113.66"});
  9378. std::string observed_remote_addr;
  9379. std::string observed_xff;
  9380. svr.Get("/ip", [&](const Request &req, Response &res) {
  9381. observed_remote_addr = req.remote_addr;
  9382. observed_xff = req.get_header_value("X-Forwarded-For");
  9383. res.set_content("ok", "text/plain");
  9384. });
  9385. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9386. auto se = detail::scope_exit([&] {
  9387. svr.stop();
  9388. t.join();
  9389. ASSERT_FALSE(svr.is_running());
  9390. });
  9391. svr.wait_until_ready();
  9392. Client cli(HOST, PORT);
  9393. auto res = cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9394. ASSERT_TRUE(res);
  9395. EXPECT_EQ(StatusCode::OK_200, res->status);
  9396. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9397. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9398. }
  9399. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9400. Server svr;
  9401. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9402. std::string observed_remote_addr;
  9403. std::string observed_xff;
  9404. svr.Get("/ip", [&](const Request &req, Response &res) {
  9405. observed_remote_addr = req.remote_addr;
  9406. observed_xff = req.get_header_value("X-Forwarded-For");
  9407. res.set_content("ok", "text/plain");
  9408. });
  9409. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9410. auto se = detail::scope_exit([&] {
  9411. svr.stop();
  9412. t.join();
  9413. ASSERT_FALSE(svr.is_running());
  9414. });
  9415. svr.wait_until_ready();
  9416. Client cli(HOST, PORT);
  9417. auto res = cli.Get(
  9418. "/ip",
  9419. {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9420. ASSERT_TRUE(res);
  9421. EXPECT_EQ(StatusCode::OK_200, res->status);
  9422. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9423. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9424. }
  9425. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9426. Server svr;
  9427. svr.set_trusted_proxies({"192.0.2.45"});
  9428. std::string observed_remote_addr;
  9429. std::string observed_xff;
  9430. svr.Get("/ip", [&](const Request &req, Response &res) {
  9431. observed_remote_addr = req.remote_addr;
  9432. observed_xff = req.get_header_value("X-Forwarded-For");
  9433. res.set_content("ok", "text/plain");
  9434. });
  9435. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9436. auto se = detail::scope_exit([&] {
  9437. svr.stop();
  9438. t.join();
  9439. ASSERT_FALSE(svr.is_running());
  9440. });
  9441. svr.wait_until_ready();
  9442. Client cli(HOST, PORT);
  9443. auto res = cli.Get("/ip",
  9444. {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9445. ASSERT_TRUE(res);
  9446. EXPECT_EQ(StatusCode::OK_200, res->status);
  9447. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9448. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9449. }
  9450. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9451. Server svr;
  9452. svr.set_trusted_proxies({"192.0.2.45"});
  9453. std::string observed_remote_addr;
  9454. std::string observed_xff;
  9455. svr.Get("/ip", [&](const Request &req, Response &res) {
  9456. observed_remote_addr = req.remote_addr;
  9457. observed_xff = req.get_header_value("X-Forwarded-For");
  9458. res.set_content("ok", "text/plain");
  9459. });
  9460. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9461. auto se = detail::scope_exit([&] {
  9462. svr.stop();
  9463. t.join();
  9464. ASSERT_FALSE(svr.is_running());
  9465. });
  9466. svr.wait_until_ready();
  9467. Client cli(HOST, PORT);
  9468. auto res = cli.Get(
  9469. "/ip",
  9470. {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9471. ASSERT_TRUE(res);
  9472. EXPECT_EQ(StatusCode::OK_200, res->status);
  9473. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9474. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9475. }
  9476. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9477. Server svr;
  9478. svr.set_trusted_proxies({"192.0.2.45"});
  9479. std::string observed_remote_addr;
  9480. std::string observed_xff;
  9481. svr.Get("/ip", [&](const Request &req, Response &res) {
  9482. observed_remote_addr = req.remote_addr;
  9483. observed_xff = req.get_header_value("X-Forwarded-For");
  9484. res.set_content("ok", "text/plain");
  9485. });
  9486. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9487. auto se = detail::scope_exit([&] {
  9488. svr.stop();
  9489. t.join();
  9490. ASSERT_FALSE(svr.is_running());
  9491. });
  9492. svr.wait_until_ready();
  9493. Client cli(HOST, PORT);
  9494. auto res = cli.Get(
  9495. "/ip",
  9496. {{"X-Forwarded-For", " 198.51.100.23 , 203.0.113.66 , 192.0.2.45 "}});
  9497. ASSERT_TRUE(res);
  9498. EXPECT_EQ(StatusCode::OK_200, res->status);
  9499. // Header parser trims surrounding whitespace of the header value
  9500. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9501. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9502. }